instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>So what I'm looking for here is something like PHP's <a href="http://us2.php.net/print_r" rel="noreferrer">print_r</a> function.</p> <p>This is so I can debug my scripts by seeing what's the state of the object in question.</p>
<p>You are really mixing together two different things.</p> <p>Use <a href="https://docs.python.org/3/library/functions.html#dir" rel="noreferrer"><code>dir()</code></a>, <a href="https://docs.python.org/3/library/functions.html#vars" rel="noreferrer"><code>vars()</code></a> or the <a href="https://docs.python.org/3/library/inspect.html" rel="noreferrer"><code>inspect</code></a> module to get what you are interested in (I use <code>__builtins__</code> as an example; you can use any object instead).</p> <pre><code>&gt;&gt;&gt; l = dir(__builtins__) &gt;&gt;&gt; d = __builtins__.__dict__ </code></pre> <p>Print that dictionary however fancy you like:</p> <pre><code>&gt;&gt;&gt; print l ['ArithmeticError', 'AssertionError', 'AttributeError',... </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(l) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... &gt;&gt;&gt; pprint(d, indent=2) { 'ArithmeticError': &lt;type 'exceptions.ArithmeticError'&gt;, 'AssertionError': &lt;type 'exceptions.AssertionError'&gt;, 'AttributeError': &lt;type 'exceptions.AttributeError'&gt;, ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... </code></pre> <p>Pretty printing is also available in the interactive debugger as a command:</p> <pre><code>(Pdb) pp vars() {'__builtins__': {'ArithmeticError': &lt;type 'exceptions.ArithmeticError'&gt;, 'AssertionError': &lt;type 'exceptions.AssertionError'&gt;, 'AttributeError': &lt;type 'exceptions.AttributeError'&gt;, 'BaseException': &lt;type 'exceptions.BaseException'&gt;, 'BufferError': &lt;type 'exceptions.BufferError'&gt;, ... 'zip': &lt;built-in function zip&gt;}, '__file__': 'pass.py', '__name__': '__main__'} </code></pre>
<p>I like working with python object built-in types <a href="https://docs.python.org/2/library/stdtypes.html?highlight=keys#dict.keys" rel="nofollow noreferrer">keys</a> or <a href="https://docs.python.org/2/library/stdtypes.html?highlight=keys#dict.values" rel="nofollow noreferrer">values</a>. </p> <p>For attributes regardless they are methods or variables: </p> <pre><code>o.keys() </code></pre> <p>For values of those attributes:</p> <pre><code>o.values() </code></pre>
23,345
<p>There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?</p> <p>I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.</p> <p>I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.</p>
<p>You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.</p> <p>Java code example:</p> <pre><code>Integer[] idx = new Integer[numbers.length]; for( int i = 0 ; i &lt; idx.length; i++ ) idx[i] = i; Arrays.sort(idx, new Comparator&lt;Integer&gt;() { public int compare(Integer i1, Integer i2) { return Double.compare(numbers[i1], numbers[i2]); } }); // numbers[idx[i]] is the sorted number at index i // colors[idx[i]] is the sorted color at index i </code></pre> <p>Note that you have to use <code>Integer</code> instead of <code>int</code> or you can't use a custom comparator. </p>
<p>You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares numbers and use that as the comparison for the colors array.</p>
13,739
<p>I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.</p> <p>Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?</p>
<pre><code>header('Content-type: application/xml'); </code></pre> <p>More information available at the PHP documentation for <a href="http://php.net/manual/en/function.header.php" rel="noreferrer"><code>header()</code></a></p>
<p>I just used the following:<br> NOTE: I am using "i" for sql improved extension. </p> <pre><code>Start XML file, echo parent node header("Content-type: text/xml"); echo "&lt;?xml version='1.0' encoding='UTF-8'?&gt;"; echo "&lt;marker&gt;"; </code></pre> <p>Iterate through the rows, printing XML nodes for each</p> <pre><code>while ($row = @mysqli_fetch_assoc($results)){ // Add to XML document node echo '&lt;marker '; echo 'id="' . $ind . '" '; echo 'name="' . parseToXML($row['name']) . '" '; echo 'address="' . parseToXML($row['address']) . '" '; echo 'lat="' . $row['lat'] . '" '; echo 'lng="' . $row['lng'] . '" '; echo 'type="' . $row['type'] . '" '; echo '/&gt;'; } // End XML file echo "&lt;/marker&gt;"; </code></pre>
18,327
<p>I am having some trouble manipulating images using CodeIgniter 1.7. With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?</p> <pre><code>//Upload image first $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png|bmp'; $this-&gt;load-&gt;library('upload', $config); $this-&gt;upload-&gt;do_upload(); //Now fix the image $picloc = $this-&gt;upload-&gt;data(); $picloc = $picloc['file_name']; $thumbnail = "thumb_".$picloc; $imagemanip['image_library'] = 'gd2'; $imagemanip['source_image'] = './uploads/'.$picloc; $imagemanip['new_img'] = './uploads/'.$thumbnail; $imagemanip['maintain_ratio'] = TRUE; $imagemanip['width'] = 250; $imagemanip['height'] = 250; $this-&gt;load-&gt;library('image_lib', $imagemanip); $this-&gt;image_lib-&gt;resize(); </code></pre>
<p>The problem is simple, you have a typo in the line:</p> <pre><code>$imagemanip['new_img'] = './uploads/'.$thumbnail; </code></pre> <p>The the index should be "new_image", not "new_img", so the line becomes..</p> <pre><code>$imagemanip['new_image'] = './uploads/'.$thumbnail; </code></pre>
<pre><code>//Upload image first $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png|bmp'; $this-&gt;load-&gt;library('upload', $config); $this-&gt;upload-&gt;do_upload(); //Now fix the image $picloc = $this-&gt;upload-&gt;data(); $picloc = $picloc['file_name']; $thumbnail = "thumb_".$picloc; $imagemanip['image_library'] = 'gd2'; $imagemanip['source_image'] = './uploads/'.$picloc; $imagemanip['new_image'] = './uploads/'.$thumbnail;// this will get change in new code. $imagemanip['maintain_ratio'] = TRUE; $imagemanip['width'] = 250; $imagemanip['height'] = 250; $this-&gt;load-&gt;library('image_lib', $imagemanip); $this-&gt;image_lib-&gt;resize(); </code></pre> <p>now this will do your work</p>
31,891
<p>I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.</p> <p>I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.</p> <p>Question is: can you do both?</p>
<p>$.datepicker.noWeekends is a pretty simple bit of code:</p> <pre><code>function (date) { var day = date.getDay(); return [day &gt; 0 &amp;&amp; day &lt; 6, ""]; } </code></pre> <p>Since you're going to have to write up the function for holidays, you can just include this logic in that function too.</p>
<p>Can you do the opposite and have the input what dates are selectable and leave all the rest filtered out?</p>
29,847
<p>There seems to have been some interest over the past year around COP within the .NET community (ala <a href="http://www.qi4j.org/" rel="noreferrer">Qi4j</a>). A few folks have rolled there own COP frameworks (<em>see links below</em>) and it would appear .NET 4.0's Dynamic Dispatch and MEF might have a potential role in any .NET COP framework. </p> <p>On one hand a lot of this would appear to hark back to ideas from System/38 days (<em>yes, I'm an old guy</em>), though on the other it would also seem to be a pretty good fit with Oslo (<em>Modeling and Repository</em>). Can anyone comment on the whether Microsoft is doing any work on COP?</p> <p>Some recent .NET COP framework efforts:</p> <p>Hendry Luk - <a href="http://hendryluk.wordpress.com/2008/05/28/roll_your_own_cop_part_i_mixins/" rel="noreferrer">Roll Your Own COP</a></p> <p>Yves GoEleven.com - <a href="http://www.goeleven.com/blog/entryDetail.aspx?entry=147" rel="noreferrer">Cop - Proof of concept</a></p> <p>Anders Norås - <a href="http://andersnoras.com/blogs/anoras/archive/2008/08/21/trick-or-trait-composite-oriented-programming-with-c.aspx" rel="noreferrer">Trick or Trait? Composite Oriented Programming with C#</a></p> <p>Magnus Mårtensson - <a href="http://blog.noop.se/archive/2008/08/27/composite-oriented-programming-spike-on-unity-application-block.aspx" rel="noreferrer">Composite Oriented Programming spike on Unity Application Block</a></p>
<p>Aku - There is considerable difference between the CAB / Composite WPF guidance and COP which is a fundamentally different approach to the expression of object behavior via the assembly of 'fragments' based on [Domain] context. The appearance of Mixins, Concerns, Constraints, and SideEffects in .NET 4.0 variously might point in that direction, but I guess I'm more specifically curious if Microsoft is by chance, or in any way, formally "doing COP" and in particular on top of the Oslo repository.</p>
<p>Check MEF <a href="http://mef.codeplex.com" rel="nofollow noreferrer">http://mef.codeplex.com</a>, currently shipped inside .NET 4, more in PDC session <a href="http://microsoftpdc.com/Sessions/FT24" rel="nofollow noreferrer">http://microsoftpdc.com/Sessions/FT24</a></p>
18,357
<p>I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 (<a href="http://adldap.sourceforge.net/" rel="noreferrer">adLDAP</a> does it on Apache). Anyone had done anything similar, with success?</p> <ul> <li>Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.</li> </ul>
<p>Importing a whole library seems inefficient when all you need is essentially two lines of code...</p> <pre><code>$ldap = ldap_connect("ldap.example.com"); if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) { // log them in! } else { // error message } </code></pre>
<p>PHP has libraries: <a href="http://ca.php.net/ldap" rel="noreferrer">http://ca.php.net/ldap</a></p> <p>PEAR also has a number of packages: <a href="http://pear.php.net/search.php?q=ldap&amp;in=packages&amp;x=0&amp;y=0" rel="noreferrer">http://pear.php.net/search.php?q=ldap&amp;in=packages&amp;x=0&amp;y=0</a></p> <p>I haven't used either, but I was going to at one point and they seemed like they should work.</p>
20,677
<p>Consider the following trivial HTML page that throws an error:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;script&gt; throw new Error('oops'); alert('should not reach here'); &lt;/script&gt;&lt;/head&gt;&lt;/html&gt; </code></pre> <p>The user I am logged into Vista with is a member of both the Administrators and Debugger Users groups.</p> <p>If I run Internet Explorer on Vista as an administrator (right click &rarr; <strong>Run as administrator</strong>) and load the page I get the following error prompt:</p> <p><a href="https://i.stack.imgur.com/pIdR1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pIdR1.png" alt="alt text"></a></p> <p>Clicking Yes displays the following prompt from which I can successfully open Visual Studio 2008 and debug the problem:</p> <p><a href="http://img227.imageshack.us/img227/9751/debuguy3.png" rel="nofollow noreferrer">alt text http://img227.imageshack.us/img227/9751/debuguy3.png</a></p> <p>If I instead launch Internet Explorer normally and load the page no error prompt is displayed (or any indication of the error for that matter) and I can't jump in and debug the problem.</p> <p>I've tried making the site the page is served from a trusted site in Internet Explorer. This causes the error prompt to be displayed for the page, but clicking yes doesn't do anything and the browser just sits and hangs.</p> <p>Similarly I can only successfully attach to an existing Internet Explorer process from Visual Studio to debug JavaScript if Internet Explorer was run as an administrator.</p> <p><strong>How can I successfully debug JavaScript with Visual Studio when running Internet Explorer with UAC enabled?</strong></p>
<p>You will probably see that the first 1000 chars will take almost no time opposed to the last 1000 chars. </p> <p>I would assume that the time-consuming part is the actual copying of the large string into a new memory-area every time you add a char that is the tough work for your computer.</p> <p>Your optimization can easily be compared to what you usually do with streams, you use a buffer. Larger chunks will usually result in better performance until you hit the critical size where it no longer makes any difference, and starts to be a downside when your handling small amounts of data.</p> <p>If you however would have defined a char-array with the appropriate size from the beginning, it would probably be blazing fast, because then it won't have to copy it over and over again.</p>
<p>Answer to the modified queston ("why does this non-obvious optimization work so well" and "is it true you shouldn't use + operator on strings"):</p> <p>I'm not sure which non-obvious optimization you are talking about. But the answer to the second question, I think, covers all of the bases.</p> <p>The way strings work in C# is that they are allocated as fixed-length, and cannot be changed. This means that any time you try to change the length of the string, an entire new string is created and the old string is copied in up to the proper length. This is obviously a slow process. When you use String.Format it internally uses a StringBuilder to create the string.</p> <p>StringBuilders work by using a memory buffer which is more intelligently allocated than fixed-length strings, and thus performs significantly better in most situations. I'm not sure on the details of StringBuilder internally, so you'll have to ask a new question for that. I can speculate it either doesn't reallocate the old portions of the string (instead creating a linked list internally and only actually allocating the final output when needed by ToString) or it reallocates with exponential growth (when it runs out of memory, it allocates twice as much the next time, thus for a 2GB string it would only need to reallocate about 30 times).</p> <p>Your example with the nested loops grows linearly. it takes a small string and grows that up to 1000, and then tacks that 1000 on to the larger string in one large operation. As the large string gets really large, the copy that results from creating a new string gets to take a long time. When you reduce the amount of times this is done (by instead resizing a smaller string more often instead) you increase the speed. Of course, StringBuilder is even smarter about allocating memory, and thus is much faster.</p>
35,773
<p>There are many different printing technologies. While it might be clear to the asker that he's talking about his home 3D printing machine, that's not necessarily the case for those that try to answer the question.</p> <p>I think it would help to specify the scope of questions with tags, to allow future visitors to identify what type of 3D printer it is about. Answers to a lot of questions related to general properties of the printing process like printing speed, resolution, additional manual work, support structures, etc. depend heavily on the technology that's being used.</p> <p>This also prevents "Well, it depends..." type of answers that cover a lot of possibly unrelated things.</p>
<p>No, there will be many questions which are more general in nature, and have little to do with the actual process used to produce the part.</p> <p>We should encourage tag use for process when appropriate, but I don't think making it mandatory will work in the long term.</p>
<p>No, there will be many questions which are more general in nature, and have little to do with the actual process used to produce the part.</p> <p>We should encourage tag use for process when appropriate, but I don't think making it mandatory will work in the long term.</p>
1
<p>In Perl, I can type:</p> <pre><code>$|++; </code></pre> <p>and anything printed to STDOUT will be automatically fflush()ed.</p> <p>Is there an equivalent in C? In other words, is there some way I can tell stdio to automatically fflush stdout after every printf(), the way it automatically flushes stderr?</p>
<p>Try <code>setvbuf(stdout, NULL, _IONBF, 0)</code>. It changes <code>stdout</code> to unbuffered (<code>_IONBF</code>) mode.</p>
<p>Take a look at setbuf() and setvbuf().</p>
26,341
<p>Since <em>length</em> is a JavaScript property, does it matter whether I use</p> <pre><code>for( var i = 0; i &lt; myArray.length; i++ ) </code></pre> <p>OR</p> <pre><code>var myArrayLength = myArray.length; for( var i = 0; i &lt; myArrayLength ; i++ ) </code></pre> <p>­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<pre><code>for(var i = 0, iLen = myArray.length; i &lt; iLen; i++) </code></pre> <p>See <a href="http://blogs.oracle.com/greimer/resource/loop-test.html" rel="nofollow noreferrer">http://blogs.oracle.com/greimer/resource/loop-test.html</a> for benchmarks of various Javascript loop constructs.</p>
<p>While the second form may be faster:</p> <pre><code>function p(f) { var d1=new Date(); for(var i=0;i&lt;20;i++) f(); print(new Date()-d1) } p(function(){for(var i=0;i&lt;1000000; i++) ;}) p(function(){var a = new Array(1000000); for(var i=0;i&lt;a.length; i++) ;}) &gt; 823 &gt; 1283 </code></pre> <p>..it shouldn't really matter in any non-edge case.</p>
20,340
<p>I am looking for a drawing library or code examples to draw images or vector shapes repeated along a path which could be curved.</p> <p>I found a cocoa library which is what I am looking for <a href="http://apptree.net/drawkitmain.htm" rel="nofollow noreferrer">http://apptree.net/drawkitmain.htm</a> but for .NET.</p>
<p>I would use <a href="http://www.w3.org/Graphics/SVG/" rel="nofollow noreferrer">Scalable Vector Graphics</a> (SVG). This is ideal for manipulating vectorial images. You may want to look at <a href="http://www.jbrowse.com/svgnet/" rel="nofollow noreferrer">SvgNet</a>.</p>
<p>Or use native .Net in form of WPF. Using a DrawingBrush you can project whatever you like over any vector path you design.</p>
22,374
<p>We have a series of drop down controls that determine the sort order of columns. The problem we are having is when the user selects a column as the 2nd column the other dropdown lists need to have their values changed so that there is only one "2nd".</p> <ol> <li>Column A [1]</li> <li>Column B [2]</li> <li>Column C [3]</li> <li>Column D [4]</li> <li>Column E [5]</li> </ol> <p>In the list above, when you change Column D to [2], Column B becomes [3], C becomes [4], etc. I can manage it on the server side but I was wondering if anybody had some clues how to do this on the client side with javascript.</p>
<p>Look at Javascript toolkits like <a href="http://script.aculo.us/" rel="nofollow noreferrer">Scriptaculous</a> for client side reordering.</p> <p>You add your elements as "<a href="http://github.com/madrobby/scriptaculous/wikis/sortable" rel="nofollow noreferrer">Sortables</a>" and code your own callbacks to execute when the items are dragged, then dropped -- such as sending an asynchronous request to the server to persist the new order.</p> <p>Here is a <a href="http://zenofshen.com/posts/ajax-sortable-lists-tutorial" rel="nofollow noreferrer">full tutorial</a> on creating sortable lists with Scriptaculous and PHP. For ASP, the client side code will be slightly different, but the process will be similar.</p>
<p>On a note on JavaScript frameworks; I highly recommend <a href="http://www.jquery.com" rel="nofollow noreferrer">jQuery</a>.</p>
18,796
<p>I had made some questions regarding PHP-GTK (there are only 4 <code>php-gtk</code> tagged questions and three are mine) and I end up answering myself because no one answer them.</p> <p>I know it is a strange language selection but I was attracted to it because it runs on several OSs and the fact that I can reuse some of my code (also the apps end up looking good and I can make little installers in NSIS that just rocks).</p> <p>Is there a better alternative, that is free (as in freedom) and can run on several platforms?</p>
<p>Both Python and Ruby can work with the GTK libraries. These may be better chocies of languages for you (you'll certainly get more folk here answering your questions :)</p> <p>See <a href="https://stackoverflow.com/questions/115501/is-ruby-any-good-for-gui-development">Is Ruby any good for GUI development?</a> and <a href="https://stackoverflow.com/questions/115495/is-python-any-good-for-gui-development">https://stackoverflow.com/questions/115495/is-python-any-good-for-gui-development</a> for links for Ruby and Python respectively. </p>
<p>To answer your question from the other side.</p> <p>Other GUI applications that can be coded in PHP include <a href="https://en.wikipedia.org/wiki/WxWidgets" rel="nofollow">wxWidgets</a> and <a href="https://en.wikipedia.org/wiki/Qt_(software)" rel="nofollow">Qt</a>, both of which have PHP bindings available: <a href="https://en.wikipedia.org/wiki/WxPHP" rel="nofollow">wxPHP</a> and <a href="https://en.wikipedia.org/wiki/PHP-Qt" rel="nofollow">PHP-Qt</a></p>
25,640
<p>I have drawn an image in the device context using python and I want to move it smoothly/animate either vertically or horizontally.</p> <p>What algorithm should I use? Where can I get info for this kind of tasks in python?</p>
<p>Once an object is drawn in a device context it stays there. If you want to move it you need to redraw it.</p> <p>You can keep a background that's fixed and only redraw the movable elements each time they move. Basically that's how it's done.</p> <p>To move an object smoothly over a line you have to do something like this (I don't have a program ready, so can only give you an idea):</p> <ul> <li>choose the start and end position: point A(x1, y1) and B(x2, y2)</li> <li>choose in how much time the object should change position from A to B (say 10 seconds).</li> <li>use a timer set to a certain interval (say 2 seconds)</li> <li>calculate the delta X and Y that the object should change for each timer interval. In this case dx = (x2-x1)*2/10 and dy = (y2-y1)*2/10</li> <li>in the timer callback increment the current object position with dx and dy and redraw the image</li> </ul> <p>That would be the algorithm.</p> <p>I suggest that you also take a look to <a href="http://www.pygame.org/" rel="nofollow noreferrer">PyGame</a>. Maybe you can use that and it also has some tutorials.</p>
<p>To smoothly move object between starting coordinate <code>(x1, y1)</code> and destination coordinate <code>(x2,y2)</code>, you need to first ask yourself, how <em>long</em> the object should take to get to its destination. Lets say you want the object to get there in <code>t</code> time units (which maybe seconds, hours, whatever). Once you have determined this it is then trivial to workout the displacement per unit time:</p> <pre><code>dx = (x2-x1)/t dy = (y2-y1)/t </code></pre> <p>Now you simply need to add <code>(dx,dy)</code> to the object's position (<code>(x,y)</code>, initially <code>(x1,y1)</code>) every unit time, and stop when the object gets within some threshold distance of the destination. This is to account for the fact errors in divisions will accumulate, so if you did an equality check like: </p> <pre><code>(x,y)==(x2,y2) </code></pre> <p>It is unlikely it will ever be true. </p> <p>Note the above method gives you constant velocity, straight line movement. You may wish to instead use some sort a slightly more complex formula to give the object the appearance of accelerating, maintaining cruise speed, then decelerating. The following formulae may then be useful:</p> <pre><code>v(t) = u(t) + t*a(t) x(t) = v(t) + t*v(t) </code></pre> <p>This is merely <a href="http://en.wikipedia.org/wiki/Eulers_Method" rel="nofollow noreferrer">Euler's method</a>, and should suffice for animation purposes. </p>
15,417
<p>I'm building a project from the command line using WinCE platform builder, and I need RTTI to be enabled, so that my project works correctly. I tried setting the option <code>RTTI="YES</code>" in the sources and in the makefile of each dir, and I also tried to add it at the end of <code>CDEFINES</code>, but when I try to build the project, I get the <code>D9025</code> warnings, which says that my <code>"/GR was overriden by /GR-" ( enable RTTI was overriden by don't enable RTTI )</code>. My question is, how can I find out where that option is set, so that I can modify it?</p> <hr> <p>The thing is that we only copy the sources to some dirs, we specify them in a file named "sources", and then we proceed with the build by issuing the following command: <code>build</code></p> <p>What I would like to know is, where is build taking it's options from? What is the name of the file?</p>
<p><strong>Command-Line Warning D9025</strong></p> <p>If two options specify contradictory or incompatible directives, the directive specified or implied in the option farthest to the right on the command line is used.</p> <p>If you get this warning when compiling from the development environment, and are not sure where the conflicting options are coming from, consider the following:</p> <p>An option can be specified either in code or in the project's project settings. If you look at the compiler's Command Line Property Pages and if you see the conflicting options in the All Options field then the options are set in the project's property pages, otherwise, the options are set in source code.</p> <p>If the options are set in project's property pages, look on the compiler's Preprocessor property page (with the project node selected in the Solution Explorer). If you do not see the option set there, check the Preprocessor property page settings for each source code file (in Solution Explorer) to make sure it's not added there.</p> <p>If the options are set in code it could be set either in code or in the windows headers. You might try creating a preprocessed file (/P) and search it for the symbol.</p> <p>reference: <a href="http://msdn.microsoft.com/en-us/library/8k3f51f1(vs.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/8k3f51f1(vs.80).aspx</a></p>
<p>Start by looking in sources.cmn, which is a common sources file for the entire build system. If it's not there, keep in mind that every SOURCES file can alter compiler variables for it's folder, plus the makefiles can also alter things. To add to the fun, the system and platform build batch files can also play with environment variables, that in turn may adjust settings.</p>
13,903
<p>I have been writing Flex applications for a few months now and luckily have not needed a full debugger as of yet, so far I have just used a few Alert boxes...</p> <p>Is there an available debugger that is included in the free Flex SDK? I am not using FlexBuilder (I have been using Emacs and compiling with ant).</p> <p>If not, how do you debug Flex applications without FlexBuilder? (note: I have no intentions of using flexbuilder)</p>
<p>A debugger called <code>fdb</code> is included in the Flex SDK. Here's some documentation on how to use it:</p> <ul> <li><a href="http://www.adobe.com/devnet/flex/articles/client_debug_08.html" rel="nofollow noreferrer">Adobe DevCenter: Debugging Client-Side Code in Flex Applications</a></li> <li><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=debugging_01.html" rel="nofollow noreferrer">Flex 3 Help: Using the Command-Line Debugger</a></li> </ul>
<p>I had the same problem when programming with ActionScript and having to test it on a browser. Try <a href="http://www.flex888.com/649/debugging-flex-with-thunderbolt.html" rel="nofollow noreferrer">this</a>. It involves using Firefox (which I believe you do) and FireBug to receive the debug messages.</p>
8,070
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
<p>You demonstrate a fundamental misunderstanding.</p> <p>You never created an instance of SimpleClass at all, because you didn't call it.</p> <pre><code>for count in xrange(4): x = SimpleClass() x.attr = count simplelist.append(x) </code></pre> <p>Or, if you let the class take parameters, instead, you can use a list comprehension.</p> <pre><code>simplelist = [SimpleClass(count) for count in xrange(4)] </code></pre>
<p>If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?</p> <pre><code>import copy x = SimpleClass() for count in range(0,4): y = copy.deepcopy(x) (...) y.attr1= '*Bob* '* count </code></pre> <p>A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: <a href="https://docs.python.org/2/library/copy.html" rel="nofollow noreferrer">https://docs.python.org/2/library/copy.html</a></p>
45,307
<p>I want to have a map that has a homogeneous key type but heterogeneous data types.</p> <p>I want to be able to do something like (pseudo-code):</p> <pre><code>boost::map&lt;std::string, magic_goes_here&gt; m; m.add&lt;int&gt;("a", 2); m.add&lt;std::string&gt;("b", "black sheep"); int i = m.get&lt;int&gt;("a"); int j = m.get&lt;int&gt;("b"); // error! </code></pre> <p>I could have a pointer to a base class as the data type but would rather not.</p> <p>I've never used boost before but have looked at the fusion library but can't figure out what I need to do.</p> <p>Thanks for your help.</p>
<pre><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/any.hpp&gt; int main() { try { std::map&lt;std::string, boost::any&gt; m; m["a"] = 2; m["b"] = static_cast&lt;char const *&gt;("black sheep"); int i = boost::any_cast&lt;int&gt;(m["a"]); std::cout &lt;&lt; "I(" &lt;&lt; i &lt;&lt; ")\n"; int j = boost::any_cast&lt;int&gt;(m["b"]); // throws exception std::cout &lt;&lt; "J(" &lt;&lt; j &lt;&lt; ")\n"; } catch(...) { std::cout &lt;&lt; "Exception\n"; } } </code></pre>
<p>boost any surely works, but I think using Int to type Technology as the key type of fusion map is a better solution. No type erasure and possibly faster </p>
31,308
<p>I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.</p> <p>Wanted conversion is like this:</p> <pre><code>CVS branch SVN branch HEAD -&gt; branches/branchX branchA -&gt; trunk branchB -&gt; branches/branchB branchC -&gt; branches/branchC </code></pre> <p>That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.</p> <p>Both CVS and SVN repositories will be on same linux machine.</p> <p>How could this be done? </p> <p>Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough.</p>
<blockquote>I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?</blockquote> <p>Yes. Subversion also keeps track of changes to the directory structure, and all version history is preserved even if a file is moved in the tree. </p> <p>I recommend converting the repository with <a href="http://cvs2svn.tigris.org/" rel="noreferrer">cvs2svn</a>, including branches and tags. Once the repository is in Subversion you can move the branches and tags around as you wish. This also keeps the history of the actual tags and branches being renamed, which may be interesting in a historical context later.</p>
<p>I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?</p>
3,513
<p>Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.</p>
<p>Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through.</p> <p>an <strong>important</strong> note: by default triggers do not fire on bulk inserts (BCP &amp; SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like:</p> <pre><code>BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS ) </code></pre>
<p>You're saying there's a column full of dates in the file, and you want that data to go into a column of type "datetime" in a table in a SQL database? And it'll blow up if one of the values from the file isn't a valid date? I just wanted to make sure I understand this right.</p> <p>You could create another, temporary, table in the SQL database, of the same structure as the table you want the data from the file to end up in, but with every column of type varchar(255) or something. Sucking the data out of the file and into that table shouldn't fail whether any of the dates is valid or not.</p> <p>Then, in SQL, you could massage the data however you want. You could use a <a href="http://www.jackdonnell.com/articles/SQL_CURSOR.htm" rel="nofollow noreferrer">cursor</a> to select all of the records from the temporary table and loop through them. For each record, you could use the T-SQL <a href="http://doc.ddart.net/mssql/sql70/ia-iz_32.htm" rel="nofollow noreferrer">ISDATE</a> function to conditionally insert the values from the current record into one table or another.</p> <p>I'm saying, get the data into the database and then run script like this:</p> <pre><code>// **this is untested, there could be syntax errors** // if we have tables like this: CREATE TABLE tempoary (id VARCHAR(255), theDate VARCHAR(255), somethingElse VARCHAR(255)) CREATE TABLE theGood (id INT, theDate DATETIME, somethingElse VARCHAR(255)) CREATE TABLE theBad (id INT, theDate VARCHAR(255)) // then after getting the data into [tempoary], do this: DECLARE tempCursor CURSOR FOR SELECT id, theDate, somethingElse FROM temporary OPEN tempCursor DECLARE @id VARCHAR(255) DECLARE @theDate VARCHAR(255) DECLARE @somethingElse VARCHAR(255) FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse While (@@FETCH_STATUS &lt;&gt; -1) BEGIN IF ISDATE(@theDate) BEGIN INSERT INTO theGood (id, theDate, somethingElse) VALUES (CONVERT(INT, @id), CONVERT(DATETIME, theDate), somethingElse) END ELSE BEGIN INSERT INTO theBad (id, theDate) VALUES (CONVERT(INT, @id), theDate) END FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse END CLOSE tempCursor DEALLOCATE tempCursor </code></pre>
13,555
<p>This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first:</p> <pre><code>// Singleton class which contains data class MyData { static MyData* sMyData ; int mData1[1024]; int mData2[1024]; int mData3[1024]; MyData* getInstance() { // sMyData is created in the very beginning. return sMyData ; } void getValues(int idx, int&amp; data1,int&amp; data2,int&amp; data3) { data1 = mData1[idx]; data2 = mData2[idx]; data3 = mData3[idx]; } int* getData1() { return &amp;mData1[0]; } } class MyThread { void workerMethod() { MyData* md = MyData::getInstance(); int d1,d2,d3; md-&gt;getValue( 12, d1,d2,d3 ); int* data1 = md-&gt;getData1(); d1 = data1[34]; } } </code></pre> <p>Now as you see I have some getter methods (all read-only), MyData::getInstance(), MyData::getValue() and MyData::getData1(). The 1st question is how thread-safe these methods are ?</p> <p>Since they are often-called methods, protecting those methods with mutex is something I am trying to avoid. </p> <p>The 2nd question is: what is the suggested way of reading data from central sources in a multi-thread application, especially in worker methods.</p> <p>Thanks !</p> <p>Paul</p>
<p>Provided that no other thread will try to write to the data in your singleton object, you don't need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program's initialization code sets up a singleton, which is then only read from by worker threads.</p> <p>However, if <em>any</em> thread <em>ever</em> writes to this data while others are reading from it, you must protect it in some way. If you have lots of readers and only the occasional writer, it is worth considering some sort of "read-write" lock, which allows multiple readers in the absence of any writers.</p>
<p>For thread safety you need to look at the class as a whole. As written your class would not be thread safe. Whilst your getValues method is okay, the getData1 method has problems.</p> <p>You say they are (read-only) getter methods. However, neither are declared as const methods. The getData1 would not be valid as a const method as it returns a non const pointer. In addition, returning a pointer to private class data is bad as you are exposing your implementation.</p> <p>If this is a singleton class to hold some essentially static data set on initialistion before your threading kicks off then all your accessors should be const methods. The getInstance should also return a const pointer to the class (and be a static method as mentioned by another answer).</p>
34,217
<p>I've seen questions about (like <a href="https://3dprinting.stackexchange.com/q/2670/11157">What is stopping us from mixing 3d filament colors in an Extruder?</a>) and some solutions for mixing filament colors/materials at print time for multi-color printing, but my question is different: Are there any (affordable) commercially available devices, or DIY/homebrew solutions, for taking 2 or more 1.75&nbsp;mm filaments, mixing them in proportion, and extruding back as 1.75&nbsp;mm filament for use in a printer?</p> <p>In principle it should just take N extruder drives fed a the right proportional rates, one of the multi-input hotends, a 1.75&nbsp;mm extrusion nozzle, and another drive to pull the extruded filament at the right rate to keep the diameter stable. But I'm curious if anyone's tried and tuned this. Another approach might be taking a hotend made for 3 mm filament, drilling the nozzle orifice out to 1.75 mm, and feeding 3 pieces of 1.75 mm filament into it at once (size seems to match pretty closely).</p> <p>My interest in this is that I mostly print small things, and it takes months to go through even a single kg of filament, so it's impractical to buy and keep around a bunch of different colors. I'd also like to be able to experiment with mixing flex PLA and plain PLA to get a material with a lot less plasticizer, so that it's not flexible, just less brittle.</p> <p>Shredding into pellets and measuring out ratios is too much overhead to make it worth it. The key part of the question is doing it direct from filament to filament.</p>
<p>OK, it just turned up on Thingiverse that someone has demonstrated a trivial machine to do exactly what I asked for: any FDM printer.</p> <blockquote> <p>Its sounds crazy, but it works! This technique will allow you to create one offs, and to color match your 3D-prints.</p> <p>It works by changing the filament (and the color) of your filament while printing, and this causes a multi colored filament, that can be printed again to archive a homogenic-color.</p> </blockquote> <p><img src="https://i.stack.imgur.com/b7aIr.jpg" alt="Rendering of STL file from the link" /></p> <p>Source <a href="https://www.thingiverse.com/thing:3565827" rel="nofollow noreferrer">3D-Printable Filament! -Print Your Own Filament for Multi-Color!</a>, with <a href="https://www.youtube.com/watch?v=6kbjZobJtbM" rel="nofollow noreferrer">demonstration video</a>.</p> <p>I'm in the process of trying this and it looks promising! The filament:</p> <p><img src="https://i.stack.imgur.com/aT5aP.jpg" alt="printed filament" /></p> <p>measures 1.65-1.75 mm in diameter and feeds and extrudes cleanly.</p> <p>The first test print:</p> <p><img src="https://i.stack.imgur.com/pICnN.jpg" alt="mixed filament frog next to unmixed comparison prints" /></p> <p>came out somewhat underextruded, but decent, with uniform mixing of color. Mixed filaments were white flex PLA and blue regular PLA, and the plasticizer seems to have mixed as expected too, but the print feels brittle due to underextrusion still. I suspect with some tuning of flow printing the filament, very good results could be had.</p> <p>On further inspection, the brittleness/underextrusion seems to be somewhat localized, so it likely comes from <em>inconsistent</em> diameter/density of printed filament. This actually seems consistent with what I saw from the slicer output for printing the filament: there were regions at +/- 45 degrees (+ or - depending on layer) in the spiral where it seems like wall gaps differed and extra gap fill material did or didn't get printed. This could be a slicer bug but it seems more likely it's a bug in the model, and I'd probably do better to recreate it myself in OpenSCAD...</p>
<h2>Making your own filament</h2> <p>Theoretically, this could be done with any filament producing equipment by taking the two filaments and shredding them into pellets and feeding them to the machine in the right mix for the color you want. Industrial setups like a <a href="https://www.filabot.com/" rel="nofollow noreferrer">Filabot</a> are heavy, large and expensive though.</p> <p>Luckily, hobbyist filament making setups exist. They vary in price and quality but can achieve ok to good results, if you tinker with them a little. Among the kits that I have seen to work is the <a href="https://www.filastruder.com/collections/filastruders-accessories" rel="nofollow noreferrer">Filastruder</a>, but there are also <a href="https://all3dp.com/make-low-cost-filament-extruder/" rel="nofollow noreferrer">DIY instructables</a> that cost less than 200 $.</p> <h3>Obtaining pellets</h3> <p>If you are good with mechanics, you might design a feed mechanism that pushes the part filaments with known feed rate into a cutter to pelletize the filament in the wanted amounts to each other, creating a homogenous mix over the length of the filament.</p> <h3>Blended waste</h3> <p>As an alternative to self-made pellets to mix in the hopper for the filament maker, one can use shredded waste prints/support structures. After smashing the material to rough chunks, using a blender to gain evenly sized small chunks of 1-2 mm, the stuff should be small enough to feed through the hopper without a problem. the blender also would take care of proper mixing and could take raw filament to mix with <em>used</em> ones.</p> <h2>Mixing in the hotend</h2> <p>Mixing filaments in the hotend would need a specialized hotend with two feed ends into the melt zone and two extruders that push the filaments with the same feed rate. The modification of the feeding system would be extensive and demand a custom firmware.</p> <h2>Splicing filaments</h2> <p>Another possibility would be a machine that splices the filament in a defined manner. One machine that might be able to do this seems to be the Palette 2 by Mosaic, but it costs (April 2019) round 600 USD. Another possibility could be to use the multi-material upgrade of a Prusa i3 Mk3.</p> <p>This would generate however a non-homogenous mix of the filaments, the transition zones changing from high concentrations of material A to high concentrations of material B whenever the materials swap. Even with very short areas of spliced material the mix will be inconsistent. With colored filaments, this could generate a rainbow pattern.</p>
1,296
<p>Emacs has a useful <code>transpose-words</code> command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.</p> <p>For example, ‘<code>stack |overflow</code>’ + M-t = ‘<code>overflow stack|</code>’ (‘<code>|</code>’ is the cursor position).</p> <p><code>&lt;a&gt;|&lt;p&gt;</code> becomes <code>&lt;p&gt;&lt;a|&gt;</code>.</p> <p>Is it possible to emulate it in Vim? I know I can use <code>dwwP</code>, but it doesn’t work well with punctuation.</p> <p><em>Update:</em> No, <code>dwwP</code> is <em>really</em> not a solution. Imagine:</p> <pre><code>SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) ) // with cursor here ^ </code></pre> <p>Emacs’ M-t would have exchanged <code>b</code> and <code>c</code>, resulting in <code>(a)(c)(b)</code>.</p> <p>What works is <code>/\w yiwNviwpnviwgp</code>. But it spoils <code>""</code> and <code>"/</code>. Is there a cleaner solution?</p> <p><em>Update²:</em></p> <h1>Solved</h1> <pre><code>:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,&lt;CR&gt;kgJ:nohl&lt;CR&gt; </code></pre> <p>Imperfect, but works.</p> <p>Thanks Camflan for bringing the <code>%#</code> item to my attention. Of course, it’s all on the <a href="http://vim.wikia.com/wiki/VimTip47" rel="noreferrer">wiki</a>, but I didn’t realize it could solve the problem of <em>exact</em> (Emacs got it completely right) duplication of the <code>transpose-words</code> feature.</p>
<p>These are from my .vimrc and work well for me.</p> <pre><code>" swap two words :vnoremap &lt;C-X&gt; &lt;Esc&gt;`.``gvP``P " Swap word with next word nmap &lt;silent&gt; gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/&lt;cr&gt;&lt;c-o&gt;&lt;c-l&gt; *N* </code></pre>
<p>You can use dwwP or dWwP as Mark and CapnNefarious have said, but I have a few notes of my own: </p> <ul> <li>If the cursor is on the first letter of the second word, as in the example you gave, you can use dwbP (or dWbP to handle punctuation);</li> <li>If the cursor is in the middle of the word, you can use dawbP/daWbP.</li> </ul>
17,082
<p>I have a datagridview with a DataGridViewComboboxColumn column with 3 values:</p> <p>"Small", "Medium", "Large"</p> <p>I get back the users default which in this case is "Medium"</p> <p>I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.</p>
<p>When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about.</p> <p>However, if you want to get in there by yourself, </p> <pre><code>DataGridView.Rows[rowindex].Cells[columnindex].Value </code></pre> <p>will let you get and set the value associated to the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).</p>
<p>Are you retrieving the user data and attempting to set values in the DataGridView manually, or have you actually bound the DataGridVew to a data source? Because if you've bound the grid to a data source, you should just need to set the DataPropertyName on the column to be the string name of the object Property:</p> <pre><code>[DataGridViewComboboxColumnName].DataPropertyName = "PropertyNameToBindTo"; </code></pre> <p>Or do you mean you want it to default to Medium for a new row?</p>
11,753
<p>I´m creating a PDA app and I need to upload/download a lot of small files and my idea is to gather them in an <strong>uncompressed zip file</strong>.</p> <p>The question is: It´s a good idea to <strong>read those files from the zip</strong> without separating them? How can I do so? Or is it <strong>better to unzip them?</strong> Since the files are not compressed my simple mind points that maybe reading them from the zip it´s more or less as efficient as reading them directly from the file system...</p> <p>Thanks for you time!</p>
<p>Since there are two different Open-source libraries (<a href="http://icsharpcode.com/OpenSource/SharpZipLib/Default.aspx" rel="nofollow noreferrer">SharpZipLib</a> and <a href="http://www.codeplex.com/DotNetZip" rel="nofollow noreferrer">DotNetZip Library</a>) to handle writing &amp; extracting files from a zip file, why worry about doing it yourself?</p>
<p>Sounds as if you want to use the archive to group your files.</p> <p>From a <em>reading the files</em> point of view, it makes very little difference if the files are handled one way or the other. You would need to implement the ability to read zip files, though. Even if you use a lib like James Curran suggested, it means additional work, which can mean additional sources of error.</p> <p>From the <em>uploading the files</em> point of view, it makes more sense: The uploader could gather all the files needed and would have to take care of only one single upload. This reduces overhead as well as error handling (if one uplaod fails, do you have to delete all files of this group already uploaded?).</p> <p>As for the efficiency of reading them from the archive vs. reading them directly from the disc: The difference should be minimal. You (or your zip library) need to once parse the zip directory structure, which is pretty straight forward. The rest is reading part of a file into memory vs. reading a file into memory. </p>
33,288
<p>I'm using <strong>DotNetNuke</strong>, so the whole site is basically dynamically driven and I'm clueless to how to go about creating a Google sitemap for it. </p> <p>Any help will be greatly appreciated.</p>
<p>Jeff Atwood has some good information on SiteMaps <a href="http://www.codinghorror.com/blog/archives/001174.html" rel="nofollow noreferrer">here</a>. You can also see more information on SiteMap formats <a href="http://sitemaps.org/protocol.php" rel="nofollow noreferrer">here</a>.</p>
<p>Thanks for the answers. I've found a great sitemap generator over at codeplex. If anyone is interested you can check it out here: <a href="http://www.codeplex.com/sitemapgenerator" rel="nofollow noreferrer">http://www.codeplex.com/sitemapgenerator</a></p> <p>Enjoy!</p>
27,023
<p>I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.</p> <pre><code>ID uniqueidentifier not null, ThingID int NOT NULL, PriceDateTime datetime NOT NULL, Price decimal(18,4) NOT NULL </code></pre> <p>I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?</p> <pre><code>SELECT * FROM Thing WHERE ThingID IN (1,2,3,4,5,6) AND PriceDate &gt; cast( convert(varchar(20), getdate(), 106) as DateTime) </code></pre> <p><strong>UPDATE:</strong> In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.</p>
<p>I think the only solution with your table structure is to work with a subquery:</p> <pre><code>SELECT * FROM Thing WHERE ID IN (SELECT max(ID) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) </code></pre> <p>(Given the highest ID also means the newest price)</p> <p>However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...</p> <pre><code>SELECT * FROM Thing WHERE ThingID IN (1,2,3,4) AND IsCurrent = 1 </code></pre> <p><strong>UPDATE</strong></p> <p>Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.</p> <pre><code>SELECT T.* FROM Thing T JOIN (SELECT ThingID, max(PriceDateTime) WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) X ON X.ThingID = T.ThingID AND X.PriceDateTime = T.PriceDateTime WHERE ThingID IN (1,2,3,4) </code></pre> <p>I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small).</p> <p>(I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.)</p>
<p>maybe i missunderstood the taks but what about a: </p> <p><code>SELECT ID, ThingID, max(PriceDateTime), Price FROM Thing GROUP BY ThingID</code></p>
7,195
<p>Greetings. I have been looking at Literate Programming a bit now, and I do like the idea behind it: you basically write a little paper about your code and write down as much of the design decisions, the code probably surrounding the module, the inner workins of the module, assumptions and conclusions resulting from the design decisions, potential extension, all this can be written down in a nice way using tex. Granted, the first point: it is documentation. It must be kept up-to-date, but that should not be that bad, because your change should have a justification and you can write that down.</p> <p>However, how does Literate Programming Scale to a larger degree? Overall, Literate Programming is still just text. Very human readable text, of course, but still text, and thus, it is hard to follow large systems. For example, I reworked large parts of my compiler to use >> and some magic to chain compile steps together, because some "x.register_follower(y); y.register_follower(z); y.register_follower(a);..." got really unwieldy, and changing that to x >> y >> z >> a made it a bit better, even though this is at its breaking point, too. </p> <p>So, how does Literate Programming scale to larger systems? Does anyone try to do that?</p> <p>My thought would be to use LP to specify components that communicate with each other using event streams and chain all of these together using a subset of graphviz. This would be a fairly natural extension to LP, as you can extract a documentation -- a dataflow diagram -- from the net and also generate code from it really well. What do you think of it? </p> <p>-- Tetha.</p>
<p>Excellent question. The motivation for literate programming will never go away, but I think it should be treated as fluid. It means "give the reader a break, and educate them to what you're trying to do". I don't think it means "make your code really wordy".</p> <p>That said, the reader will have to put some effort into it, depending on what they already know. Presumably the code is worth understanding, and nothing comes for free.</p> <p>I also think it means more than just making readable code. Most likely the reason someone is reading the code is because they need to make a change. You should anticipate the possible changes that might be needed, and tell them how to do it if necessary.</p>
<p>Literate Programming was developed in an era where long variable and function names were simply not possible. Because of this, code really wasn't that readable.</p> <p>Obviously, a lot has happened since then. </p> <p>In today's world, the code itself is the documentation, hence the term "self documenting code." The realization is that no set of comments or external documentation can ever stay in sync with the underlying code. So, the goal of a lot of today's programmers is to write the code in such a way that it is readable to others.</p>
38,294
<p>I have to maintain a large number of classic ASP pages, many of which have tabular data with no sort capabilities at all. Whatever order the original developer used in the database query is what you're stuck with.</p> <p>I want to to tack on some basic sorting to a bunch of these pages, and I'm doing it all client side with javascript. I already have the basic script done to sort a given table on a given column in a given direction, and it works well as long as the table is limited by certain conventions we follow here.</p> <p>What I want to do for the UI is just indicate sort direction with the caret character ( <code>^</code> ) and ... what? Is there a special character that is the direct opposite of a caret? The letter <code>v</code> won't quite cut it. Alternatively, is there another character pairing I can use?</p>
<p>There's &#9650;: <a href="http://www.fileformat.info/info/unicode/char/25b2/index.htm" rel="noreferrer">&amp;#9650;</a> and &#9660;: <a href="http://www.fileformat.info/info/unicode/char/25bc/index.htm" rel="noreferrer">&amp;#9660;</a></p>
<p>Could you just draw an svg path inside of a span using document.write? The span isn't required for the svg to work, it just ensures that the svg remains inline with whatever text the carat is next to. I used margin-bottom to vertically center it with the text, there might be another way to do that though. This is what I did on <a href="http://www.costonmission.com" rel="nofollow noreferrer">my blog's side nav</a> (minus the js). If you don't have text next to it you wouldn't need the span or the margin-bottom offset. </p> <pre><code>&lt;div id="ID"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; var x = document.getElementById('ID'); // your "margin-bottom" is the negative of 1/2 of the font size (in this example the font size is 16px) // change the "stroke=" to whatever color your font is too x.innerHTML = document.write = '&lt;span&gt;&lt;svg style="margin-bottom: -8px; height: 30px; width: 25px;" viewBox="0,0,100,50"&gt;&lt;path fill="transparent" stroke-width="4" stroke="black" d="M20 10 L50 40 L80 10"/&gt;&lt;/svg&gt;&lt;/span&gt;'; &lt;/script&gt; </code></pre>
43,969
<p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p> <p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p> <p>I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>
<p>I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):</p> <pre><code>(defun buildtree (wordlist) ...code to build tree recursively returns the tree...) (define lookup (tree word) ...code to look up word using tree, returns t or nil...) (defun lookupmany (tree querylist) (if (eq querylist nil) nil (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist)) ) ) (defun main (wordlist querylist) ; the main entry point (lookupmany (buildtree wordlist) querylist) ) </code></pre> <p>if this is what you mean, this is fairly straight-forward functional programming. Is it really stateless? That's a matter of debate. Some people would say some forms of functional programming store what we normally call "state" on the stack. Moreover, Common LISP even since the first edition of the Steele book has had iterative constructs, and LISP has had setq for a long, long time.</p> <p>But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here.</p> <p>I think the above is something like the arrangement you mean.</p>
<p>I imagine you'd want something like a tree with a list of children, as described <a href="http://csus.cs.mcgill.ca/wiki/COMP-302_(Panangaden%2C_Pientka%2C_Winter_06)_Lectures#Trees_with_a_list_of_children" rel="nofollow noreferrer">here</a>.</p>
6,911
<p>I'm afraid my trial of VS 2008 is running out soon, and unless a client pays for it, I might be shelling out some cash for it. I've been looking through the <a href="http://msdn.microsoft.com/en-us/vs2008/products/cc149003.aspx" rel="nofollow noreferrer">comparison chart</a> to compare VS Professional to Standard, and so far I think I'm safe. I wanted to hear from you on what the most important features are that I would be missing.</p> <p>Of course, you don't know all the details of my situation - but please just answer based on what you perceive as most important.</p>
<p>Developing Windows Mobile Applications and availability of Database Projects are the showstoppers for me (this applies to Visual Studio 2008).</p> <p>That's it really. This was a dealbreaker for me though since I wanted to join this mobile application programming contest and was floored when I found out I couldn't do it with Standard.</p> <p>Otherwise you're fine with Standard edition.</p>
<p>Very little difference between the two. The only one I can think of is remote debugging is not available in standard.</p>
12,447
<p>For example I have such query:</p> <pre><code>Query q = sess.createQuery("from Cat cat"); List cats = q.list(); </code></pre> <p>If I try to make something like this it shows the following warning </p> <pre><code>Type safety: The expression of type List needs unchecked conversion to conform to List&lt;Cat&gt; List&lt;Cat&gt; cats = q.list(); </code></pre> <p>Is there a way to avoid it?</p>
<p>Using <code>@SuppressWarnings</code> everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call <code>q.list()</code>.</p> <p>There are two other techniques I'd suggest:</p> <p><strong>Write a cast-helper</strong></p> <p>Simply refactor all your <code>@SuppressWarnings</code> into one place:</p> <pre><code>List&lt;Cat&gt; cats = MyHibernateUtils.listAndCast(q); ... public static &lt;T&gt; List&lt;T&gt; listAndCast(Query q) { @SuppressWarnings("unchecked") List list = q.list(); return list; } </code></pre> <p><strong>Prevent Eclipse from generating warnings for unavoidable problems</strong> </p> <p>In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox <code>Ignore unavoidable generic type problems due to raw APIs</code></p> <p>This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.</p> <p>Some comments:</p> <ul> <li>I chose to pass in the <code>Query</code> instead of the result of <code>q.list()</code> because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any <code>List</code> in general.</li> <li>You could add similar methods for <code>.iterate()</code> etc.</li> </ul>
<p>If you don't want to use @SuppressWarnings("unchecked") you can do the following.</p> <pre><code> Query q = sess.createQuery("from Cat cat"); List&lt;?&gt; results =(List&lt;?&gt;) q.list(); List&lt;Cat&gt; cats = new ArrayList&lt;Cat&gt;(); for(Object result:results) { Cat cat = (Cat) result; cats.add(cat); } </code></pre> <p>FYI - I created a util method that does this for me so it doesn't litter my code and I don't have to use @SupressWarning. </p>
14,103
<p>In the Visual Studio toolbar, you can enter commands into the search box by prefixing them with a > symbol. Is there any way to disable this? I've never used the feature, and it's slightly annoying when trying to actually search for something that you know is prefixed by greater-than in the code. It's particularly annoying when you accidentally search for "> exit" and the IDE quits (I knew there was a line in the code that was something like <code>if(counter &gt; exitCount)</code> so entered that search without thinking).</p> <p>At the very least, can you escape the > symbol so that you can search for it? Prefixing with ^ doesn't seem to work.</p>
<p>This is a really cool feature. I've poked through the <a href="http://msdn.microsoft.com/en-us/library/1665hyw1(VS.80).aspx" rel="nofollow noreferrer">feature documentation</a>, and the accompanying <a href="http://msdn.microsoft.com/en-us/library/c338aexd(VS.80).aspx" rel="nofollow noreferrer">command list</a>, and not a heck of a lot is showing up in terms of turning it off.</p> <p>If you want to search for <code>&gt;exit</code>, you could always type <code>&gt;Edit.Find &gt;exit</code> in the search box; that seems to do the trick. A bit verbose, though, but it really is an edge case.</p>
<blockquote> <p>Wow, I didn't know that. Where do I find the list of possible commands?</p> </blockquote> <p>The commands are the same as those you can enter in the command window, so you can pretty much drive the entire IDE and debugger using it. There are a load of predefined aliases for common commands. Open up the command window and enter <code>alias</code> for a list, to get you started.</p>
3,555
<p>Is there a website/list of problems which can be used to practice OOP design skills? Let's say if I am a colleague graduate familiar with object-oriented-design theory, these problems should give me a chance to exercise the theory and improve my software design skills. </p>
<p>If you're wanting to try out a new methodology or something, try making a small application just for you, or perhaps for internal use only. eg: A timesheet application, a task manager, a grocery list organiser, etc. Make sure it's a <em>real</em> problem, so you're forced to deal with <em>real</em> requirements. I've found that if you just play around and try things out, you tend to just ignore certain parts when they don't work immediately.</p>
<p><a href="http://codekata.pragprog.com/" rel="nofollow noreferrer">CodeKata</a> is a place to start.</p> <p>It's not a web site, but Head First Design Patterns has a multitude of problems to solve. </p>
21,964
<p>I've got a class named <code>BackgroundWorker</code> that has a thread constantly running. To turn this thread off, an instance variable named <code>stop</code> to needs to be <code>true</code>. </p> <p>To make sure the thread is freed when the class is done being used, I've added <code>IDisposable</code> and a finalizer that invokes <code>Dispose()</code>. Assuming that <code>stop = true</code> does indeed cause this thread to exit, is this sippet correct? It's fine to invoke <code>Dispose</code> from a finalizer, right?</p> <p>Finalizers should always call <code>Dispose</code> if the <code>object</code> inherits <code>IDisposable</code>, right?</p> <pre><code>/// &lt;summary&gt; /// Force the background thread to exit. /// &lt;/summary&gt; public void Dispose() { lock (this.locker) { this.stop = true; } } ~BackgroundWorker() { this.Dispose(); } </code></pre>
<p>First off, a <strong>severe warning</strong>. Don't use a finalizer like you are. You are setting yourself up for some very bad effects if you take locks within a finalizer. Short story is don't do it. Now to the original question.</p> <pre><code>public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// &lt;summary&gt; /// Force the background thread to exit. /// &lt;/summary&gt; protected virtual void Dispose(bool disposing) { if (disposing) { lock (this.locker) { this.stop = true; } } } ~BackgroundWorker() { Dispose(false); } </code></pre> <p>The only reason to have a finalizer at all is to allow sub-classes to extend and release <strong>unmanaged resources</strong>. If you don't have subclasses then seal your class and drop the finalizer completely.</p>
<p>Is the "stop" instance variable a property? If not, there's no particular point in setting it during the finalizer - nothing is referencing the object anymore, so nothing can query the member.</p> <p>If you're actually releasing a resource, then having Dispose() and the finalizer perform the same work (first testing whether the work still needs to be done) is a good pattern.</p>
18,204
<p>Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as <code>96</code>. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as <code>0140</code>. Hexadecimal based numbers are usually prefixed by <code>0x</code>: 96 would be written as <code>0x60</code>.</p> <p>The question is: can I write numbers as binary literals in Ruby? How?</p>
<p>use 0b prefix</p> <pre><code>&gt;&gt; 0b100 =&gt; 4 </code></pre>
<p>From <a href="http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#numeric" rel="noreferrer">this manual</a></p> <pre><code>0b01011 </code></pre> <p>binary integer </p>
12,694
<p>Basically what the title says...</p> <p>I need to have an image that when clicked, I call script.php for instance and in that PHP script file, I get the image coordinates where the mouse was clicked.</p> <p>Is this possible?</p> <p><strong>EDIT:</strong><br /> After a couple of answers I realized I didn't describe my problem correctly... The thing is, I don't have total control over the HTML. The control I have for the image and the image link is the control BBCode provides me.</p> <p>Basically want I want to do is to have a forum signature with links to various sections on my website. You could argue I could use multiple images but most forums limit how much you can type for the signature, which is not enough for multiple images.</p> <p>So, I will only be able to do something like this:<br /></p> <pre><code>[url=http://www.mydomain.com/script.php] [img]http://www.mydomain.com/signature.jpg[/img] [/url] </code></pre> <p>Which translates to something like this:<br /></p> <pre><code>&lt;a href="http://www.mydomain.com/script.php"&gt; &lt;img src="http://www.mydomain.com/signature.jpg" /&gt; &lt;/a&gt; </code></pre>
<p>If you can't:</p> <ol> <li>use JavaScript, or</li> <li>use input type="image", or</li> <li>add any attributes to your img tag (to do things like create an image map)</li> </ol> <p>then, no, you won't be able to do what you describe.</p>
<p>You can use an ajax request when "onclick" is performed to send a request to "script.php". Otherwise I would read up on php, which is a server-side language.</p>
46,735
<p>I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation. I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis. I am working on deriving the formulas, but I would like to know if there is a resource already available for this.</p>
<p>I'd first define the equation for the parabolic arc in 2D without rotations:</p> <pre><code> x(t) = ax² + bx + c y(t) = t; </code></pre> <p>You can now apply the rotation by building a rotation matrix:</p> <pre><code> s = sin(angle) c = cos(angle) matrix = | c -s | | s c | </code></pre> <p>Apply that matrix and you'll get the rotated parametric equation:</p> <pre><code>x' (t) = x(t) * c - s*t; y' (t) = x(t) * s + c*t; </code></pre> <p>This will give you two equations (for x and y) of your parabolic arcs.</p> <p>Do that for both of your rotated arcs and subtract them. This gives you an equation like this:</p> <pre><code> xa'(t) = rotated equation of arc1 in x ya'(t) = rotated equation of arc1 in y. xb'(t) = rotated equation of arc2 in x yb'(t) = rotated equation of arc2 in y. t1 = parametric value of arc1 t2 = parametric value of arc2 0 = xa'(t1) - xb'(t2) 0 = ya'(t1) - yb'(t2) </code></pre> <p>Each of these equation is just a order 2 polynomial. These are easy to solve.</p> <p>To find the intersection points you solve the above equation (e.g. find the roots).</p> <p>You'll get up to two roots for each axis. Any root that is equal on x and y is an intersection point between the curves.</p> <p>Getting the position is easy now: Just plug the root into your parametric equation and you can directly get x and y.</p>
<p>Unfortunately, the general answer requires solution of a fourth-order polynomial. If we transform coordinates so one of the two parabolas is in the standard form y=x^2, then the second parabola satisfies (ax+by)^2+cx+dy+e==0. To find the intersection, solve both simultaneously. Substituting in y=x^2 we see that the result is a fourth-order polynomial: (ax+bx^2)^2+cx+dx^2+e==0. Nils solution therefore won't work (his mistake: each one is a 2nd order polynomial in each variable separately, but together they're not).</p>
15,768
<p>What options do I have to publish Flash video from webcams other than Adobe's Flash Media Server and Red5? I would prefer a solution in .NET, Python or PHP but can't find anything.</p>
<p>Besides another commercial product, like <a href="http://www.wowzamedia.com/" rel="nofollow noreferrer">Wowza Media Server</a>, you could go with a CDN (Content Delivery Network), like <a href="http://www.limelightnetworks.com/" rel="nofollow noreferrer">Limelight Networks</a> or <a href="http://www.voxel.net/" rel="nofollow noreferrer">Voxel.net</a>. You might even be able to find a local hosting provider that would serve up live Flash video for you.</p> <p>(Live Flash video in a non-trivial thing to do, so the options are a bit limited.)</p>
<p>It looks like WebOrb can do it: <a href="http://www.themidnightcoders.com/weborb/dotnet/faq.shtm" rel="nofollow noreferrer">WebOrb FAQ</a> (last entry)</p> <blockquote> <p>Can I stream Flash video to a Flex/Flash client through WebORB? Yes, WebORB supports FLV video streaming. An example is included with the WebORB for .NET product distribution.</p> </blockquote> <p>I haven't worked with WebOrb though, so I can't say for sure how easy it is.</p>
6,581
<p>I've been asked to write code/design things in an interview. Sometimes even to provide code samples. Very reasonable and very wise (always surprised when this DOESN'T happen)</p> <p>I had a job a year or so back where the code was so awful that I would not have taken the job, if I'd seen the mess I had to deal with ahead of time. And I can't tell you how many horrendous databases I've had to work with.</p> <p>Is it out of the question for me to ask <strong>them</strong> to provide a code sample and to view their database design? Assuming I'd be happy to sign an NDA, part of me feels it would insane to take a job without examining the codebase or database I'd be working with.</p> <p>Anyone done this?</p> <h3>Update</h3> <p>This would be something I would ask later in the interview process, if things were proceeding well and I felt an offer was forthcoming.</p> <p>It's also in the context of working in a small shop or small project as my preference is to avoid places that use phrases like "get a developer off the floor"</p>
<p>You can definitely ask. The answer may be "No," but nobody should consider that to be a bad or inappropriate question.</p> <p>If they won't show you the code, you should definitely take that into account when you decide whether you want to accept an offer. I would take it as a sign that at least one of the following things is true:</p> <ul> <li>The code is so horrible that they know you'll run away screaming.</li> <li>The company has an ultra-secretive trust-nobody culture (which I would hate).</li> <li>The company thinks they have such amazing code that just glancing at it would turn you into a superstar competitor. (In other words, they're self-deluded morons.)</li> <li>They have glaring security holes that they hope to keep secret.</li> <li>The people who are interviewing you don't know how to get the code themselves. (In which case you are not talking to the right people.)</li> </ul>
<p>I think this is a great idea; however, as an employer, I would be hesitant -- even with an NDA -- to provide an interview candidate samples of real, working code unless I was pretty sure I wanted to hire the person.</p>
19,649
<p>In a Flex / Java app stack using remoting (via BlazeDS), classes to hold data passed back and forth between client and server need to be maintained in both the client (in ActionScript) and server (in Java).</p> <p>I want a way to maintain theses classes in Java only, and have the corresponding ActionScript value object classes generated by the build process.</p>
<p>Check out the AS3 generator from the Granite Data Services project:</p> <p><a href="http://www.graniteds.org" rel="nofollow noreferrer">http://www.graniteds.org</a></p> <p>If I recall correctly it's an Eclipse plugin which should be quite easy to use. Just remember that if you exclude a property from the ActionScript class that it will still be serialized by Blaze when it's sent back to the Flex client.</p>
<p><a href="http://xdoclet.codehaus.org/" rel="nofollow noreferrer">XDoclet2</a> includes an ActionScript plugin that can generate ActionScript classes from Javadoc comments in Java code.</p> <p>The downside is that it's based on Javadoc rather than Java annotations, and does not appear to be well-documented or very widely used.</p>
27,428
<p>Is there anyone already implement memcached for production use in Windows environment? Because many blogs that I've read, it's not recommended to run memcached in Windows especially for production use, for example <a href="http://latebound.blogspot.com/2008/10/running-memcached-on-windows.html" rel="noreferrer">running memcached on windows</a>.</p> <p>And one more thing, which memcached client that is good to use with c# and .net 3.5 ? I've found many alternate such as <a href="http://www.codeplex.com/memcachedproviders" rel="noreferrer">Memcached Providers @ Codeplex</a>, <a href="http://code.google.com/p/beitmemcached/" rel="noreferrer">Beitmemcached</a>, and <a href="http://sourceforge.net/projects/memcacheddotnet" rel="noreferrer">memcached provider @ Sourceforge</a></p>
<p>Why do you need to run memcached on windows? It’s an expensive affair in a production environment. </p> <p>If your code needs to run in a Windows environment get a windows memcached client and talk to a *nix based memcached machine. </p> <p>In a production environment running memcached on Server 2003 or 2008 would mean that you get licenses for all those boxes. Linux will offer you all the OSS benefits. TCO will rise linearly with memcached on Windows </p> <p><strong>Edit:</strong> </p> <p>It’s been around 1.5 years since I wrote this answer and lot of things have changed since. You’ve to take notice, especially when someone like Dustin comments.<br> So here’s how you can get memcached on windows running. <a href="http://blog.couchbase.com/memcached-144-windows-32-bit-binary-now-available" rel="noreferrer">Download memcached for windows from Couchbase (formerly Northscale)</a>.<br> Typically if you plan to run memcached on the same production machine you’d want to start it in limited memory, i.e. define the maximum memory memcached is allowed to use. </p> <blockquote> <p>c:\Program Files\memcached>memcached.exe -m 128.</p> </blockquote> <p><em>Here memcached runs with a maximum of 128 mb usage. You don’t want memcached to take up all the memory on your webserver.</em> </p> <p>The moment you decided to <a href="http://en.wikipedia.org/wiki/Scale_out#Scale_horizontally_.28scale_out.29" rel="noreferrer">scale out</a> memcached you’ll need to consider what I said earlier. Additionally compress your values in the key value combinations. Web servers typically consume very little CPU (2-3%) usage and compression brings in a lot of value to network throughout in comparison to the CPU usage. If you are too concerned about normal compression, try <a href="http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Oberhumer" rel="noreferrer">LZO</a></p>
<p>If you're interested in running a memcached client on Windows then there are two additional open source servers that can do the job. Both implement the standard memcached server protocol and are written in Java so they run on Windows. </p> <ul> <li><a href="http://code.google.com/p/jmemcache-daemon/" rel="nofollow">jmemcached</a></li> <li><a href="http://code.google.com/p/quickcached/" rel="nofollow">quickcached</a></li> </ul>
45,786
<p>I'll go first.</p> <p>I'm 100% in the set-operations camp. But what happens when the set logic on the entire desired input domain leads to a such a large retrieval that the query slows down significantly, comes to a crawl, or basically takes infinite time?</p> <p>That's one case where I'll use a itty-bitty cursor (or a while loop) of perhaps most dozens of rows (as opposed to the millions I'm targeting). Thus, I'm still working in (partitioned sub) sets, but my retrieval runs faster.</p> <p>Of course, an even faster solution would be to call the partioned input domains in parallel from outside, but that introduces an interaction will an external system, and when "good enough" speed can be achieved by looping in serial, just may not be worth it (epecially during development).</p>
<p>Sure, there are a number of places where cursors might be better than set-based operations.</p> <p>One is if you're updating a lot of data in a table (for example a SQL Agent job to pre-compute data on a schedule) then you might use cursors to do it in multiple small sets rather than one large one to reduce the amount of concurrent locking and thus reduce the chance of lock contention and/or deadlocks with other processes accessing the data.</p> <p>Another is if you want to take application-level locks using the <code>sp_getapplock</code> stored procedure, which is useful when you want to ensure rows that are being polled for by multiple processes are retrieved exactly once (<a href="http://gregbeech.com/blogs/tech/archive/2008/06/11/retrieving-a-row-exactly-once-with-multiple-polling-processes-in-sql-server.aspx" rel="nofollow noreferrer">example here</a>).</p> <p>In general though, I'd agree that it's best to start using set based operations if possible, and only move to cursors if required either for functionality or performance reasons (with evidence to back the latter up).</p>
<p>Well one operation where cursors are better than sets is when calculating a running total and similar stuff.</p>
20,789
<p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
<pre><code>import sys # argv is your commandline arguments, argv[0] is your program name, so skip it for n in sys.argv[1:]: print(n) #print out the filename we are currently processing input = open(n, "r") output = open(n + ".out", "w") # do some processing input.close() output.close() </code></pre> <p>Then call it like:</p> <pre> ./foo.py bar.txt baz.txt </pre>
<p>This thing also works for reading multiple files, my file name is <code>fedaralist_1.txt</code> and <code>federalist_2.txt</code> and like this, I have 84 files till <code>fedaralist_84.txt</code></p> <p>And I'm reading the files as f.</p> <pre class="lang-py prettyprint-override"><code>for file in filename: with open(f'federalist_{file}.txt','r') as f: f.read() </code></pre>
25,528
<p>I have a winforms application that normally is at about 2-4% CPU. We are seeing some spikes up to 27% of CPU for limited number of times. What is the best profiling tool to determine what is actually causing this spike. We use dottrace but i dont see how to map that to exactly the CPU spikes?</p> <p>Appreciate the help</p>
<p>I've used 2 profiling tools before - RedGate's ANTS profiler, and the built in profiler found in Visual Studio Team System.</p> <p>It's been some time since I used RedGate's (<a href="http://www.red-gate.com/products/ants_profiler/index.htm" rel="nofollow noreferrer">http://www.red-gate.com/products/ants_profiler/index.htm</a>) profiler, though I used the built in in Visual Studio 2008 fairly recently.</p> <p>That being said, I felt that the RedGate product felt more intuitive to use. One thing that frustrated me back when I used the RedGate product was that I couldn't instruct the profiler to only profile my code starting at a certain point - I had a performance hit that couldn't be reached until a fair amount of code had already executed and therefore polluted my results. They may have added that feature since then.</p> <p>The built in version for Visual Studio is only available in their very-high end versions of the product. Someone correct me if I am wrong, but I don't think even the "Professional" version has the profiler. I am currently using Team System Developer Edition, which <em>does</em> have the code analysis tools.</p> <p>One thing the VS version does do though, is enable you to pause the profiling, and even start your app with profiling paused, so you can really focus on the performance of something very specific. This can be exceedingly helpful when you are trying to understand the analysis results.</p> <p>EDIT: Both tools will show you memory usage, and the number of times a specific method was called, and how much time was spent in each method. What they do not do, to the best of my knowledge, is show you CPU usage at any given point in time. However, there are likely strong correlations between CPU usage and the amount of time spent in a given block of code.</p> <p>If you can duplicate the CPU spikes consistently by invoking certain actions in the APP, then what I would do is try and get my hands on the VS profiler, start the app with profiling pause, enable profiling right before you do whatever typically results in the spike, and examine those results.</p> <p>This assumes of course that you have some sort of deterministic behavior to recreate the spikes. If not ... you might considering threaded processes or garbage collection a candidate for your performance hit.</p>
<p>I’ve found DevPartner from Compuware <a href="http://www.compuware.com/" rel="nofollow noreferrer">http://www.compuware.com/</a> to be an excellent profiling tool. Unfortunately it looks like at the present time they don’t support VS 2008.</p>
13,040
<p>I'm trying to get a user control working asynchronously, yet no matter what I do it continues to work synchronously. I've stripped it down to its bare minimum as a test web application. This would be the user control:</p> <pre><code>&lt;%@ Control Language="C#" %&gt; &lt;script runat="server"&gt; SqlConnection m_oConnection; SqlCommand m_oCommand; void Page_Load(object sender, EventArgs e) { Trace.Warn("Page_Load"); string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true"; string strSQL = "waitfor delay '00:00:10'; select * from MyTable"; m_oConnection = new SqlConnection(strDSN); m_oCommand = new SqlCommand(strSQL, m_oConnection); m_oConnection.Open(); Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true)); Page.ExecuteRegisteredAsyncTasks(); } IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state) { Trace.Warn("BeginHandler"); return m_oCommand.BeginExecuteReader(cb, state); } void EndHandler(IAsyncResult ar) { Trace.Warn("EndHandler"); GridView1.DataSource = m_oCommand.EndExecuteReader(ar); GridView1.DataBind(); m_oConnection.Close(); } void TimeoutHandler(IAsyncResult ar) { Trace.Warn("TimeoutHandler"); } &lt;/script&gt; &lt;asp:gridview id="GridView1" runat="server" /&gt; </code></pre> <p>And this would be the page in which I host the control three times:</p> <pre><code>&lt;%@ page language="C#" trace="true" async="true" asynctimeout="60" %&gt; &lt;%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %&gt; &lt;html&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;uc:mycontrol id="MyControl1" runat="server" /&gt; &lt;uc:mycontrol id="MyControl2" runat="server" /&gt; &lt;uc:mycontrol id="MyControl3" runat="server" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The page gets displayed without errors, but the trace at the bottom of the page shows each control instance is processed synchronously. What am I doing wrong? Is there a configuration setting somewhere I'm missing?</p>
<p>Looks like I can answer my own question. The user control should not be calling <code>Page.ExecuteRegisteredAsyncTasks</code>. By doing that, the control was adding the async task, running it, and waiting for it to complete.</p> <p>Instead, each instance of the user control should call only <code>Page.RegisterAsyncTask</code>. After each control instance has done this the page automatically calls <code>RegistereAsyncTask</code> running all three registered async tasks simultaniously.</p> <p>So here is the new user control:</p> <pre><code>&lt;%@ Control Language="C#" %&gt; &lt;script runat="server"&gt; SqlConnection m_oConnection; SqlCommand m_oCommand; void Page_Load(object sender, EventArgs e) { Trace.Warn(ID, "Page_Load - " + Thread.CurrentThread.GetHashCode().ToString()); string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true"; string strSQL = "waitfor delay '00:00:10'; select * from TEProcessedPerDay where Date &gt; dateadd(day, -90, getutcdate()) order by Date asc"; m_oConnection = new SqlConnection(strDSN); m_oCommand = new SqlCommand(strSQL, m_oConnection); m_oConnection.Open(); Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true)); } IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state) { Trace.Warn(ID, "BeginHandler - " + Thread.CurrentThread.GetHashCode().ToString()); return m_oCommand.BeginExecuteReader(cb, state); } void EndHandler(IAsyncResult ar) { Trace.Warn(ID, "EndHandler - " + Thread.CurrentThread.GetHashCode().ToString()); GridView1.DataSource = m_oCommand.EndExecuteReader(ar); GridView1.DataBind(); m_oConnection.Close(); } void TimeoutHandler(IAsyncResult ar) { Trace.Warn(ID, "TimeoutHandler - " + Thread.CurrentThread.GetHashCode().ToString()); } &lt;/script&gt; &lt;asp:gridview id="GridView1" runat="server" /&gt; </code></pre> <p>And the unchanged page that creates three instances of the control:</p> <pre><code>&lt;%@ page language="C#" async="true" trace="true" %&gt; &lt;%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %&gt; &lt;html&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;uc:mycontrol id="MyControl1" runat="server" /&gt; &lt;uc:mycontrol id="MyControl2" runat="server" /&gt; &lt;uc:mycontrol id="MyControl3" runat="server" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>If I may add a little to the above post, we should not call the <code>ExecuteRegisteredAsyncTassk</code> explicitly unless there is a compelling reason. once you register the async task, the ASP.NET framework will execute all these tasks right after the <code>OnPrerender</code> event of the page lifecycle.</p> <p>An example for the usage of <code>ExecuteRegisteredAsyncTasks</code> could be; Sometimes you may need to ensure that several async operations are completed before calling another async task. in a situation like this it is justifiable to use <code>ExecuteRegisteredAsyncTasks</code>.</p>
34,465
<p>We're having problem with a huge number of legacy stored procedures at work. Do you guys recommend any tool the can help better understand those procedures? Some kind of reverse engineering that indentifies inter-procedure dependencies and/or procedure vs. tables dependencies. Can be a free or commercial tool.</p> <p>Thanks!</p>
<p>Redgate has a rather expensive product called <a href="http://www.red-gate.com/products/SQL_Dependency_Tracker/" rel="nofollow noreferrer">SQL Dependency Tracker</a> that seems to fulfill the requirements.</p>
<p>The single best tool for reverse engineering is by APEX. Its amazing. It can even trace into .NET assemblies and tell you where the procs are used. Its by far the deepest product of its kind. RedGate has great other tools but not in this case. </p>
9,533
<p>Is there an IE6/PNG fix that is officially developed by the jQuery team?</p> <p>If not which of the available plugins should I use?</p>
<p>I'm using <a href="http://jquery.andreaseberhard.de/pngFix/" rel="nofollow noreferrer">jquery.pngFix.js</a>. I don't know if it's officially sanctioned or not, I do know that it works. I chose it because it was the plugin included with FancyBox, no other reason. </p>
<p>Hey guys, just wanted to toss this one in. I was digging around for it again and it has one specific advantage over the rest: repeatable backgrounds, as well as background-position (the one thats flagged as the best answer here actually just scales the background image). </p> <p><a href="http://www.dillerdesign.com/experiment/DD_belatedPNG/" rel="nofollow noreferrer">http://www.dillerdesign.com/experiment/DD_belatedPNG/</a></p> <p>It's so great. Just drop it in and forget its there. Have yet to see it explode a set of CSS. </p>
8,572
<p>I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was looking for some better strategies for handling these problems.</p> <p>I've been frequently running into the problem of duplicating almost every header file with a blank version in order to separate the class I'm testing in it's entirety, and then writing substantial stub/mock/fake code for objects that will need to be replaced since they're now undefined.</p> <p>Anyone know some better practices?</p>
<p>The depression in the responses is overwhelming... But don't fear, we've got <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="noreferrer" rel="nofollow noreferrer">the holy book to exorcise the demons of legacy C++ code</a>. Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code.</p> <p>Turn to page 127: <strong>The case of the horrible include dependencies.</strong> (Now I am not even within miles of Michael Feathers but here as-short-as-I-could-manage answer..)</p> <p><strong>Problem</strong>: In C++ if a classA needs to know about ClassB, Class B's declaration is straight-lifted / textually included in the ClassA's source file. And since we programmers love to take it to the wrong extreme, a file can recursively include a zillion others transitively. Builds take years.. but hey atleast it builds.. we can wait. </p> <p>Now to say 'instantiating ClassA under a test harness is difficult' is an understatement. (Quoting MF's example - Scheduler is our poster problem child with deps galore.)</p> <pre><code>#include "TestHarness.h" #include "Scheduler.h" TEST(create, Scheduler) // your fave C++ test framework macro { Scheduler scheduler("fred"); } </code></pre> <p>This will bring out the includes dragon with a flurry of build errors.<br> <strong>Blow#1 Patience-n-Persistence</strong>: Take on each include one at a time and decide if we really need that dependency. Let's assume SchedulerDisplay is one of them, whose displayEntry method is called in Scheduler's ctor.<br> <strong>Blow#2 Fake-it-till-you-make-it</strong> (Thanks RonJ):</p> <pre><code>#include "TestHarness.h" #include "Scheduler.h" void SchedulerDisplay::displayEntry(const string&amp; entryDescription) {} TEST(create, Scheduler) { Scheduler scheduler("fred"); } </code></pre> <p>And pop goes the dependency and all its transitive includes. You can also reuse the Fake methods by encapsulating it in a Fakes.h file to be included in your test files.<br> <strong>Blow#3 Practice</strong>: It may not be always that simple.. but you get the idea. After the first few duels, the process of breaking deps will get easy-n-mechanical</p> <p><strong>Caveats</strong> (Did I mention there are caveats? :) </p> <ul> <li>We need a separate build for test cases in this file ; we can have only 1 definition for the SchedulerDisplay::displayEntry method in a program. So create a separate program for scheduler tests.</li> <li>We aren't breaking any dependencies in the program, so we are not making the code cleaner.</li> <li>You need to maintain those fakes as long as we need the tests.</li> <li>Your sense of aesthetics may be offended for a while.. just bite your lip and 'bear with us for a better tomorrow' </li> </ul> <p>Use this technique for a very huge class with severe dependency issues. Don't use often or lightly.. <strong>Use this as a starting point for deeper refactorings.</strong> Over time this testing program can be taken behind the barn as you extract more classes (WITH their own tests).</p> <p>For more.. please do read the book. Invaluable. Fight on bro!</p>
<p>If you keep writing stubs/mock/fake codes you risk doing unit testing on a class that has different behavior then when compiled on the main project.</p> <p>But if those includes are there and have no added behavior then it's Ok.</p> <p>I'd try not changing anything on the includes while doing the unit testing so you're sure (as far you can be on legacy code :) ) that you testing the real code.</p>
9,080
<p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p> <pre><code>import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() </code></pre>
<p>I recommend <code>babel</code> and <code>pytz</code> when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.</p> <ul> <li><a href="http://babel.pocoo.org/" rel="noreferrer">Babel</a></li> <li><a href="http://pytz.sourceforge.net/" rel="noreferrer">pytz</a></li> </ul>
<h2>Python &gt;= 3.9</h2> <p>Python comes with <a href="https://docs.python.org/3/library/zoneinfo.html" rel="nofollow noreferrer">zoneinfo</a> as part of the standard lib. Example usage:</p> <pre><code>from datetime import datetime, timezone from zoneinfo import ZoneInfo UTC = datetime(2012,11,10,9,0,0, tzinfo=timezone.utc) # convert to another tz with &quot;astimezone&quot;: eastern = UTC.astimezone(ZoneInfo(&quot;US/Eastern&quot;)) # note that it is safe to use &quot;replace&quot;, # to get the same wall time in a different tz: pacific = eastern.replace(tzinfo=ZoneInfo(&quot;US/Pacific&quot;)) print(UTC.isoformat()) print(eastern.isoformat()) print(pacific.isoformat()) # 2012-11-10T09:00:00+00:00 # 2012-11-10T04:00:00-05:00 # 2012-11-10T04:00:00-08:00 </code></pre> <p>Also note <a href="https://docs.python.org/3/library/zoneinfo.html#data-sources" rel="nofollow noreferrer">this section from the docs</a>:</p> <blockquote> <p>The zoneinfo module does not directly provide time zone data, and instead pulls time zone information from the system time zone database or the first-party PyPI package <a href="https://pypi.org/project/tzdata/" rel="nofollow noreferrer">tzdata</a>, if available.</p> </blockquote> <p>So don't forget to call a <code>pip install tzdata</code>, on Windows at least.</p>
14,316
<p>After creating a translucent window (<a href="http://stormsilver.net/itunescheck/browser/tags/0.91/TransparentWindow.m?rev=25" rel="noreferrer">based on example code by Matt Gemmell</a>) I want to get keyboard events in this window. It seems that there are only keyboard events when my application is the active application while I want keyboard events even when my application isn't active but the window is visible.</p> <p>Basically I want behavior like that provided by the Quicksilver application (by blacktree).</p> <p>Does anybody have any hints on how to do this?</p>
<p>There are two options:</p> <ol> <li>Use <a href="http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/Reference/reference.html#//apple_ref/c/func/GetEventMonitorTarget" rel="nofollow noreferrer"><code>GetEventMonitorTarget()</code></a> with a tacked-on Carbon run loop to grab keyboard events. Sample code is available on <a href="http://www.cocoadev.com/index.pl?KeyboardEventsFromOtherApps" rel="nofollow noreferrer">this page</a> at CocoaDev. <br><br><li>Register an event trap with <a href="http://developer.apple.com/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/c/func/CGEventTapCreate" rel="nofollow noreferrer"><code>CGEventTapCreate</code></a>. Sample code can be found in <a href="http://lists.apple.com/archives/quartz-dev/2005/Oct/msg00013.html" rel="nofollow noreferrer">this thread</a> from the Apple developer mailing list. </ol> <p><b>Edit:</b> Note that these methods only work if you check off “Enable access for assistive devices” in the Universal Access preference pane.</p>
<p>Update:<br> Apple actually seems to have changed everything again starting with 10.5 BTW (I recently upgraded and my sample code did not work as before).</p> <p>Now you can indeed only capture keydown events setting up an event tap if you are either root or assistive devices are enabled, regardless on which level you plan to capture and regardless if you selected to capture (which allows you to modify and even discard events) or to be listen only. You can still get information when flags have changed (actually even change these) and other events, but keydown under no other circumstances.</p> <p>However, using the carbon event handler and the method RegisterEventHotKey() allows you to register a hotkey and you'll get notified when it is pressed, you neither need to be root for that nor do you need anything like assistive devices enabled. I think Quicksilver is probably doing it that way.</p>
41,951
<p>Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)</p>
<p>How about using the C++ language itself?</p> <pre><code>bool t = true; bool f = false; std::cout &lt;&lt; std::noboolalpha &lt;&lt; t &lt;&lt; " == " &lt;&lt; std::boolalpha &lt;&lt; t &lt;&lt; std::endl; std::cout &lt;&lt; std::noboolalpha &lt;&lt; f &lt;&lt; " == " &lt;&lt; std::boolalpha &lt;&lt; f &lt;&lt; std::endl; </code></pre> <p>UPDATE: </p> <p>If you want more than 4 lines of code without any console output, please go to <a href="https://en.cppreference.com/w/cpp/io/manip/boolalpha" rel="noreferrer">cppreference.com's page talking about <code>std::boolalpha</code> and <code>std::noboolalpha</code></a> which shows you the console output and explains more about the API. </p> <p>Additionally using <code>std::boolalpha</code> will modify the global state of <code>std::cout</code>, you may want to restore the original behavior <a href="https://stackoverflow.com/q/2273330/52074">go here for more info on restoring the state of <code>std::cout</code></a>.</p>
<p>I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; #define BOOL_STR(b) (b?"true":"false") int main (int argc, char const *argv[]) { bool alpha = true; printf( BOOL_STR(alpha) ); return 0; } </code></pre>
4,903
<p>I'm looking at a new project and we are wanting to use Flex (to provide the easy integration with AIR and provide a desktop app for our project). How easy does CakePHP play with Flex or is there a better PHP framework to use with Flex, or should we use none?</p>
<p>If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable. It's much more fluent and intuitive and you can control where the nodes go... wherever you add them to the collection is where they appear in the resulting XML.</p> <p>Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit: <a href="http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx" rel="nofollow noreferrer">http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx</a></p>
<p>Your best option if you want a quick and dirty way is to load the users information into the dataset, call the "WriteXml" method to save and use "ReadXml" to pull it back in. The XML format that the DataSet uses on its own will come in and out in the same format.</p> <p>You also have many other options, but the DataSet is the most quick and dirty way of doing it.</p>
29,548
<p>I need to add a paging, sortable table to my GWT application.</p> <p>I see lots of these out there so I'm looking for your experience to save me time by choosing the best one.</p> <p>So far I'm looking at...</p> <p><a href="http://code.google.com/p/gwt-advanced-table/" rel="noreferrer">http://code.google.com/p/gwt-advanced-table/</a><br> <a href="http://code.google.com/p/google-web-toolkit-incubator/wiki/PagingScrollTableOld" rel="noreferrer">http://code.google.com/p/google-web-toolkit-incubator/wiki/PagingScrollTableOld</a></p> <p>I like the second one best. Any stories to tell?</p>
<p>There's a new CellTable that has support for paging. It's in the GWT trunk right now and will, with any luck, make it into a 2.1 release later this year.</p>
<p>It's already been answered <a href="https://stackoverflow.com/questions/231407/gwt-paging-widget">here</a></p> <p>And unfortunately there is no satisfying implementation available. The best approach i have found has the <a href="http://gwt-widget.sourceforge.net/" rel="nofollow noreferrer">GWT widget library</a>. I have used it to create my own paging solution.</p>
43,536
<p>Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?</p>
<p>Not according to <a href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#infrastructure-for-the-send%28%29-method" rel="noreferrer">the W3C standard for the XMLHttpRequest object</a> (emphasis added):</p> <blockquote> <p>If the response is an HTTP redirect:</p> <blockquote> <p>If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, <strong>transparently follow the redirect</strong> while observing the same-origin request event rules.</p> </blockquote> </blockquote> <p>They were <a href="http://www.w3.org/TR/2008/WD-XMLHttpRequest-20080415/#notcovered" rel="noreferrer">considering</a> it for a future release:</p> <blockquote> <p>This specification does not include the following features which are being considered for a future version of this specification:</p> <ul> <li>Property to disable following redirects;</li> </ul> </blockquote> <p>but the <a href="http://www.w3.org/TR/XMLHttpRequest/" rel="noreferrer">latest</a> specification no longer mentions this.</p>
<p>It is not possible to handle redirect or 302 status at client side as answered in other comments. However you can prevent redirection. To do that you can set request header &quot;X-Requested-With&quot; with &quot;XMLHttpRequest&quot; xhttp.setRequestHeader(&quot;X-Requested-With&quot;, &quot;XMLHttpRequest&quot;); This should be done after open but before send. Example below</p> <pre><code>let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 &amp;&amp; this.status == 200) { reqObj.success(JSON.parse(this.responseText)) } else if (this.status != 200) { reqObj.error(this.statusText) } }; xhttp.open(reqObj.type, reqObj.url, reqObj.async); xhttp.setRequestHeader(&quot;X-Requested-With&quot;, &quot;XMLHttpRequest&quot;); xhttp.send(); </code></pre>
28,246
<p>Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example.</p> <p>You get a screenful of stackoverflow questions by requesting <code>/questions ?sort=newest</code> page. Next page link leads to <code>/questions?page=2 &amp;sort=newest</code>. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!)</p> <p>Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still.</p> <p>The best idea I have (apart from storing request history per client) is to use <code>/questions?answer_id=NNN</code> format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? </p> <p>Is it how it usually done? Or there is a better way?</p>
<p>This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upvoted post could have been moved to page 1 or 2.</p> <p>Only way to do it is to load the complete list in someones session. Please don't...</p> <p>As already mentioned, let's hope people are used to this by now.</p>
<p>Most web sites I've seen don't solve this problem - they show you a page including some content you've already seen.</p> <p>You might consider that a feature - when you click "next" and see some content you're seen before, it's a signal that you want to go back to the front again because there's some new content.</p>
5,963
<p>I read somewhere in the Microsoft documentation that the content of the ASP.NET's <strong>web.config is cached</strong>. If that is true, <strong>where</strong> is it cached - in <strong>memory or on disk</strong>?</p> <p>And a follow-up question: are there any performance considerations I have to make, if I have to access the web.config intensively?</p>
<p>Its cached in memory, caching on disk doesn't make any sense, its already on disk.</p> <p>First of all in ASP.NET you want to ensure you access configuration sections through the HttpContext object's <code>GetSection</code> method (this uses the cached copies managed by ASP.NET).</p> <p>Performance of accessing config values is a function of the internal implementation of the Section object (the object returned by GetSection). A <code>ConfigurationSection</code> may simply act as wrapper for a DOM node which it may read on every request for a property. OTH it could internaly cache the value and watch for changes.</p> <p>My advice would be keep your code simple and just access the values you need via <code>GetSection</code> rather than attempt to hold copies of them elsewhere but by all means maintain a reference to the object returned by <code>GetSection</code> for the duration of a request if you are going to fetch multiple values from it.</p>
<p>My advice would be to use it just like anyother variable for the simple reason that data is cached. An if you create static variables in global.asax you are forcing yourself to write more code. No matter how planned you are, it is highly likely that you add variables in appconfig frequently during the development stage.</p>
34,617
<p>We have a rather simple site (minimal JS) with plain html and CSS. It is a simple mobile interface for our main application.</p> <p>We are running into trouble because we have more than one column and several browsers seem to force single columns.</p> <p>Through some searching I ran into 2 meta tags.</p> <pre><code>&lt;meta name="MobileOptimized" content="220" /&gt; &lt;meta name="viewport" content="width=320" /&gt; </code></pre> <p>With these we have a good 'scaled' view for IE Mobile and the iPhone. We have not run into any problems with palm's Blazer. But Blackberry is another matter.</p> <p>Does the Blackberry have a simple way to control the view of the browser as well? By simple I mean without making a special page for that device.</p>
<p>I wouldn't bother making a "medium" version for the iPhone etc, iPhone users can just look at your real web page easily enough. Have your full version and a single column version, and you'll reach the largest audience with minimal work.</p> <p>To answer your question though, there's no good way to make the Blackberry do anything other than 1 column views. You can get it to look fairly professional, as CSS and simple javascript still apply, but you'll have to lose a lot of your horizontal real estate.</p>
<p>BlackBerry (from OS 4.6 and higher) supports both the meta-viewport tag as well as the meta-HandheldFriendly tag. See the "Content Design Guidelines" document at <a href="http://na.blackberry.com/eng/support/docs/subcategories/?userType=21&amp;category=BlackBerry+Browser" rel="nofollow noreferrer">http://na.blackberry.com/eng/support/docs/subcategories/?userType=21&amp;category=BlackBerry+Browser</a> for details.</p>
13,259
<p>When trying to invoke a method on an external webservice (over the Internet) it throws me "The remote server returned an error: (407) Proxy Authentication Required."</p> <p>To solve this, I used the following code to set the proxy we use in the office:</p> <pre><code>//Set the system proxy with valid server address or IP and port. System.Net.WebProxy pry = new System.Net.WebProxy("MyHost", 8080); //The DefaultCredentials automically get username and password. pry.Credentials = System.Net.CredentialCache.DefaultCredentials; System.Net.WebRequest.DefaultWebProxy = pry; </code></pre> <p>That works fine, but now... I need to do that "less harcoded" trying to get the information from my system instead of setting that manually. </p>
<p>This will use whatever the default proxy is for IE I believe (not deprecated):</p> <pre><code>Services.MyService service = new Services.MyService(); service.UseDefaultCredentials = true; service.Proxy = new System.Net.WebProxy(); service.Proxy.Credentials = service.Credentials; </code></pre>
<p>System.Net.WebProxy.GetDefaultProxy() although VS cautions its been deprecated.</p>
36,099
<p>I have a lot of changes in a working folder, and something screwed up trying to do an update.</p> <p>Now when I issue an 'svn cleanup' I get:</p> <pre><code>&gt;svn cleanup . svn: In directory '.' svn: Error processing command 'modify-wcprop' in '.' svn: 'MemPoolTests.cpp' is not under version control </code></pre> <p>MemPoolTests.cpp is a new file another developer added and was brought down in the update. It did not exist in my working folder before.</p> <p>Is there anything I can do to try and move forward <strong>without</strong> having to checkout a fresh copy of the repository?</p> <p><strong>Clarification:</strong> Thanks for the suggestions about moving the directory out of the way and bringing down a new copy. I know that is an option, but it is one I'd like to avoid since there are many changes nested several directories deep (this should have been a branch...)</p> <p>I'm hoping for a more aggressive way of doing the cleanup, maybe someway of forcing the file SVN is having trouble with back into a known state (and I tried deleting the working copy of it ... that didn't help).</p>
<p>When starting all over is not an option...</p> <p>I deleted the log file in the <code>.svn</code> directory (I also deleted the offending file in <code>.svn/props-base</code>), did a cleanup, and resumed my update.</p>
<p>It might not apply in all situations, but when I recently encountered this problem my "fix" was to upgrade the Subversion package on my system. I had been running 1.4.something, and when I upgraded to the latest (1.6.6 in my case) the checkout worked.</p> <p>(I did try re-downloading it, but a checkout to a clean directory always hung at the same spot.)</p>
19,191
<p>What techniques are available to profile services running in WebMethods Integration Server?</p> <p>That is, to obtain data which would indicate which parts would benefit most from optimisation.</p>
<p>Check the 'Service Profiler for webMethods Integration Server' from <a href="http://www.wrightia.com/serviceprofiler.html" rel="nofollow noreferrer">http://www.wrightia.com/serviceprofiler.html</a> </p>
<p>I was involved only in development phase so i dont know details but our system was tested with heavy load-testing and hardware was monitored during the process, it actually gave some feedback about bottlenecks. JMeter and sar were used.</p>
26,617
<p>I need to output some JavaScript in a WebControl based on some processing and some properties that the consumer can set, doing it on the load of the page will be to early.</p> <p>When is the latest I can call RegisterClientScriptBlock and still have it output on the page?</p>
<p>OnPreRender</p> <p>or, if you override Render.... before calling "base.Render"</p>
<p>Logically, your startup script needs to be rendered as well as registered on the page, so the Page_PreRender event would seem to be a good bet. After that the HTML and Script for the page is 'locked'.</p>
31,570
<p>I need to export a SL DataGrid to HTML so my users can then print it. Can someone put me in the right direction?</p> <p>Upate: After reading Rob's answer I am changing my question. Instead of Silverlight Grid to HTML, I now just want to export it to PDF. Has anyone used any 3rd party PDF generators with Silverlight?</p>
<p>I did this and it seems to work:</p> <p>Handle the <code>SelectedIndexChanged</code> for the <code>tabControl</code>. Check if <code>tabControl1.SelectedIndex</code> == the one I want and call <code>textBox.Focus();</code></p> <p>I'm using VS 2008, BTW.</p> <hr> <p>Something like this worked:</p> <pre><code>private void tabControl1_selectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 1) { textBox1.Focus(); } } </code></pre>
<p>Try the TabPage.Enter something like</p> <pre> private void tabPage1_Enter(object sender, EventArgs e) { TabPage page = (TabPage)sender; switch (page.TabIndex) { case 0: textBox1.Text = "Page 1"; if (!textBox1.Focus()) textBox1.Focus(); break; case 1: textBox2.Text = "Page 2"; if (!textBox2.Focus()) textBox2.Focus(); break; default: throw new InvalidOperationException(); } } </pre>
21,644
<p>I'm storing an object (<code>TTF_Font</code>) in a <code>shared_ptr</code> that is provided to me from a third-party API. I cannot use new or delete on the object, so the <code>shared_ptr</code> is also provided a "freeing" functor.</p> <pre><code>// Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr&lt;TTF_Font&gt; screenFont; screenFont = boost::shared_ptr&lt;TTF_Font&gt;( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); </code></pre> <p>If, later, I need to explicitly free this object is it correct to do this:</p> <pre><code>screenFont.reset(); </code></pre> <p>And then let <code>screenFont</code> (the actual <code>shared_ptr</code> object) be destroyed naturally?</p>
<p>shared_ptr&lt;>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr&lt;> will be freed.</p> <p>So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.</p> <p>To be clear, the normal usage of shared_ptr&lt;> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr&lt;> would be naturally destructed.</p>
<p>Mike B's answered your question, so I'll just comment on your code. If <code>TTF_OpenFont</code> doesn't return null, or if <code>TTF_CloseFont</code> can handle nulls harmlessly, you don't need a <code>CloseFont</code> class at all, just use <code>&amp;TTF_CloseFont</code>.</p>
18,917
<p>I'd like to periodically run an arbitrary .NET exe under a specified user account from a Windows Service. </p> <p>So far I've got my windows service running with logic to decide what the target process is, and when to run it. The target process is started in the following manner:</p> <ol> <li>The Windows Service is started using "administrator" credentials.</li> <li>When the time comes, an intermediate .NET process is executed with arguments detailing which process should be started (filename, username, domain, password).</li> <li>This process creates a new System.Diagnostics.Process, associates a ProcessStartInfo object filled with the arguments passed to it, and then calls Start() on the process object.</li> </ol> <p>The <strong>first time</strong> this happens, <strong>the target process executes fine and then closes normally</strong>. Every subsequent time however, as soon as the target process is started it throws the error "Application failed to initalize properly (0xc0000142)". Restarting the Windows Service will allow the process to run successfully once again (for the first execution).</p> <p>Naturally, the goal is to have target process execute successfully every time.</p> <p>Regarding step 2 above: To run a process as a different user .NET calls the win32 function CreateProcessWithLogonW. This function requires a window handle to log the specified user in. Since the Windows Service isn't running in Interactive Mode it has no window handle. This intermediate process solves the issue, as it has a window handle which can be passed to the target process.</p> <p>Please, no suggestions of using psexec or the windows task planner. I've accepted my lot in life, and that includes solving the problem in the manner stated above.</p>
<p>I seem to have a working implementation (Works On My Machine(TM)) for the following scenarios:</p> <p>Batch File, .NET Console Assembly, .NET Windows Forms application.</p> <p>Here's how:</p> <p>I have a windows service running as the Administrator user. I add the following policies to the Administrator user:</p> <ul> <li>Log on as a service </li> <li>Act as part of the operating system</li> <li>Adjust memory quotas for a process </li> <li>Replace a process level token</li> </ul> <p>These policies can be added by opening Control Panel/ Administrative Tools / Local Security Policy / User Rights Assignment. Once they are set, the policies don't take effect until next login. You can use another user instead of the Administrator, which might make things a bit safer :)</p> <p>Now, my windows service has the required permissions to start jobs as other users. When a job needs to be started the service executes a seperate assembly ("Starter" .NET console assembly) which initiates the process for me.</p> <p>The following code, located in the windows service, executes my "Starter" console assembly:</p> <pre><code>Process proc = null; System.Diagnostics.ProcessStartInfo info; string domain = string.IsNullOrEmpty(row.Domain) ? "." : row.Domain; info = new ProcessStartInfo("Starter.exe"); info.Arguments = cmd + " " + domain + " " + username + " " + password + " " + args; info.WorkingDirectory = Path.GetDirectoryName(cmd); info.UseShellExecute = false; info.RedirectStandardError = true; info.RedirectStandardOutput = true; proc = System.Diagnostics.Process.Start(info); </code></pre> <p>The console assembly then starts the target process via interop calls:</p> <pre><code>class Program { #region Interop [StructLayout(LayoutKind.Sequential)] public struct LUID { public UInt32 LowPart; public Int32 HighPart; } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { public LUID Luid; public UInt32 Attributes; } public struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public LUID_AND_ATTRIBUTES[] Privileges; } enum TOKEN_INFORMATION_CLASS { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, MaxTokenInfoClass } [Flags] enum CreationFlags : uint { CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_NO_WINDOW = 0x08000000, CREATE_PROTECTED_PROCESS = 0x00040000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_SEPARATE_WOW_VDM = 0x00001000, CREATE_SUSPENDED = 0x00000004, CREATE_UNICODE_ENVIRONMENT = 0x00000400, DEBUG_ONLY_THIS_PROCESS = 0x00000002, DEBUG_PROCESS = 0x00000001, DETACHED_PROCESS = 0x00000008, EXTENDED_STARTUPINFO_PRESENT = 0x00080000 } public enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } public enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation } [Flags] enum LogonFlags { LOGON_NETCREDENTIALS_ONLY = 2, LOGON_WITH_PROFILE = 1 } enum LOGON_TYPE { LOGON32_LOGON_INTERACTIVE = 2, LOGON32_LOGON_NETWORK, LOGON32_LOGON_BATCH, LOGON32_LOGON_SERVICE, LOGON32_LOGON_UNLOCK = 7, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NEW_CREDENTIALS } enum LOGON_PROVIDER { LOGON32_PROVIDER_DEFAULT, LOGON32_PROVIDER_WINNT35, LOGON32_PROVIDER_WINNT40, LOGON32_PROVIDER_WINNT50 } #region _SECURITY_ATTRIBUTES //typedef struct _SECURITY_ATTRIBUTES { // DWORD nLength; // LPVOID lpSecurityDescriptor; // BOOL bInheritHandle; //} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; #endregion struct SECURITY_ATTRIBUTES { public uint Length; public IntPtr SecurityDescriptor; public bool InheritHandle; } [Flags] enum SECURITY_INFORMATION : uint { OWNER_SECURITY_INFORMATION = 0x00000001, GROUP_SECURITY_INFORMATION = 0x00000002, DACL_SECURITY_INFORMATION = 0x00000004, SACL_SECURITY_INFORMATION = 0x00000008, UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000, UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000, PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000, PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 } #region _SECURITY_DESCRIPTOR //typedef struct _SECURITY_DESCRIPTOR { // UCHAR Revision; // UCHAR Sbz1; // SECURITY_DESCRIPTOR_CONTROL Control; // PSID Owner; // PSID Group; // PACL Sacl; // PACL Dacl; //} SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR; #endregion [StructLayoutAttribute(LayoutKind.Sequential)] struct SECURITY_DESCRIPTOR { public byte revision; public byte size; public short control; // public SECURITY_DESCRIPTOR_CONTROL control; public IntPtr owner; public IntPtr group; public IntPtr sacl; public IntPtr dacl; } #region _STARTUPINFO //typedef struct _STARTUPINFO { // DWORD cb; // LPTSTR lpReserved; // LPTSTR lpDesktop; // LPTSTR lpTitle; // DWORD dwX; // DWORD dwY; // DWORD dwXSize; // DWORD dwYSize; // DWORD dwXCountChars; // DWORD dwYCountChars; // DWORD dwFillAttribute; // DWORD dwFlags; // WORD wShowWindow; // WORD cbReserved2; // LPBYTE lpReserved2; // HANDLE hStdInput; // HANDLE hStdOutput; // HANDLE hStdError; //} STARTUPINFO, *LPSTARTUPINFO; #endregion struct STARTUPINFO { public uint cb; [MarshalAs(UnmanagedType.LPTStr)] public string Reserved; [MarshalAs(UnmanagedType.LPTStr)] public string Desktop; [MarshalAs(UnmanagedType.LPTStr)] public string Title; public uint X; public uint Y; public uint XSize; public uint YSize; public uint XCountChars; public uint YCountChars; public uint FillAttribute; public uint Flags; public ushort ShowWindow; public ushort Reserverd2; public byte bReserverd2; public IntPtr StdInput; public IntPtr StdOutput; public IntPtr StdError; } #region _PROCESS_INFORMATION //typedef struct _PROCESS_INFORMATION { // HANDLE hProcess; // HANDLE hThread; // DWORD dwProcessId; // DWORD dwThreadId; } // PROCESS_INFORMATION, *LPPROCESS_INFORMATION; #endregion [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process; public IntPtr Thread; public uint ProcessId; public uint ThreadId; } [DllImport("advapi32.dll", SetLastError = true)] static extern bool InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision); const uint SECURITY_DESCRIPTOR_REVISION = 1; [DllImport("advapi32.dll", SetLastError = true)] static extern bool SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR sd, bool daclPresent, IntPtr dacl, bool daclDefaulted); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] extern static bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out IntPtr phNewToken); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken ); #region GetTokenInformation //BOOL WINAPI GetTokenInformation( // __in HANDLE TokenHandle, // __in TOKEN_INFORMATION_CLASS TokenInformationClass, // __out_opt LPVOID TokenInformation, // __in DWORD TokenInformationLength, // __out PDWORD ReturnLength //); #endregion [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation( IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength ); #region CreateProcessAsUser // BOOL WINAPI CreateProcessAsUser( // __in_opt HANDLE hToken, // __in_opt LPCTSTR lpApplicationName, // __inout_opt LPTSTR lpCommandLine, // __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, // __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, // __in BOOL bInheritHandles, // __in DWORD dwCreationFlags, // __in_opt LPVOID lpEnvironment, // __in_opt LPCTSTR lpCurrentDirectory, // __in LPSTARTUPINFO lpStartupInfo, // __out LPPROCESS_INFORMATION lpProcessInformation); #endregion [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateProcessAsUser( IntPtr Token, [MarshalAs(UnmanagedType.LPTStr)] string ApplicationName, [MarshalAs(UnmanagedType.LPTStr)] string CommandLine, ref SECURITY_ATTRIBUTES ProcessAttributes, ref SECURITY_ATTRIBUTES ThreadAttributes, bool InheritHandles, uint CreationFlags, IntPtr Environment, [MarshalAs(UnmanagedType.LPTStr)] string CurrentDirectory, ref STARTUPINFO StartupInfo, out PROCESS_INFORMATION ProcessInformation); #region CloseHandle //BOOL WINAPI CloseHandle( // __in HANDLE hObject // ); #endregion [DllImport("Kernel32.dll")] extern static int CloseHandle(IntPtr handle); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid); [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TokPriv1Luid { public int Count; public long Luid; public int Attr; } //static internal const int TOKEN_QUERY = 0x00000008; internal const int SE_PRIVILEGE_ENABLED = 0x00000002; //static internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; internal const int TOKEN_QUERY = 0x00000008; internal const int TOKEN_DUPLICATE = 0x0002; internal const int TOKEN_ASSIGN_PRIMARY = 0x0001; #endregion [STAThread] static void Main(string[] args) { string username, domain, password, applicationName; username = args[2]; domain = args[1]; password = args[3]; applicationName = @args[0]; IntPtr token = IntPtr.Zero; IntPtr primaryToken = IntPtr.Zero; try { bool result = false; result = LogonUser(username, domain, password, (int)LOGON_TYPE.LOGON32_LOGON_NETWORK, (int)LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT, out token); if (!result) { int winError = Marshal.GetLastWin32Error(); } string commandLine = null; #region security attributes SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR(); IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(sd)); Marshal.StructureToPtr(sd, ptr, false); InitializeSecurityDescriptor(ptr, SECURITY_DESCRIPTOR_REVISION); sd = (SECURITY_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(SECURITY_DESCRIPTOR)); result = SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false); if (!result) { int winError = Marshal.GetLastWin32Error(); } primaryToken = new IntPtr(); result = DuplicateTokenEx(token, 0, ref processAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken); if (!result) { int winError = Marshal.GetLastWin32Error(); } processAttributes.SecurityDescriptor = ptr; processAttributes.Length = (uint)Marshal.SizeOf(sd); processAttributes.InheritHandle = true; #endregion SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES(); threadAttributes.SecurityDescriptor = IntPtr.Zero; threadAttributes.Length = 0; threadAttributes.InheritHandle = false; bool inheritHandles = true; //CreationFlags creationFlags = CreationFlags.CREATE_DEFAULT_ERROR_MODE; IntPtr environment = IntPtr.Zero; string currentDirectory = currdir; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.Desktop = ""; PROCESS_INFORMATION processInformation; result = CreateProcessAsUser(primaryToken, applicationName, commandLine, ref processAttributes, ref threadAttributes, inheritHandles, 16, environment, currentDirectory, ref startupInfo, out processInformation); if (!result) { int winError = Marshal.GetLastWin32Error(); File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + " " + winError + Environment.NewLine); } } catch { int winError = Marshal.GetLastWin32Error(); File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + " " + winError + Environment.NewLine); } finally { if (token != IntPtr.Zero) { int x = CloseHandle(token); if (x == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); x = CloseHandle(primaryToken); if (x == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); } } } </code></pre> <p>The basic procedure is:</p> <ol> <li>Log the user on</li> <li>convert the given token into a primary token</li> <li>Using this token, execute the process</li> <li>Close the handle when finished.</li> </ol> <p>This is development code fresh from my machine and no way near ready for use in production environments. The code here is still buggy - For starters: I'm not sure whether the handles are closed at the right point, and there's a few interop functions defined above that aren't required. The separate starter process also really annoys me. Ideally I'd like all this Job stuff wrapped up in an assembly for use from our API as well as this service. If someone has any suggestions here, they'd be appreciated.</p>
<p>You do not need a window handle to use CreateProcessWithLogonW, I'm not sure where your information came from.</p> <p>The application failed to initialize error has many causes, but it is almost always related to security or exhausted user resources. It is extremely difficult to diagnose this without a lot more information about what you are running and the context that you're running in. But things to look into are: does the user provided have the correct permissions to access the executable file's directory, does the user have permission to access the window station and desktop in which it is being launched, does it have correct permissions on any dll files it needs to load at initialization, etc.</p>
47,297
<p>I wondered if anyone can give an example of a professional use of RSS/Atom feeds in a company product. Does anyone use feeds for other things than updating news?</p> <p>For example, did you create a product that gives results as RSS/Atom feeds? Like price listings or current inventory, or maybe dates of training lessons?</p> <p>Or am I thinking in a wrong way of use cases for RSS/Atom feeds anyway?</p> <p><strong>edit</strong> @<a href="https://stackoverflow.com/users/573/abyx">abyx</a> has a really good example of a somewhat unexpected use of RSS as a way to get <em>debug</em> information from program transactions. I like the idea of this process. This is the type of use I was thinking of - besides publishing search results or last changes (like <a href="http://www.mediawiki.org" rel="nofollow noreferrer">mediawiki</a>)</p>
<p>Some of my team's new systems generate RSS feeds that the developers syndicate. These feeds push out events that interest the developers at certain times and the information is controlled using different loggers. Thus when debugging you can get the debugging feed, when you want to see completed transactions you go to the transactions feeds etc. This allows all the developers to get the information they want in a comfortable way and without any need to mess a lot with configuration. If you don't want to get it there's no need to remove yourself from a mailing list or edit a configuration file - simply remove the feed and <em>be done with it</em>.</p> <p>Very cool, and the idea was stolen from Pragmatic Project Automation.</p>
<p>I have seen RSS used to syndicate gas prices from a service for a specific zip code.</p>
3,691
<p>I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...</p> <pre><code>exec sp_executesql N'SELECT [t0].[CustomerID] FROM [dbo].[Customers] AS [t0] WHERE [t0].[ContactName] LIKE @p0 ORDER BY [t0].[CompanyName]', 'N'@p0 nvarchar(2)',@p0=N'c%' </code></pre> <p>...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.</p> <p>Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.</p> <pre><code>var customers = from c in context.Customers where c.CompanyName.StartsWith("c") orderby c.CompanyName select c.CustomerID; foreach (var CustomerID in customers.TagWith("CustomerList4")) { Console.WriteLine(CustomerID); } </code></pre> <p>If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.</p>
<p>These are my favorite shortcuts:</p> <ul> <li><kbd>cmd</kbd>+<kbd>t</kbd> Start typing name of a file to open it</li> <li><kbd>ctrl</kbd>+<kbd>w</kbd> Select word</li> <li><kbd>cmd</kbd>+<kbd>r</kbd> Run the ruby or php-script that is open</li> <li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>m</kbd> Define a new macro</li> <li><kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>m</kbd> Run the macro</li> <li><kbd>opt</kbd> Switch to vertical selection mode</li> <li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>a</kbd> Edit ends of selected lines</li> </ul>
<p>(these are mostly html-related) </p> <ul> <li><kbd>cmd</kbd> + <kbd>option</kbd> <kbd>+</kbd> closes current open html tag </li> <li><kbd>shift</kbd> + <kbd>cmd</kbd> + <kbd>w</kbd> wrap selection in tags</li> <li><kbd>ctrl</kbd> + <kbd>return</kbd> insert escaped line end, i.e. <code>\n</code> or <code>&lt;br&gt;</code> depending on the occasion. </li> </ul>
12,504
<blockquote> <pre><code>List&lt;tinyClass&gt; ids = new List&lt;tinyClass(); ids.Add(new tinyClass(1, 2)); bool b = ids.IndexOf(new tinyClass(1, 2)) &gt;= 0; //true or false? </code></pre> </blockquote> <p>If it compares by value, it should return true; if by reference, it will return false.<br> If it compares by reference, and I make tinyClass a struct - will that make a difference?</p>
<p>From MSDN:</p> <blockquote> <p>This method determines equality using the default equality comparer EqualityComparer&lt;T&gt;.Default for T, the type of values in the list.</p> <p>The Default property checks whether type T implements the System.IEquatable&lt;T&gt; generic interface and if so returns an EqualityComparer&lt;T&gt; that uses that implementation. Otherwise it returns an EqualityComparer&lt;T&gt; that uses the overrides of Object.Equals and Object.GetHashCode provided by T.</p> </blockquote> <p>It seems like it uses the Equals method, unless the stored class implements the IEquatable&lt;T&gt; interface.</p>
<p>Be sure to implement .Equals(..) for your struct, as the default implementation may use reflection to compare each field, which is very expensive. </p> <p>Read more at: <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx" rel="nofollow noreferrer">http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx</a></p>
21,197
<p>I'm terrible with regex, but I've had a try and a Google (and even looked in reddit's source) and I'm still stuck so here goes:</p> <p>My aim is to match the following 'codes' and replace them with the HTML tags. It's just the regex I'm stuck with.</p> <pre><code>**bold text** _italic text_ ~hyperlink~ </code></pre> <p>Here's my attempts at the bold one:</p> <pre><code>^\*\*([.^\*]+)\*\*$ </code></pre> <p>Why this isn't working? I'm using the preg syntax.</p>
<p>use:</p> <pre><code>\*\*(.[^*]*)\*\* </code></pre> <p>explanation:</p> <pre><code>\*\* // match two *'s (. // match any character [^*] // that is not a * *) // continuation of any character \*\* // match two *'s </code></pre> <p>in a character class "[ ]" "^" is only significant if it's the first character. so <code>(.*)</code> matches anything, <code>(.[^*]*)</code> is match anything until literal *</p> <p><strong>edit</strong>: in response to comments to match asterisk within (ie <code>**bold *text**</code>), you'd have to use a non greedy match:</p> <pre><code>\*\*(.*?)\*\* </code></pre> <p>character classes are more efficient non greedy matches, but it's not possible to group within a character class (<a href="http://www.regular-expressions.info/brackets.html" rel="nofollow noreferrer">see</a> "Parentheses and Backreferences...")</p>
<pre><code>\*\*(.*?)\*\* </code></pre> <p>that will work for the <strong>bold text</strong>.</p> <p>just replace the ** with _ or ~ for the others</p>
39,011
<p>I know there is a Jackpot API <a href="http://jackpot.netbeans.org/docs/org-netbeans-modules-jackpot/overview-summary.html" rel="nofollow noreferrer">http://jackpot.netbeans.org/docs/org-netbeans-modules-jackpot/overview-summary.html</a> for programmatic access the the rules engine, has anyone had success seperating this from NetBeans itself? So it can operate on any Java source files?</p>
<p>It is impossible to prove anything without building upon guarentees, so the first thing you want to do is to get familiar with the memory model of your target platform; Java and x86 both have solid and standardized memory models - I'm not so sure about CLR, but if all else fails, you'll have build upon the memory model of your target CPU architecture. The exception to this rule is if you intend to use a language that does does not allow any shared mutable state at all - I've heard Erlang is like that.</p> <p>The first problem of concurrency is shared mutable state.</p> <p>That can be fixed by:</p> <ul> <li>Making state immutable</li> <li>Not sharing state</li> <li>Guarding shared mutable state by the <em>same</em> lock (two different locks cannot guard the same piece of state, unless you <em>always</em> use exactly these two locks)</li> </ul> <p>The second problem of concurrency is safe publication. How do you make data available to other threads? How do you perform a hand-over? You'll the solution to this problem in the memory model, and (hopefully) in the API. Java, for instance, has many ways to publish state and the java.util.concurrent package contains tools specifically designed to handle inter-thread communication.</p> <p>The third (and harder) problem of concurrency is locking. Mismanaged lock-ordering is the source of dead-locks. You can analytically prove, building upon the memory model guarentees, whether or not dead-locks are possible in your code. However, you need to design and write your code with that in mind, otherwise the complexity of the code can quickly render such an analysis impossible to perform in practice.</p> <p>Then, once you have, or before you do, prove the correct use of concurrency, you will have to prove single-threaded correctness. The set of bugs that can occur in a concurrent code base is equal to the set of single-threaded program bugs, plus all the possible concurrency bugs.</p>
<p>@Just in case: I is. But from what i learnt, doing so for a non trivial algorithm is a major pain. I leave that sort of a thing for brainier people. I learnt what i know from Parallel Program Design: A Foundation (1988) by K M Chandy, J Misra </p>
10,004
<p>I'm experimenting with an updated build system at work; currently, I'm trying to find a good way to set compiler &amp; flags depending on the target platform. </p> <p>What I would like to do is something like</p> <pre><code>switch $(PLATFORM)_$(BUILD_TYPE) case "Linux_x86_release" CFLAGS = -O3 case "Linux_x86_debug" CFLAGS = -O0 -g case "ARM_release" CC = armcc AR = armlink CFLAGS = -O2 -fx ... </code></pre> <p>which is not supported by GNU Make. Now, my first thought was to just do</p> <pre><code>-include $(PLATFORM)_$(BUILD_TYPE) </code></pre> <p>which is a pretty decent solution, however, it makes it hard to get an overview of what differs between files, not to mention that I'm looking forward to writing &amp; maintaining a good 60-80 files, each containing a set of variable definitions.</p> <p>Does anyone happen to know a better way to accomplish this? I.e. setting a set of flags and other options based on another variable?</p>
<p>How about:</p> <pre><code>CFLAGS_Linux_x86_release = -O3 CFLAGS_Linux_x86_debug = -O0 -g CFLAGS = ${CFLAGS_${PLATFORM}_${BUILD}} </code></pre>
<p>Switching to a system which does it for you (automake/autoconf) may be simpler...</p>
24,413
<p>I know there is a list-comprehension library for common lisp (<a href="http://superadditive.com/projects/incf-cl/" rel="noreferrer">incf-cl</a>), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme?</p> <p>incf-cl is implemented in CL as a library using macros - shouldn't it be possible to use the same techniques to create one for Scheme?</p>
<ul> <li><a href="http://docs.plt-scheme.org/swindle/index.html" rel="noreferrer">Swindle</a> is primarily a CLOS emulator library, but it has list comprehensions too. I've used them, they're convenient, but the version I used was buggy and incomplete. (I just needed generic functions.)</li> <li>However, you probably want <a href="http://srfi.schemers.org/srfi-42/srfi-42.html" rel="noreferrer">SRFI-42</a>. I haven't used it, but it HAS to have fewer bugs than the Swindle list comprehensions.</li> </ul> <p>I don't know which Scheme you use. <a href="http://www.plt-scheme.org" rel="noreferrer">PLT Scheme</a> bundles Swindle and SRFI-42. Both are supposed to be cross-Scheme compatible, though.</p> <p>If you use PLT Scheme, here is SRFI-42's <a href="http://docs.plt-scheme.org/srfi/srfi-42.html" rel="noreferrer">man page</a>. You say <code>(require srfi/42)</code> to get it.</p>
<p>You can use <a href="https://ironscheme.svn.codeplex.com/svn/IronScheme/IronSchemeConsole/ironscheme/linq.ss" rel="nofollow noreferrer">LINQ for R6RS Scheme</a> (although it could be made to run under 'older' implementations).</p>
15,911
<p>I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint. The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value. The simplified tables are:</p> <pre> import_table: part_number varchar(30) quantity int inventory_master: part_number varchar(30) type char(1) </pre> <p>So I want to ensure the <code>part_number</code> exists in <code>inventory_master</code>, but only if the type is 'C'. Is this possible? Thanks.</p>
<p>You can also do it this way:</p> <pre><code>select columnproperty(object_id('mytable'),'mycolumn','IsIdentity') </code></pre> <p>Returns 1 if it's an identity, 0 if not.</p>
<p>As expansion on @Blogbeard's answer</p> <p>If you like pure query and not inbuilt functions</p> <pre><code>select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns join sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id where sys.all_objects.name = 'system_files' </code></pre>
22,921
<p>In my Application_Start() method, how can I stop the execution of the ASP.NET application when certain conditions are not met?</p> <p>Throwing an exception doesn't appear to work.</p>
<p>i don't think that's possible; even if you could 'abort' the startup, the next attempt to access a URL from the site would try to start it again</p> <p>perhaps a static variable could be used to signal go/no-go, and begin_request could redirect to a placeholder page instead?</p>
<p>Do something that throws an unhandled error. Maybe throwing an Exception would be enough.</p>
49,800
<p>Or vice versa.</p> <p>Update:<br> Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button. The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could <code>Button.PostBackURL = "Invoice.aspx"</code></p> <p>or I could do </p> <pre><code>Server.Transfer("Invoice.aspx") </code></pre> <p>(I also changed the title since the method is called Transfer and not TransferURL)</p>
<ul> <li>Server.TransferURL will not result in a roundtrip of HTTP request/response. The address bar will not update, as far as the browser knows it has received only one document. Server.Transfer also retains execution context, so the script "keeps going" as opposed to "starts anew".</li> <li>PostbackURL ensures an HTTP request, resulting in a possibly different URL and of course incurring network latency costs.</li> </ul> <p>Usually when you are attempting to "decide between the two" it means you are better off using PostbackURL. </p> <p>Feel free to expand your question with specifics and we can look at your precise needs.</p>
<p>Server.Transfer is done entirely from the server. Postback is initiated from the client for posting form contents and postback url identifies the page to post to.</p> <p>Maybe you meant to compare with Response.Redirect, which forces the client to submit a new request for a new url.</p>
9,159
<p>I've been given the task of working with SAML to implement an SSO solution between my company and a third party provider. My only issue is that I can't seem to find how to implement SAML in C# 2.0. I've been able to find a few examples for .Net 3.0 and 3.5, but none for 2.0 (and the classes they use don't appear to be available in 2.0). Does anyone know of any oline examples using SAML and C# 2.0?</p>
<p>Unless you can find a third party implementation, you are going to have to upgrade beyond v2.0. Probobly not what you want to hear, sorry...</p>
<p>I'm sorry to be this late but I had the same problem you were having. But I've found an excellent solution in .NET 2.0 namely OIOSAML.NET (currently v. 1.4).</p> <p><a href="http://www.softwareborsen.dk/projekter/softwarecenter/brugerstyring/oiosaml.net/releases/1.4/oiosaml-dot-net-v1-4.zip" rel="nofollow noreferrer">http://www.softwareborsen.dk/projekter/softwarecenter/brugerstyring/oiosaml.net/releases/1.4/oiosaml-dot-net-v1-4.zip</a></p>
38,410
<p>I'm using Tomcat 5.5 as my servlet container. My web application deploys via .jar and has some resource files (textual files with strings and configuration parameters) located under its WEB-INF directory. Tomcat 5.5 runs on ubuntu linux. The resource file is read with a file reader:<br> <code>fr = new FileReader("messages.properties");</code></p> <p>The problem is that sometimes the servlet can't find the resource file, but if i restart it a couple of times it works, then again after some time it stops working. Can someone suggest what's the best way of reading resource strings from a servlet? Or a workaround for this problem? Putting the resource files under WEB-INF/classes doesn't help either.</p>
<p>I'm guessing the problem is you're trying to use a relative path to access the file. Using absolute path should help (i.e. "/home/tomcat5/properties/messages.properties").</p> <p>However, the usual solution to this problem is to use the getResourceAsStream method of the ClassLoader. Deploying the properties file to "WEB-INF/classes" will make it available to the class loader and you'll be able to access the properties stream.</p> <p>Untested proto-code:</p> <pre><code>Properties props = new Properties(); InputStream is = getClass().getClassLoader().getResourceAsStream("messages.properties"); props.load(is); </code></pre>
<p>I did used for Jboss Seam: </p> <p><code>ServletLifecycle.getServletContext().getRealPath("")</code></p>
38,217
<p>I suppose this question could just as easily be applied to PHP with regard to MSSQL. However, with some versions of MSSQL being so expensive, I always wondered, what is the real advantage of choosing it over MySQL for .NET development? Is it really difficult to use .NET tools in conjunction with a MySQL database? Why not create some sort of DAO that abstracts out the differences between the two so that you can use both? As I consider building .NET apps, I'm always wondering, should I just go with MSSQL, and not even consider MySQL as an option?</p>
<p>Typically, the fact MySQL came so late to the stored procedure party has kept many away from the database. However, I do like the database and use it with some regularity in my "outside the office" time. Did you know the BO ships Crystal with MySQL as its choice datasource?</p> <p>As for .NET and what to do? If you do not need the advanced features, then I would recommend SQL Express Edition. </p>
<p>I've been using <a href="http://www.nhibernate.org/" rel="nofollow noreferrer">NHibernate</a> ORM as a way of abstracting MySQL, MSSQL and others. Perhaps it could work for you.</p>
31,810
<p>I am looking to do the following (see pseudo code); I want to select 4 rows for each gd.id (7, 11 or 9). I've incorrectly use limit because that only brings up 4 rows in total. Anyone have an idea on how to change this query to accomplish my goal? </p> <pre><code>SELECT gd.gid, gd.aid, li.ads, li.til FROM gd JOIN li ON li.a_id = gd.aid WHERE gd.gid IN ( '7', '11', '9' ) ORDER BY li.timestamp DESC LIMIT 4 #FOR EACH ;-) </code></pre> <p>Thank you!</p> <p>Ice</p> <p>p.s. Maybe sometype of group_by?</p>
<p>Okay I'm posting this second answer now that I understand the relationship between your tables.</p> <pre><code>CREATE TABLE gd ( aid INT AUTO_INCREMENT PRIMARY KEY, gid INT ); INSERT INTO gd (gid) VALUES (7), (7), (7), -- fewer than four rows (9), (9), (9), (9), -- exactly four rows (11), (11), (11), (11), (11); -- greater than four rows CREATE TABLE li ( a_id INT AUTO_INCREMENT PRIMARY KEY, ads VARCHAR(10), til VARCHAR(10), `timestamp` TIMESTAMP ); INSERT INTO li (ads, til, `timestamp`) VALUES ('foo1', 'bar1', '2008-01-01'), ('foo2', 'bar2', '2008-02-01'), ('foo3', 'bar3', '2008-03-01'), ('foo4', 'bar4', '2008-04-01'), ('foo5', 'bar5', '2008-05-01'), ('foo6', 'bar6', '2008-06-01'), ('foo7', 'bar7', '2008-07-01'), ('foo8', 'bar8', '2008-08-01'), ('foo9', 'bar9', '2008-09-01'), ('foo10', 'bar10', '2008-10-01'), ('foo11', 'bar11', '2008-11-01'), ('foo12', 'bar12', '2008-12-01'); </code></pre> <p>So you want the top four rows per value of <code>gd.gid</code>, depending on the <code>timestamp</code> value in the associated table <code>li</code>.</p> <pre><code>SELECT g1.gid, g1.aid, l1.ads, l1.til, l1.`timestamp` FROM gd AS g1 INNER JOIN li AS l1 ON (g1.aid = l1.a_id) LEFT OUTER JOIN ( gd AS g2 INNER JOIN li AS l2 ON (g2.aid = l2.a_id) ) ON (g1.gid = g2.gid AND l1.`timestamp` &lt;= l2.`timestamp`) WHERE g1.gid IN ('7', '11', '9') GROUP BY g1.aid HAVING COUNT(*) &lt;= 4 ORDER BY g1.gid ASC, l1.`timestamp` DESC; </code></pre> <p>The output is the following:</p> <pre><code>+------+-----+-------+-------+---------------------+ | gid | aid | ads | til | timestamp | +------+-----+-------+-------+---------------------+ | 7 | 3 | foo3 | bar3 | 2008-03-01 00:00:00 | | 7 | 2 | foo2 | bar2 | 2008-02-01 00:00:00 | | 7 | 1 | foo1 | bar1 | 2008-01-01 00:00:00 | | 9 | 7 | foo7 | bar7 | 2008-07-01 00:00:00 | | 9 | 6 | foo6 | bar6 | 2008-06-01 00:00:00 | | 9 | 5 | foo5 | bar5 | 2008-05-01 00:00:00 | | 9 | 4 | foo4 | bar4 | 2008-04-01 00:00:00 | | 11 | 12 | foo12 | bar12 | 2008-12-01 00:00:00 | | 11 | 11 | foo11 | bar11 | 2008-11-01 00:00:00 | | 11 | 10 | foo10 | bar10 | 2008-10-01 00:00:00 | | 11 | 9 | foo9 | bar9 | 2008-09-01 00:00:00 | +------+-----+-------+-------+---------------------+ </code></pre>
<p>the usual approach is:</p> <p>(SELECT * FROM table WHERE key=X LIMIT 4) UNION ALL (SELECT * FROM table WHERE key=Y LIMIT 4) UNION ALL (SELECT * FROM table WHERE key=Z LIMIT 4) ORDER BY ... LIMIT ...</p> <p>do note, it will materialize each subselect in the temptable, so isn't very efficient if your outer LIMIT is low, and internal ones are high. </p>
38,913
<p>(MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.</p>
<p>You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually is. So, if you want to draw a line from the top left corner of the bottom right corner of the current viewport, you do need GetViewPortOrg() and GetViewportExt(). If these return the wrong values, something is wrong in your use of CScrollView. Did you call SetScrollSizes()?</p>
<p>Inside your OnDraw() function, you could call pDC->GetViewportOrg and pDC->GetViewportExt.</p> <p><strong>EDIT</strong>: Sorry, I forgot that Viewport extents are only scaling factors. I agree that what you really need here is the client rect.</p>
17,734
<p>I am searching for all drives and their contents. I don't want to search network drives. How can I determine if a given drive is network mounted? What I would want further is to get similar information one gets using NET USE command?</p>
<p>You want the <a href="http://msdn.microsoft.com/en-us/library/aa364939.aspx" rel="noreferrer">GetDriveType</a> function.</p>
<p>Also if you would like to add remove drives or check status, check this article out:</p> <p><a href="http://support.microsoft.com/kb/173011" rel="nofollow noreferrer">http://support.microsoft.com/kb/173011</a></p> <p>That's using the win32 api.</p>
16,701
<p>I'm making a simple jquery command:</p> <p><code>element.html("&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;");</code></p> <p>using the attributes/html method: <a href="http://docs.jquery.com/Attributes/html" rel="nofollow noreferrer">http://docs.jquery.com/Attributes/html</a></p> <p>It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.</p> <p>So instead of <code>" "</code> <em>(6 spaces)</em> it's just <code>""</code>. </p> <p>Once again, this is running on App Engine, but I don't think that should matter...</p>
<p>You could try generating the space during run-time, so it won't be trimmed or whatever happens during transport:</p> <pre><code>element.html(String.fromCharCode(32)); </code></pre>
<p>Is there a possibility that the code is minified as part of the process of being deployed onto the App Engine?</p> <p>I would not expect any string of whitespace to be retained as written, perhaps you could actually escape the white space and force any minification to leave it:</p> <p>example:</p> <pre><code>element.html('\ \ \ \ \ \ \ \ \ \ \ \ ');</code></pre>
17,824
<p>How can I pass arguments to a constructor in an IOC-framework? I want to do something like: (Trying to be IOC-framework agnostic ;) )</p> <pre><code>object objectToLogFor = xxx; container.Resolve&lt;ILogging&gt;(objectToLogFor); public class MyLogging : ILogging { public MyLogging(object objectToLogFor){} } </code></pre> <p>It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong.</p> <p>Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?</p>
<p>In structure map you could achieve this using the With method:</p> <pre><code>string objectToLogFor = "PolicyName"; ObjectFactory.With&lt;string&gt;(objectToLogFor).GetInstance&lt;ILogging&gt;(); </code></pre> <p>See: <a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx" rel="nofollow noreferrer">http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx</a></p>
<p>Yes, other frameworks are more feature-rich - you need to use an ioc framework that allows for constructor injection. Spring is an example of a multi-language ioc container that allows constructor dependency injection.</p>
15,728
<p>I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using</p> <pre><code>Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url) </code></pre> <p>For short URLs like "<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored.</p> <p>Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?</p>
<p>You will be running up against <a href="https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html" rel="nofollow noreferrer">this (archived)</a> operating system/browser specific maximum URL length problem:</p> <p>For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://).</p> <p>From where I sit you have two alternatives:</p> <ol> <li><p>Build (or use) a TinyURL-style service that turns your long-urls into short, redirected ones. However even here you are going to run into the same URL length issue, just within the browser itself rather than your Runtime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail. </p></li> <li><p>Use a POST request and bury some or all of your URL parameters within it. Rather than using a GET call you can supply very long parameters within the body of an HTTP POST request. This would not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...</p></li> </ol>
<p>It will also depend on the version of windows, because you may be exceeding the operating system's <code>MAX_PATH</code> length on the command line?</p>
30,028
<p>I'm not sure if Jeff coined it but it's the joke/saying that people who say "oh, I know I'll use regular expressions!" now have <a href="http://www.codinghorror.com/blog/archives/001016.html" rel="nofollow noreferrer">two problems</a>. I've always taken this to mean that people use regular expressions in very <a href="http://thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx" rel="nofollow noreferrer">inappropriate contexts</a>. </p> <p>However, under what circumstances are regular expressions really the best answer? What problems are they really the best or maybe only way to solve a situation?</p>
<p>RexExprs are good for: </p> <ul> <li>Text Format Validations (email, url, numbers)</li> <li>Text searchs/substitution.</li> <li>Mappings (e.g. url pattern to function call)</li> <li>Filtering some texts (related to substitution)</li> <li>Lexical analysis during parsing.</li> </ul>
<p>Regular expressions are a great way to parse text that doesn't already have a parser (i.e. XML) I have used it to create a parser for the mod_rewrite syntax in the .htaccess file or in my URL Rewriter project <a href="http://www.codeplex.com/urlrewriter" rel="nofollow noreferrer">http://www.codeplex.com/urlrewriter</a> for example</p>
28,511
<p>My company has an existing established WinForm application which in running on WinXP. The application does alot of sound processing using DirectSound.</p> <p>My company would like to evaluate Mono, as an alternative on a per workstation cost to Vista/Win Server 2008.</p> <p>I've heard that different estimates, ranging from 'it will work easily on Mono' to 'it could take months of recoding in certain cases to get a WinForm app to run with Mono on Linux'.</p> <p>Does anyone have a good real world experience with this? A good link reference? I would like to get a better idea before I commit to testing.</p> <p>Thanks!</p>
<p>The WinForms part will be easy, you may have to do very little as Mono now claims to support Winforms 100%, however all the DirectSound calls will have to be rewritten to use an API available on Linux, ALSA being the obvious choice.</p> <p>I have written small apps in VS 2005 and ported them with ease to Mono. If you do a lot of P/Invokes, then you'll have to take that into account, as those may have to be completely rewritten or rethought.</p> <p>Also, check out <a href="http://www.mono-project.com/MoMA" rel="noreferrer">MOMA</a>: "The Mono Migration Analyzer (MoMA) tool helps you identify issues you may have when porting your .Net application to Mono. It helps pinpoint platform specific calls (P/Invoke) and areas that are not yet supported by the Mono project."</p>
<p>Mono can help you move the managed code, but it will not help you move the audio layer.</p> <p>Sadly, the .NET framework does not provide a comprehensive API for audio processing. It merely provides a way of playing back a small sound sample, and it is not even very good at this (See Jeroen's post about audio gaps when running the C64 emulator under IKVM).</p> <p>You will have to research which Linux API maps best to what your audio application is doing. </p> <p>Lennart Poettering blog entry on audio is an excellent starting point:</p> <p><a href="http://0pointer.de/blog/projects/guide-to-sound-apis.html" rel="nofollow noreferrer">http://0pointer.de/blog/projects/guide-to-sound-apis.html</a></p> <p>Once you decide on an API, just like in Windows, you will have to P/Invoke the API that is right for you.</p>
25,394
<p>So apparently the wiring in my home is... questionable. Very rarely, plugging or unplugging things will cause a power dip. This is almost always the result of turning on a fan or something, is only for a moment before coming back, but its long enough to cause my printer to reset. I want to add a backup battery supply using either the 12v cell pulled out of an old apc ups (before the suggestion of just plugging it into that... I did, somethings fried in it and it will ALSO power cycle everything connected to it every few hours) or an old car battery. Is there any reason I shouldn't use this circuit, which was originally intended for amateur radio equipment? <a href="https://i.stack.imgur.com/Jd7Sp.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jd7Sp.gif" alt="battery backup circuit"></a></p> <p>Also is there anything else i should be considering?</p>
<p>There are a couple of points to consider with this question. First, you will need to make sure the PSU is correctly adjusted to the float charge voltage of the 12V battery. SLA should be safe to float charge, but over voltage will damage it over time.</p> <p>One alternative solution (since powering the heaters will limit your run time) is to detect power failure, cut the heaters immediately, and save state to EEPROM in the firmware. This is the approach taken in the latest Prusa printers, and is a bit more complex, but might turn out to be more reliable.</p> <p>If the problem you are solving really is brown-outs, then a simpler solution might be to isolate the high current and control sides of the circuit. The MCU will be run from a regulated 5V or 3V3, so a large capacitor (with diode isolation) on that regulator's input would do the trick.</p>
<p>This circuit is correct as it does the job (provides a charge and switch-over when needed). </p> <p>The only drawback could be that you need to ensure that the battery is sealed as during the charging process the electlorit will slowly evaporate and decrease battery capacity.</p> <p>I am personally using a UPC as that gives me more options to power-up more stuff including 240V heater and it has a self-test built-in (it is APC1500VA).</p>
1,008
<p>I am a Web developer who spends 99% of his time in Linux, but I need to develop a super simple application with VB or possibly C# (.Net). The only version of Visual Studio I have is the most current free ones. There MIGHT be a copy of 2001 lying around somewhere. Anyways, the machine I need to develop this for is running Windows NT4. I cannot change this because another piece of software runs on that requires it. </p> <p>Is there a way to develop an app with the new VS and keep it compatible with such an old version of the .Net framework (1.1)? </p> <p>If nothing else I could install Perl on the machine and write a command line type script, but given the people that will be using it GUI would be better.</p>
<p>I don't believe you can target .Net 1.1 in Visual Studio 2008. Here's one of the developer's explanations, from a comment in <a href="http://blogs.msdn.com/lukeh/archive/2007/06/29/net-framework-multitargeting-in-visual-studio-2008-aka-orcas.aspx" rel="nofollow noreferrer">this blog entry</a>:</p> <blockquote> <p>Visual Studio 2008 will not support targeting .Net Framework 1.1. This is something we really wanted to be able to support - since we know there are a lot of .NET developers working on .NET 1.1 applications. However, it would have been significantly more difficult to go back and support .NET 1.1 which was a substantially different runtime.</p> <p>Thus, to fit in this release, the decision ended up being either to not support multitargeting at all - or to support only targeting .NET2.0 and greater. Because we really wanted Visual Studio 2008 to be a great tool for at least both .NET 3.0 and .NET 3.5 - we decided to put in the most multitargeting support we could fit in this release.</p> </blockquote>
<p>Have you tried <a href="http://msdn.microsoft.com/en-us/vs2005/aa718347.aspx" rel="nofollow noreferrer">MSBee</a>? This is an add-on to VS2005 (well, strictly speaking: MSBuild in 2.0), but it may well work with VS2008 too. Of course, you can always use the IDE to write code, and simply use MSBuild from the 2.0 folder to build...</p> <p>Either way, if you target .NET 1.1, you can only use .NET 1.1 / C# 1.2 features.</p> <p><strike>Personally, I'd target 3.5SP1, using (if it needs to be free) C# Express 2008.</strike> (I've removed this since you need to target such an old OS)</p>
34,828
<p>In .NET 3.5, I'm going to be working with System.Reflection to use AOP (probably in the context of Castle's Windsor Interceptors) to do things like define which security actions need to be performed at the method level, etc. I have heard that some parts of Reflection are slow (I've read the MSDN article around it), and would like to cache these parts (when I get closer to production code, at any rate). I would like to validate my approach:</p> <ul> <li>cache key is {type} + {case sensitive method name} + {list of parameter types}</li> <li>cache key objects can be compared via an Equals operation</li> <li>cache payload is a {MethodInfo} + {list of custom-attributes defined on the method}</li> <li>cache is injected to my interceptors via constructor injection</li> <li>cache can be maintained for a long time (based on the assumption that I'm not going to be writing self-modifying code ;-) )</li> </ul> <p>Update:</p> <p>I'm not intending to call methods via Reflection something I'm writing myself; just (at the moment) look up attributes on the ones I want to inject functionality into, where the attributes define the behaviour to inject. My interceptors at the moment will be using Castle's Windsor IInterceptor mechanism until I notice a reason to change it.</p>
<p>Explicitly calling a MethodInfo is indeed slow - but you can make it much, <em>much</em> faster if you convert it into a delegate. See <a href="http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx" rel="nofollow noreferrer">this blog post</a> for example. That doesn't help in terms of finding methods etc of course, but if you're going to call the method repeatedly it's worth bearing in mind.</p> <p>The cache key sounds easy enough to build - types and strings compare nice and easily. Values are always relatively simple :)</p> <p>Once built, is the cache going to be read-only? Can you separate out the phases so that you can guarantee it won't be read before being fully built? If so, you should be able to get away without any explicit locking - basically a dictionary from your custom key type to your custom value type.</p>
<p>I'd agree with most of Jon's post - a small note re the dictionary: from a performance perspective, you might want to benchmark this vs just a flat list. Last time I did a benchmark (dictionary vs flat list, checking each item until match found), the dividing point (for read access) was around 150 items; below that, the list was quicker (just through simplicity). But do your own tests... (I don't have the numbers to hand to prove one way or another).</p> <p>Depending on the code, you might be able to use generics to further split the data - i.e. a Cache so that all the info for type T is in one place, populated in the static ctor for Cache. This may or may not be possible, depending on the architecture.</p> <p>Finally, it might or might not fit, but there are existing AOP frameworks like PostSharp that might help simplify the injection points.</p> <p>Re the generic point - it would be fairly easy to (in your init code) create a typed delegate to a method on the Cache method, to reduce the amount of data it needs to scan through - just a bit of Type.MakeGenericType and and Delegate.CreateDelegate - after this point, the code just knows about your Func&lt;...> delegate, and doesn't need to care about the implementation.</p>
23,564
<p>I have a table class that creates modifies a table of items. I want to display those items in a JTable using a table model. To me table model belongs to my GUI package but table needs table model in order to fire changes and table model needs table class in order to display it so I can not separate the two. if you need to do this what would be the class structure you use? or do I have a flow in my thinking and they belong in the same package?</p>
<p>A <code>TableModel</code> is an <em>adapter</em>. I always write the table model to extends <code>AbstractTableModel</code> and have it as a private inner class of my GUI panel class. You only have to fill in a few methods: <code>getRowCount</code>, <code>getColumnCount</code> and <code>getValueAt</code></p> <p>Your GUI class should have access to some <em>controller</em> where it can fill in this information from. When your controller finds out about updates to the data, it should inform your GUI class which can then call <code>AbstractTableModel.fireTableDataChanged</code> or other appropriate methods.</p> <p><strong>Never</strong> use the <code>DefaultTableModel</code> class because you then have to keep the table model's data in sync with the controller's. As I said, the table model is an adapter which presents the controller's data in a way which the <code>JTable</code> can understand </p>
<p>The table model doesn't need to know anything about the table that it's put in. I put the table model in the model package, and the table in the view package. The controller is responsible for asking the model package for the model, asking the view package for the table, and setting that model in the table.</p>
20,162
<p>I know how to move a layer based on touch. But I would also like to be able to rotate the image. </p> <p>Is there any sample code that shows how to do this? Or can anyone give me some advice?</p> <p>Thanks!</p>
<p>The simplest way to do this is using the layer's transform property:</p> <pre><code>float angle = M_PI; //rotate 180°, or 1 π radians layer.transform = CATransform3DMakeRotation(angle, 0, 0.0, 1.0); </code></pre> <p>The first argument to the CATransform3DMakeRotation function is the amount to rotate, in radians. The next three describe the vector around which to rotate. This is describing a vector in the z-axis, so effectively perpendicular to the screen. This will rotate the layer so it's upside down. </p>
<p>You should look at Apple's <a href="https://developer.apple.com/iphone/library/samplecode/MoveMe/index.html" rel="nofollow noreferrer">MoveMe</a> example for how to move around a layer based on touch. It also applies some scaling transforms as you do it, so that should serve as a reasonable example of to apply rotation transforms.</p>
30,010
<p>How can I get the value between quotes with an RegEx</p> <p>for example I want to find all the parameters from the function test</p> <pre><code>&lt;html&gt; test("bla"); print("foo"); test("moo"); &lt;/html&gt; </code></pre> <p>The result must be { "bla", "moo" }</p>
<p>If you just want the args to <code>test</code>, you'll need to include that in the regex:</p> <pre><code> StringBuilder sb = new StringBuilder("{"); bool first = true; foreach (Match match in Regex.Matches(html, @"test\((""[^\""]*\"")\)")) { if(first) {first = false;} else {sb.Append(',');} sb.Append(match.Groups[1].Value); } sb.Append('}'); Console.WriteLine(sb); </code></pre> <p>From the question, I am using quote detection here.</p> <p>Alternatively - if you just want the values:</p> <pre><code> foreach (Match match in Regex.Matches(html, @"test\(""([^\""]*)\""\)")) { Console.WriteLine(match.Groups[1].Value); } </code></pre> <p>The main change here is that the group is now inside the quotes.</p>
<p>edit: Removed old code and made a linq version...</p> <pre><code> var array = (from Match m in Regex.Matches(inText, "\"\\w+?\"") select m.Groups[0].Value).ToArray(); string json = string.Format("{{{0}}}", string.Join(",", array)); </code></pre>
36,499
<p>What <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="noreferrer">CAPTCHA</a> system is compatible with ASP.NET MVC? Are there any good examples out there?</p>
<p><a href="http://www.coderjournal.com/2008/03/aspnet-mvc-captcha/" rel="nofollow noreferrer">Try this post</a></p> <p>Source code can be found here if you don't have the patience to read the article: <a href="http://www.coderjournal.com/uploads/2008/03/captcha.zip" rel="nofollow noreferrer">zip file</a></p>
<p>Check out <a href="http://weblogs.asp.net/awilinsk/archive/2008/12/09/recaptchamvc.aspx" rel="nofollow noreferrer">RecaptchaMvc</a>. It's a framework that uses the reCAPTCHA service and ASP.NET MVC.</p>
32,329
<h3>Update: Solved, with code</h3> <p><a href="https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056">I got it working, see my answer below for the code...</a></p> <h3>Original Post</h3> <p>As Tundey pointed out in <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456">his answer</a> to my <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">last question</a>, you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? <a href="http://www.codeproject.com/KB/cs/UserSettings.aspx" rel="nofollow noreferrer">This tutorial</a> says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:</p> <pre><code>public Size RestoreSize { get { if (this.WindowState == FormWindowState.Normal) { return this.Size; } else { return this.RestoreBounds.Size; } } set { ... } } </code></pre> <p>But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).</p>
<p>I finally came up with a Form subclass that solves this, once and for all. To use it:</p> <ol> <li>Inherit from RestorableForm instead of Form.</li> <li>Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState.</li> <li>Call Properties.Settings.Default.Save() when the window is about to close.</li> </ol> <p>Now window position and state will be remembered between sessions. Following the suggestions from other posters below, I included a function ConstrainToScreen that makes sure the window fits nicely on the available displays when restoring itself.</p> <h3>Code</h3> <pre><code>// Consider this code public domain. If you want, you can even tell // your boss, attractive women, or the other guy in your cube that // you wrote it. Enjoy! using System; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; namespace Utilities { public class RestorableForm : Form, INotifyPropertyChanged { // We invoke this event when the binding needs to be updated. public event PropertyChangedEventHandler PropertyChanged; // This stores the last window position and state private WindowRestoreStateInfo windowRestoreState; // Now we define the property that we will bind to our settings. [Browsable(false)] // Don't show it in the Properties list [SettingsBindable(true)] // But do enable binding to settings public WindowRestoreStateInfo WindowRestoreState { get { return windowRestoreState; } set { windowRestoreState = value; if (PropertyChanged != null) { // If anybody's listening, let them know the // binding needs to be updated: PropertyChanged(this, new PropertyChangedEventArgs("WindowRestoreState")); } } } protected override void OnClosing(CancelEventArgs e) { WindowRestoreState = new WindowRestoreStateInfo(); WindowRestoreState.Bounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; WindowRestoreState.WindowState = WindowState; base.OnClosing(e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (WindowRestoreState != null) { Bounds = ConstrainToScreen(WindowRestoreState.Bounds); WindowState = WindowRestoreState.WindowState; } } // This helper class stores both position and state. // That way, we only have to set one binding. public class WindowRestoreStateInfo { Rectangle bounds; public Rectangle Bounds { get { return bounds; } set { bounds = value; } } FormWindowState windowState; public FormWindowState WindowState { get { return windowState; } set { windowState = value; } } } private Rectangle ConstrainToScreen(Rectangle bounds) { Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds); Rectangle workingArea = screen.WorkingArea; int width = Math.Min(bounds.Width, workingArea.Width); int height = Math.Min(bounds.Height, workingArea.Height); // mmm....minimax int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left)); int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top)); return new Rectangle(left, top, width, height); } } } </code></pre> <h3>Settings Bindings References</h3> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.settingsbindableattribute.aspx" rel="noreferrer">SettingsBindableAttribute</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" rel="noreferrer">INotifyPropertyChanged</a></li> </ul>
<p>Well I have had a quick play with this and you are correct, while there is no way to directly <em>bind</em> the size of the form to AppSettings, you can add your own values and change the size on load.</p> <p>I would perhaps recommend that if this is a common feature, you subclass Form and make it automatically prob the App.Config for the forms size settings.</p> <p>(Or you could roll your own file.. Get it to query an Xml file "formname.settings.xml" or something? - thinking out loud!)..</p> <p>Heres what I had (very rough, no error checking etc).</p> <h2>App.Config</h2> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key ="FormHeight" value="500" /&gt; &lt;add key ="FormWidth" value="200"/&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <h2>Form Code</h2> <pre><code> private void Form1_Load(object sender, EventArgs e) { string height = ConfigurationManager.AppSettings["FormHeight"]; int h = int.Parse(height); string width = ConfigurationManager.AppSettings["FormWidth"]; int w = int.Parse(width); this.Size = new Size(h, w); } </code></pre>
3,912
<p>I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?</p>
<p>This can now be done purely in markup. Just add an <code>applicationName</code> attribute to the <code>errorLog</code> element in the <code>&lt;elmah&gt;</code> section of the web.config file. Example:</p> <pre><code>&lt;errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="connectionString" applicationName="myApp" /&gt; </code></pre> <p>I've tested this and it works both when logging an exception and when viewing the log via <code>Elmah.axd</code>.</p> <p>In the case of the OP, one would imagine it can be set programatically too but I didn't test that. For me and I imagine for most scenarios the markup approach is sufficient.</p>
<p>By default, Elmah uses the AppPool's application GUID as the default application name. It uses this as the key to identify the errors in the Elmah_Error table when you look at the web interface that's created through it's HTTP Module. </p> <p>I was tasked to explore this option for my company earlier this year. I couldn't find a way to manipulate this by default since Elmah pulls the application name from <code>HttpRuntime.AppDomainAppId</code> in the ErrorLog.cs file. You could manipulate it by whatever key you want; however, that is the AppPool's GUID.</p> <p>With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName. What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:</p> <pre><code>public virtual string ApplicationName { get { if (_applicationName == null) { _applicationName = HttpRuntime.AppDomainAppId; } return _applicationName; } set { _applicationName = value; } } </code></pre> <p>What you will probably need to do is adjust this differently and set the ApplicationName not to <code>HttpRuntime.AppDomainAppId</code> but, instead, a value pulled from the web.config. All in all, it's possible. The way I did it enhanced the <code>ErrorLog.Log(ex)</code> method so I could use Elmah has a callable framework beyond web applications. Looking back I wish I did the app/web.config approach instead. </p> <p>One thing to keep in mind when changing the application name in Elmah. The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.</p>
18,469
<p>I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?</p>
<p>Use the <code>RUBY_PLATFORM</code> constant, and optionally wrap it in a module to make it more friendly:</p> <pre><code>module OS def OS.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def OS.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def OS.unix? !OS.windows? end def OS.linux? OS.unix? and not OS.mac? end def OS.jruby? RUBY_ENGINE == 'jruby' end end </code></pre> <p>It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.</p>
<p>When I just need to know if it is a Windows or Unix-like OS it is often enough to </p> <pre><code>is_unix = is_win = false File::SEPARATOR == '/' ? is_unix = true : is_win = true </code></pre>
20,618
<p>I'm checking for existing of a row in in_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.</p> <pre><code>select count(*) from in_fmd i where (description='GN') and ( i.isbn in ( select bwi_isbn from bw_isbn where orig_isbn = ? union all select cast(? as varchar) as isbn ) ) </code></pre> <p>I don't actually care about the count of the rows, but rather mere existence of at least one row.</p> <p>This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement. It's PostgreSQL 8.1, if it matters.</p>
<p>Why bother with the <code>UNION ALL</code></p> <pre><code>select count(*) from in_fmd i where (description='GN') and ( i.isbn in ( select bwi_isbn from bw_isbn where orig_isbn = ? ) or i.isbn = cast(? as varchar) ) </code></pre> <p>I would probably use a <code>LEFT JOIN</code>-style query instead of the <code>IN</code>, but that's more personal preference:</p> <pre><code>select count(*) from in_fmd i left join bw_isbn on bw_isbn.bwi_isbn = i.isbn and bw_isbn.orig_isbn = ? where (i.description='GN') and ( bw_isbn.bwi_isbn is not null or i.isbn = cast(? as varchar) ) </code></pre> <p>The inversion discussed over IM:</p> <pre><code>SELECT SUM(ct) FROM ( select count(*) as ct from in_fmd i inner join bw_isbn on bw_isbn.bwi_isbn = i.isbn and bw_isbn.orig_isbn = ? and i.isbn &lt;&gt; cast(? as varchar) and i.description = 'GN' UNION select count(*) as ct from in_fmd i where i.isbn = cast(? as varchar) and i.description = 'GN' ) AS x </code></pre>
<pre><code>select count(*) from in_fmd i where description = 'GN' and exists (select 1 from bwi_isbn where bw_isbn.bwi_isbn = in_fmd.isbn) </code></pre>
30,821
<p>I'm having issues with color matching css background colors with colors in images on the same html page. What gives?</p>
<p>I'm guessing that you use a PNG image? This is a gamma correction “feature”. Mark Ransom has posted a <a href="https://stackoverflow.com/questions/115818/which-format-for-small-website-images-gif-or-png#128390">useful text</a> about this.</p> <p>Notice that the <code>pngcrush</code> solution listed somewhere hasn't worked for me.</p>
<p>Probably the browser your testing, I've had a lot of trouble with ie 6. </p>
18,674
<p>I want to create a bundle from an arbitrary bundle identifier<br> e.g. <code>com.apple.iokit.IOStorageFamily</code> </p> <p>It's not an unreasonable thing to do as bundle IDs are supposed<br> to be unique, however the obvious code does not work:</p> <pre><code>NSString* bID = @"com.apple.iokit.IOStorageFamily"; NSBundle* bundle = [NSBundle bundleWithIdentifier:bID]; </code></pre> <p>This code only works for bundles you've already loaded<br> (hello, chicken and egg problem), and in fact, you have<br> to know a little more than you'd like about the the identifier<br> before you can do anything. For the above style of ID<br> I grep out the final component and tranform it into<br> <code>/System/Library/Extensions/IOStorageFamily.kext</code><br> which I then load by path. </p> <p>Is this the state of the art or is there a more general way? </p>
<p>Use this</p> <pre><code>NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"]; </code></pre>
<p>If what you're looking for is definitely a kext, then you could look at the info dictionary for each bundle in the /S/L/Es/ folder until you find yours. There's no search for bundle by identifier apart from for Applications (where LaunchServices will do it), and loaded bundles as you've already found.</p>
24,018