input
stringlengths
51
42.3k
output
stringlengths
18
55k
Silverlight Hosted in Winforms <p>I would like to host a silverlight control in winforms via a winforms browser, but for it to work I need some way for the forms to talk to the silverlight, and also the other way around. Would it be possible to somehow have the two interact with each other using JavaScript as a middleman? I.e., have the form speak to the browser's javascript, and have that speak to the silverlight control? Is there a better way? Or even a way at all? (other than compiling the code as silverlight and wpf)</p>
<p>I think using the Windows Forms WebBrowser control is your best bet. To do this, you'll need your Silverlight app on a webpage, then you point your WebBrowser at the page's URI.</p> <p>To keep your WebBrowser control from acting like IE, I'd recommend setting the following:</p> <pre><code>webBrowser.AllowNavigation = false; webBrowser.AllowWebBrowserDrop = false; webBrowser.IsWebBrowserContextMenuEnabled = false; webBrowser.WebBrowserShortcutsEnabled = false; </code></pre> <p>Calling methods on your form from within Silverlight is easy enough to do. To start, you need a class that has all the methods you want to call from Silverlight. You can use your form itself or another object, but you need to mark the class with the [ComVisible(true)] attribute. Then you assign your object to the WebBrowser.ObjectForScripting property. This exposes your object as "window.external" on the webpage.</p> <pre><code>[ComVisible(true)] public partial class Form1 : Form { ...... webBrowser.ObjectForScripting = this; ...... public void CallMeInForm(string something) { MessageBox.Show("Silverlight said: " + something); } } </code></pre> <p>That's it for inside your Windows Forms project. Inside of your Silverlight app, you need to pick up this ObjectForScripting and invoke methods on it. To call the method in my example above, use the following lines:</p> <pre><code>using System.Windows.Browser; ...... ScriptObject myForm = (ScriptObject)HtmlPage.Window.GetProperty("external"); myForm.Invoke("CallMeInForm", "testing 1 2 3"); </code></pre> <p>The Invoke command lets you pass any number and type of parameters to your function, although I suspect it wouldn't like it very much if you try passing complex datatypes around. But if you needed to do so, you could always use serialization.</p> <p>Calling Silverlight functions from your form seems to be the tricker direction. I haven't figured this one out completely yet.</p> <p>In your Silverlight app, you also expose functions to the webpage. To do this, use the HtmlPage.RegisterScriptableObject() function. Again, you can pass in any class with methods you want to expose. For a method to be exposed, though, you have to mark it with the [ScriptableMember] attribute.</p> <pre><code>HtmlPage.RegisterScriptableObject("Page", this); ...... [ScriptableMember] public void CallMeInSilverlight(string message) { HtmlPage.Window.Alert("The form said: " + message); } </code></pre> <p>At this point, your method is exposed to JavaScript on the page and you could call it like so, assuming you added <code>id="silverlightControl"</code> to your <code>&lt;object&gt;</code> element:</p> <pre><code>document.getElementById('silverlightControl').Content.Page.CallMeInSilverlight("testing 1 2 3"); </code></pre> <p>Notice the <code>Page</code> property? That's what the call to <code>RegisterScriptableObject()</code> gave us. Now, let's wrap this into a tidy JavaScript method:</p> <pre><code>&lt;script type="text/javascript"&gt; function CallMe(message) { var control = document.getElementById('silverlightControl'); control.Content.Page.CallMeInSilverlight(message); } &lt;/script&gt; </code></pre> <p>And now we can call the <code>CallMe()</code> method from the Windows Forms app like so:</p> <pre><code>public void CallToSilverlight() { webBrowser.InvokeScript("CallMe", new object[] { "testing 1 2 3" }); } </code></pre>
How to get a random number in Ruby <p>How do I generate a random number between <code>0</code> and <code>n</code>?</p>
<p>What is wrong with <a href="http://www.ruby-doc.org/core-2.1.3/Kernel.html#method-i-rand"><code>rand(range)</code></a>?</p> <p>From <a href="http://www.codeodor.com/index.cfm/2007/3/25/Ruby-random-numbers/1042">Ruby Random Numbers</a>:</p> <blockquote> <p>If you needed a random integer to simulate a roll of a six-sided die, you'd use: <code>1 + rand(6)</code>. A roll in craps could be simulated with <code>2 + rand(6) + rand(6)</code>.</p> <p>Finally, if you just need a random float, just call <code>rand</code> with no arguments.</p> </blockquote> <hr> <p>As <a href="http://stackoverflow.com/users/8279/marc-andre-lafortune">Marc-André Lafortune</a> mentions in <a href="http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866">his answer below (go upvote it)</a>, <a href="http://www.ruby-lang.org/en/news/2009/07/20/ruby-1-9-2-preview-1-released/">Ruby 1.9.2 has its own <code>Random</code> class</a> (that Marc-André himself <a href="http://redmine.ruby-lang.org/issues/show/3104">helped to debug</a>, hence the <a href="http://redmine.ruby-lang.org/versions/show/11">1.9.2 target</a> for that feature).</p> <p>For instance, in this <a href="http://www.eggheadcafe.com/software/aspnet/35817496/random-integer-within-a-r.aspx">game where you need to guess 10 numbers</a>, you can initialize them with:</p> <pre><code>10.times.map{ 20 + Random.rand(11) } #=&gt; [26, 26, 22, 20, 30, 26, 23, 23, 25, 22] </code></pre> <p>Note: </p> <ul> <li><p>Using <code>Random.new.rand(20..30)</code> (using <code>Random.new</code>) generally would not be a good idea, as explained in detail (again) by <a href="http://stackoverflow.com/users/8279/marc-andre-lafortune">Marc-André Lafortune</a>, in <a href="http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866">his answer</a> (again).</p></li> <li><p>But if you don't use <code>Random.new</code>, then the <a href="http://www.ruby-doc.org/core/classes/Random.src/M000693.html">class method <code>rand</code></a> only takes a <code>max</code> value, not a <code>Range</code>, as <a href="http://stackoverflow.com/users/66725/banister">banister</a> (energetically) points out in the comment (and as documented in the <a href="http://www.ruby-doc.org/core/classes/Random.html">docs for <code>Random</code></a>). Only the <a href="http://www.ruby-doc.org/core/classes/Random.src/M000688.html">instance method</a> can take a <code>Range</code>, as illustrated by <a href="http://stackoverflow.com/questions/5722881/generate-a-random-number-with-7-digits/5723105#5723105">generate a random number with 7 digits</a>.</p></li> </ul> <p>This is why the equivalent of <code>Random.new.rand(20..30)</code> would be <code>20 + Random.rand(11)</code>, since <code>Random.rand(int)</code> returns “a random integer greater than or equal to zero and <em>less than the argument</em>.” <code>20..30</code> includes 30, I need to come up with a random number between 0 and 11, excluding 11.</p>
How to best prevent CSRF attacks in a GAE app? <p>So, what is the best way to prevent an XSRF attack for a GAE application? Imagine the following:</p> <ol> <li>Anyone can see a user's public object, and the db.Model id is used in the request to figure out which object to show. Malicious user now has the id.</li> <li>Malicious user creates their own object and checks out the delete form. They now know how to delete an object with a certain id.</li> <li>Malicious user gets innocent user to submit a delete request for that user's object.</li> </ol> <p>What steps can I add to prevent #3? Note that when I say ID, I am using the actual ID part of the key. One idea I had was to use the full key value in delete requests, but would that prevent a malicious user from being able to figure this out? As far as I know, the key is some combination of the model class type, the app id, and the object instance id, so they could probably derive the key from the id if they wanted to.</p> <p>Any other ideas? Jeff wrote <a href="http://www.codinghorror.com/blog/archives/001171.html">a post about this</a>, and suggested a couple methods - a hidden form value that would change on each request, and a cookie value written via js to the form. I won't want to exclude non-javascript users, so the cookie solution is no good - for the hidden form value, I would have to do a datastore write on every request that displayed a deletable object - not an ideal situation for a scalable app!</p> <p>Any other ideas out there?</p>
<p>When you generate the page that lets the user delete an object, generate a random token and include it in a hidden form field. Also set a HTTP-only cookie with that value. When you receive a delete request, check that the random token from the form and the value from the cookie match.</p> <p>Your random token shouldn't just be a random number. You should encrypt the combination of a random number and the user's identity, to make it difficult for attackers to forge their own tokens. You should also use different encryption keys for the value stored in the form and the value stored in the cookie, so if one of the tokens does leak, it is still difficult for an attacker to forge the other token.</p> <p>This approach verifies that the delete request originates from your form, by the presence of the security token in the form; and doesn't require writing to the datastore.</p> <p>This approach is still vulnerable to cross-site scripting attacks, where an attacker could retrieve the hidden value from the form or submit the form, so thoroughly test your site for cross-site scripting vulnerabilities. This approach is also vulnerable to <a href="http://en.wikipedia.org/wiki/Clickjacking" title="clickjacking">"clickjacking"</a> attacks.</p>
What are optimal settings for Recycling of Application Pools in IIS7 in shared environment? <p>What are optimal settings for Recycling of Application Pools in IIS7 in a shared environment?</p> <p><img src="http://i.stack.imgur.com/RNQo8.png" alt="enter image description here"></p>
<p>As a Hoster, you definitely want to recycle on Memory &amp; Time, potentially Request limits and CPU. You want to be pretty aggressive about these limits, but make sure you publish them to your clients.</p> <p><a href="https://technet.microsoft.com/en-us/library/cc725749(v=ws.10).aspx" rel="nofollow"><strong>Memory</strong></a> - 512 for an x86 box, maybe 768. For x64, you can set this much higher depending on the number of hosts per server. You just have to be careful and watch your app pool recycle events on memory issues.</p> <p><a href="https://technet.microsoft.com/en-us/library/cc754494(v=ws.10).aspx" rel="nofollow"><strong>Time</strong></a> - We typically recycle at 1 am in the morning, plus or minus (first site 1:01, second 1:11, third 1:21, just so you don't have all recycling at the same time) </p> <p><a href="https://technet.microsoft.com/en-us/library/cc770469(v=ws.10).aspx" rel="nofollow"><strong>Request limit</strong></a> - 35,000 was the default for IIS6, but this number is quite arbitrary, and very dependant on the site in question. For small usage sites, the nightly recycle will hit long before you get 35k requests.</p> <p><a href="http://www.iis.net/configreference/system.applicationhost/applicationpools/add/cpu" rel="nofollow"><strong>CPU</strong></a> - 95%/1 minute limit/KillW3WP, but use this carefully. My understanding of this is that if the CPU hits 95%+ over the 1 minute limit for this worker process, the worker process gets killed and is unable to restart for the remainder of the limit when Action is set to KillW3WP. You might want to try NoAction initially and just watch your event logs carefully.</p> <p><a href="https://technet.microsoft.com/en-us/library/cc771318(v=ws.10).aspx" rel="nofollow"><strong>Recycle Event Logs</strong></a> - You want to make sure you are logging app pool recycles for each event threshhold that you set - i.e. if you limit based off of requests limits, make sure that Request Limit logging is enabled.</p> <p>One thing to remember is that you <em>should</em> set <code>retail="true"</code> in the <code>&lt;deployment&gt;</code> element in your <a href="http://www.iis.net/learn/get-started/planning-your-iis-architecture/the-configuration-system-in-iis-7" rel="nofollow">machine.config</a>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.web&gt; &lt;!-- &lt;deployment retail = "false" [true|false] /&gt; --&gt; &lt;deployment retail="true" /&gt; &lt;/system.web&gt; </code></pre> <p>Not setting this will allow a site to turn debugging on, which allows unlimited timeouts in requests - not exactly ideal for a hoster...</p>
Multiple Data Tables in PHP/MySQL? <p>In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php?</p> <p>Example:</p> <pre><code>$sql ="select * from t1; select * from t2;"; $result = SomeQueryFunc($sql); print_r($result[0]); // dump results for t1 print_r($result[1]); // dump results for t2 </code></pre> <p>Can you do something like this?</p>
<p>This is called "multi-query." The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi_query() method. See <a href="http://php.net/manual/en/mysqli.multi-query.php" rel="nofollow">http://php.net/manual/en/mysqli.multi-query.php</a></p> <p>Using multi-query is not recommended, because it can increase the potential damage caused by SQL injection attacks. If you use multi-query, you should use rigorous code inspection habits to avoid SQL injection vulnerability.</p>
JQuery Select Box and Loop Help <p>Thanks for reading. I'm a bit new to jQuery, and am trying to make a script I can include in all my websites to solve a problem that always drives me crazy...</p> <p>The problem: Select boxes with long options get cut off in Internet Explorer. For example, these select boxes: <a href="http://discoverfire.com/test/select.php">http://discoverfire.com/test/select.php</a></p> <p>In Firefox they are fine, but in IE, the options are cut off to the width of the select when they drop down.</p> <p>The solution: What I am looking to do, is create a script that I can include in any page that will do the following:</p> <ol> <li><p>Loop through all the selects on the page.</p></li> <li><p>For each select: A. Loop through its options. B. Find the width of the longest option. C. Bind a function to expand the select to that width on focus (or maybe click...). D. Bind a function to shrink to it's original width on blur.</p></li> </ol> <p>I've managed to do most of step #2 for one select box.</p> <p>I found that getting the options width was a problem (especially in IE), so I looped through and copied the text of each option to a span, measured the span width, and used the longest one as the width the select will be expanded to. Perhaps somebody has a better idea.</p> <p>Here is the code</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { /* This function will: 1. Create a data store for the select called ResizeToWidth. 2. Populate it with the width of the longest option, as approximated by span width. The data store can then be used */ // Make a temporary span to hold the text of the options. $('body').append("&lt;span id='CurrentOptWidth'&gt;&lt;/span&gt;"); $("#TheSelect option").each(function(i){ // If this is the first time through, zero out ResizeToWidth (or it will end up NaN). if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) { $(this).parent().data( 'OriginalWidth', $(this).parent().width() ); $(this).parent().data('ResizeToWidth', 0); $('CurrentOptWidth').css('font-family', $(this).css('font-family') ); $('CurrentOptWidth').css('font-size', $(this).css('font-size') ); $('CurrentOptWidth').css('font-weight', $(this).css('font-weight') ); } // Put the text of the current option into the span. $('#CurrentOptWidth').text( $(this).text() ); // Set ResizeToWidth to the longer of a) the current opt width, or b) itself. //So it will hold the width of the longest option when we are done ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') ); // Update parent ResizeToWidth data. $(this).parent().data('ResizeToWidth', ResizeToWidth) }); // Remove the temporary span. $('#CurrentOptWidth').remove(); $('#TheSelect').focus(function(){ $(this).width( $(this).data('ResizeToWidth') ); }); $('#TheSelect').blur(function(){ $(this).width( $(this).data('OriginalWidth') ); }); alert( $('#TheSelect').data('OriginalWidth') ); alert( $('#TheSelect').data('ResizeToWidth') ); }); &lt;/script&gt; </code></pre> <p>and the select:</p> <pre><code>&lt;select id='TheSelect' style='width:50px;'&gt; &lt;option value='1'&gt;One&lt;/option&gt; &lt;option value='2'&gt;Two&lt;/option&gt; &lt;option value='3'&gt;Three&lt;/option&gt; &lt;option value='42,693,748,756'&gt;Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... &lt;/option&gt; &lt;option value='5'&gt;Five&lt;/option&gt; &lt;option value='6'&gt;Six&lt;/option&gt; &lt;option value='7'&gt;Seven...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Hopefully this will run for you if you want to run it, or you can see it in action here: <a href="http://discoverfire.com/test/select.php">http://discoverfire.com/test/select.php</a>.</p> <p>What I need help with: This needs a bit of polish, but seems to work ok if you specify the select box.</p> <p>However, I don't seem to be able to figure out how to apply it to all select boxes on the page with a loop. So far, I have this:</p> <pre><code>$('select').each( function(i, select){ // Get the options for the select here... can I use select.each...? } ); </code></pre> <p>Also, is there a better way to get the length of the longest option for each select? The span is close, but not very exact. The problem is that IE returns zero for the option widths of the actual selects.</p> <p>Any ideas are very welcome, both for the questions asked, and any other improvements to my code.</p> <p>Thanks!!</p>
<p>To modify each select, try this:</p> <pre><code>$('select').each(function(){ $('option', this).each(function() { // your normalizing script here }) }); </code></pre> <p>The second parameter (this) on the second jQuery call scopes the selecter ('option'), so it is essentially 'all option elements within this select'. You can think of that second parameter defaulting to 'document' if it's not supplied.</p>
ColdFusion web.xml? <p>Is there a ColdFusion analog for the deployment descriptor/web.xml file found in a J2EE web container? I know CF is running on top of JRun and that I could just tweak the JRun dd, but what about an application-specific configuration file? Is there something like this that I'm not aware of or do you just have to roll your own?</p>
<p>ColdFusion 8 has several application-specific configurations that can be set in the application.cfc file</p> <p>application.cfc also implements several "general events" which occur during application execution. </p>
DoubleRenderError in restful_authentication with acts_as_state_machine when activating users <p>In a project which uses <code>restful_authentication</code> with <code>acts_as_state_machine</code> and email activation, I get a double render error whenever a user does the activation action from the email link.</p> <p>I'm using the default</p> <pre><code>def activate self.current_user = params[:activation_code].blank? ? false : User.find_by_activation_code(params[:activation_code]) if logged_in? &amp;&amp; !current_user.active? current_user.activate! flash[:notice] = "Signup complete!" end redirect_back_or_default('/') end </code></pre> <p>to activate, and the default</p> <pre><code>def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end </code></pre> <p>to redirect. The redirect method works in every other case it's called in the same way.</p> <p>The double render error occurs at the render of the page main_page/home that is routed as "/".</p> <p>What should I be looking for?</p>
<p>Acts As State Machine will sometimes have some odd behavior where the saved record written to the database will be out of sync with the object in memory. I bet you have a situation where the ruby object corresponding to the newly activated user is not being updated even though the field in the db is being set (of vice versa).</p> <p>I'd need to see the controller action that actually runs to render the route you have setup to match "/", but I bet you've got subtly inconsistent cases in that action that are being tripped up by this inconsistency in AASM. Try reloading the user object at the start of that controller action to see if the problem goes away. If not begin debugging by making sure that your state changes are actually being saved out to the db.</p>
Does Google Maps respect the <BalloonStyle> definition in KML? <p>I'm using the GGeoXml object to overlay KML on an embedded Google Map. I need to customize the popup balloon for placemarks, so I'm trying to use the <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#balloonstyle" rel="nofollow"><code>&lt;BalloonStyle&gt;</code></a> element:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Document xmlns="http://earth.google.com/kml/2.0"&gt; &lt;name&gt;Concessions&lt;/name&gt; &lt;Style id="masterPolyStyle"&gt; ... &lt;BalloonStyle&gt; &lt;text&gt; &lt;![CDATA[ &lt;h6&gt;Concession&lt;/h6&gt; &lt;h4&gt;$[name]&lt;/h4&gt; &lt;p&gt;$[description]&lt;/p&gt; ]]&gt; &lt;/text&gt; &lt;displayMode&gt;default&lt;/displayMode&gt; &lt;bgColor&gt;DDA39B81&lt;/bgColor&gt; &lt;/BalloonStyle&gt; &lt;/Style&gt; ... &lt;/Document&gt; </code></pre> <p>This works as expected in Google Earth, but the embedded map API appears to ignore this altogether. I suppose I could just leave out the <code>&lt;name&gt;</code> element altogether and just put everything in HTML inside the <code>&lt;description&gt;</code> element, but I'd like to be able to take advantage of the <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#extendeddata" rel="nofollow"><code>&lt;ExtendedData&gt;</code></a> element to display custom data in a structured way. </p>
<p>This is now documented here (2009/04):</p> <p><a href="http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html" rel="nofollow">http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html</a></p> <ul> <li>&lt; BalloonStyle > no</li> </ul> <p>(When did you ask this ? This forum/service needs a big fat DATE on each question, with a year in it :-) )</p> <p>2$c, *pike</p>
How can I add an image to my Run for a RichTextBlock? <p>I wrote a small WPF app where I like to prepend text into a RichTextBox, so that the newest stuff is on top. I wrote this, and it works: </p> <pre><code> /// &lt;summary&gt; /// Prepends the text to the rich textbox /// &lt;/summary&gt; /// &lt;param name="textoutput"&gt;The text representing the character information.&lt;/param&gt; private void PrependSimpleText(string textoutput) { Run run = new Run(textoutput); Paragraph paragraph = new Paragraph(run); if (this.RichTextBoxOutput.Document.Blocks.Count == 0) { this.RichTextBoxOutput.Document.Blocks.Add(paragraph); } else { this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph); } } </code></pre> <p>Now I would like to make a new version of that function which can add small images as well. I'm at a loss though - is it possible to add images? </p>
<p>Try the following:</p> <pre><code>BitmapImage bi = new BitmapImage(new Uri(@"C:\SimpleImage.jpg")); Image image = new Image(); image.Source = bi; InlineUIContainer container = new InlineUIContainer(image); Paragraph paragraph = new Paragraph(container); RichTextBoxOutput.Document.Blocks.Add(paragraph); </code></pre> <p>The InlineUIContainer is the "magic" here... You can add any UIElement to it. If you want to add multiple items, use a panel to wrap the items (ie. StackPanel, etc)</p>
Is it possible to initialize a const struct without using a function? <p>I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?</p>
<p>You can, if the pointers point to global objects:</p> <pre><code>// In global scope int x, y; const struct {int *px, *py; } s = {&amp;x, &amp;y}; </code></pre>
How to detect what .NET Framework versions and service packs are installed? <p>A similar question was asked <a href="http://stackoverflow.com/questions/198931/how-do-i-tell-if-net-35-sp1-is-installed">here</a>, but it was specific to .NET 3.5. Specifically, I'm looking for the following:</p> <ol> <li>What is the correct way to determine which .NET Framework versions and service packs are installed? </li> <li>Is there a list of registry keys that can be used?</li> <li>Are there any dependencies between Framework versions?</li> </ol>
<p>The registry is <a href="https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx">the official way</a> to detect if a specific version of the Framework is installed. </p> <p><img src="http://i.stack.imgur.com/hiLch.png" alt="enter image description here"></p> <p>Which registry keys are needed change depending on the Framework version you are looking for:</p> <pre> Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install </pre> <p>Generally you are looking for:</p> <pre><code>"Install"=dword:00000001 </code></pre> <p>except for .NET 1.0, where the value is a string (<code>REG_SZ</code>) rather than a number (<code>REG_DWORD</code>).</p> <p>Determining the service pack level follows a similar pattern:</p> <pre> Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing [1] Windows Media Center or Windows XP Tablet Edition </pre> <p>As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.</p> <p>For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.</p> <p>While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:</p> <pre> Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 2.0[2] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 2.0[3] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version [1] Windows Media Center or Windows XP Tablet Edition [2] .NET 2.0 SP1 [3] .NET 2.0 Original Release (RTM) </pre> <p>Again, .NET 1.0 uses a string value while all of the others use a DWORD.</p> <h2>Additional Notes</h2> <ul> <li><p>for .NET 1.0 the string value at either of these keys has a format of <code>#,#,####,#</code>. The <code>#,#,####</code> portion of the string is the Framework version.</p></li> <li><p>for .NET 1.1, we use the name of the registry key itself, which represents the version number.</p></li> <li><p>Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.</p></li> <li><p>.NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.</p></li> </ul> <h2>Update for .NET 4.5</h2> <p>There won't be a <code>v4.5</code> key in the registry if .NET 4.5 is installed. Instead you have to check if the <code>HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full</code> key contains a value called <code>Release</code>. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found <a href="http://stackoverflow.com/a/15227828/270591">here</a> and <a href="http://msdn.microsoft.com/en-us/library/hh925568.aspx">here</a>.</p>
How do I increase the /proc/pid/cmdline 4096 byte limit? <p>For my Java apps with very long classpaths, I cannot see the main class specified near the end of the arg list when using ps. I think this stems from my Ubuntu system's size limit on /proc/pid/cmdline. How can I increase this limit?</p>
<p>For looking at Java processes <a href="http://download.oracle.com/javase/6/docs/technotes/tools/share/jps.html">jps</a> is very useful.</p> <p>This will give you the main class and jvm args:</p> <pre><code>jps -vl | grep &lt;pid&gt; </code></pre>
Is there any way to get python omnicomplete to work with non-system modules in vim? <p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
<p>Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules.</p> <p>EDIT: Not true at all.</p> <p>Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it.</p> <p>The issue was that I'm working on a django project, and in order to import django.db, you need to have an environment variable set. Since I couldn't import django.db, any class that inherited from django.db, or any module that imported a class that inherited from django.db wouldn't complete.</p>
How do I reverse a UTF-8 string in place? <p>Recently, someone asked about an <a href="http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c">algorithm for reversing a string in place in C</a>. Most of the proposed solutions had troubles when dealing with non single-byte strings. So, I was wondering what could be a good algorithm for dealing specifically with utf-8 strings.</p> <p>I came up with some code, which I'm posting as an answer, but I'd be glad to see other people's ideas or suggestions. I preferred to use actual code, so I've chosen C#, as it seems to be one of the most popular language in this site, but I don't mind if your code is in another language, as long as it could be reasonably understood by anyone who is familiar with an imperative language. And, as this is intended to see how such an algorithm could be implemented at a low-level (by low-level I just mean dealing with bytes), the idea is to avoid using libraries for the core code.</p> <p><strong>Notes:</strong></p> <p>I'm interested in the algorithm itself, its performance and how could it be optimized (I mean algorithm-level optimization, not replacing i++ with ++i and such; I'm not really interested in actual benchmarks either).</p> <p>I don't mean to actually use it in production code or "reinventing the wheel". This is just out of curiosity and as an exercise.</p> <p>I'm using C# byte arrays so I'm assuming you can get the length of the string without running though the string until you find a NUL. That is, I'm not accounting for the complexity of finding the length of the string. But if you're using C, for instance, you could factor that out by using strlen() before calling the core code. </p> <p><strong>Edit:</strong></p> <p>As Mike F points out, my code (and other people's code posted here) is not dealing with composite characters. Some info about those <a href="http://www.unicode.org/faq/char_combmark.html">here</a>. I'm not familiar with the concept, but if that means that there are "combining characters", i.e., characters / code points that are only valid in combination with other "base" characters / code points, a look-up table of such characters could be used to preserve the order of the "global" character ("base" + "combining" characters) when reversing.</p>
<p>I'd make one pass reversing the bytes, then a second pass that reverses the bytes in any multibyte characters (which are easily detected in UTF8) back to their correct order.</p> <p>You can definitely handle this in line in a single pass, but I wouldn't bother unless the routine became a bottleneck.</p>
What's the best way to embed IronPython inside my C# App? <p>I have an application used by pretty tech-savey people and they want small island of programmability so I've used embedded Iron Python.</p> <p>However, since IronPython 2.0 Eval() doesn't work any more. Specifically I can't both load modules and inject local variables.</p> <p>There is a work around where I can still call Execute(), print out my answer and listen to StandardOut, but then it comes out as a string and I've lost the type.</p> <p>Not a disaster for a long, but a huge pain for more complex objects.</p> <p>Does anyone know how to get Eval() working again in 2.0 like it did in 1.x?</p> <p>Cheers, Jan</p>
<p>Could you be a little more specific about the problem, and maybe provide a code example? The "eval"-style functionality is definitely still present, though as you've noticed, the hosting interface has changed considerably since 1.0.</p> <p>This works in beta 5:</p> <pre><code>ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromString("2 + 5", SourceCodeKind.Expression); int result = source.Execute&lt;int&gt;(); </code></pre> <p>By the way, using the right <code>SourceCodeKind</code> is critical here.</p>
Whats the main difference between int.Parse() and Convert.ToInt32 <p>I am using C#,and wanted to know the main difference between the two and which one is preferred to use while coding. </p>
<ul> <li><p>If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use <a href="http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx"><strong><code>Int32.Parse()</code></strong></a>. </p></li> <li><p>If you're collecting input from a user, you'd generally use <a href="http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx"><strong><code>Int32.TryParse()</code></strong></a>, since it allows you more fine-grained control over the situation when the user enters in invalid input. </p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/System.Convert.ToInt32.aspx"><strong><code>Convert.ToInt32()</code></strong></a> takes an object as its argument, and I believe it invokes <code>Int32.TryParse()</code> when it finds that the object taken as the argument is a string. </p> <p><code>Convert.ToInt32()</code> also does not throw <code>ArgumentNullException</code> when it's argument is null the way <code>Int32.Parse()</code> does. That also means that <code>Convert.ToInt32()</code> is probably a wee bit slower than <code>Int32.Parse()</code>, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.</p></li> </ul>
Code review for VS <p>looking for a good code review tool that plugs in nicely to Visual Studio. Would be nice if it could diff from different source control providers, like Source Safe, The Vault, and/or Subversion.</p>
<p>I have used <a href="http://www.smartbear.com/codecollab.php" rel="nofollow">code collaborator</a> in the past. It is not integrated with Visual Studio but I would not let that stop you. </p> <p>All our Windows developers had no problem using it and since the reviews is done online, you are not using the IDE during the review.</p> <p>Hope this helps.</p>
I've never encountered a well written business layer. Any advice? <p>I look around and see some great snippets of code for defining rules, validation, business objects (entities) and the like, but I have to admit to having never seen a great and well-written business layer in its entirety.</p> <p>I'm left knowing what I don't like, but not knowing what a great one is.</p> <p>Can anyone point out some good OO business layers (or great business objects) or let me know how they judge a business layer and what makes one great?</p> <p>Thanks</p>
<blockquote> <p>I’ve never encountered a well written business layer.</p> </blockquote> <p>Here is <a href="http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx">Alex Papadimoulis's take on this</a>:</p> <blockquote> <p><em>[...] If you think about it, virtually every line of code in a software application is business logic:</em></p> <ul> <li><em>The Customers database table, with its CustomerNumber (CHAR-13), ApprovedDate (DATETIME), and SalesRepName (VARCHAR-35) columns: business logic. If it wasn’t, it’d just be Table032 with Column01, Column02, and Column03.</em></li> <li><em>The subroutine that extends a ten-percent discount to first time customers: definitely business logic. And hopefully, not soft-coded.</em></li> <li><em>And the code that highlights past-due invoices in red: that’s business logic, too. Internet Explorer certainly doesn’t look for the strings “unpaid” and “30+ days” and go, hey, that sure would look good with a #990000 background!</em></li> </ul> <p><em>So how then is possible to encapsulate all of this business logic in a single layer of code? With terrible architecture and bad code of course!</em></p> <p><em>[...] By implying that a system’s architecture should include a layer dedicated to business logic, many developers employ all sorts of horribly clever techniques to achieve that goal. And it always ends up in a disaster.</em></p> </blockquote>
Get last answer <p>In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like <code>Ans</code> or <code>%</code> to retrieve the last computed value. Is there a similar facility in the Python shell?</p>
<p>Underscore.</p> <pre><code>&gt;&gt;&gt; 5+5 10 &gt;&gt;&gt; _ 10 &gt;&gt;&gt; _ + 5 15 &gt;&gt;&gt; _ 15 </code></pre>
Suggestions for a Web application for a group project <p>I am doing 2nd year computer science and we have a software engineering group project. There are 5 people in the group and we would like to build a web application in php. Please suggest some ideas for me </p>
<p>Have a look a Paul Graham's list of "Startup Ideas We'd Like to Fund" - lots more ideas and the CMS has been done to death.</p> <p><a href="http://ycombinator.com/ideas.html">http://ycombinator.com/ideas.html</a></p> <p>The list in short:</p> <ol> <li>A cure for the disease of which the RIAA is a symptom.</li> <li>Simplified browsing</li> <li>New news</li> <li>Outsourced IT</li> <li>Enterprise software 2.0</li> <li>More variants of CRM</li> <li>Something your company needs that doesn't exist</li> <li>Dating</li> <li>Photo/video sharing services</li> <li>Auctions</li> <li>Web Office apps</li> <li>Fix advertising</li> <li>Online learning</li> <li>Tools for measurement</li> <li>Off the shelf security</li> <li>A form of search that depends on design</li> <li>New payment methods (tricky)</li> <li>The WebOS (si tienes 'webos', sorry Spanish joke)</li> <li>Application and/or data hosting</li> <li>Shopping guides</li> <li>Finance software for individuals and small businesses</li> <li>A web-based Excel/database hybrid</li> <li>More open alternatives to Wikipedia</li> <li>A buffer against bad customer service</li> <li>ACraigslist competitor</li> <li>Better video chat</li> <li>Hardware/software hybrids</li> <li>Fixing email overload</li> <li>Easy site builders for specific markets</li> <li>Startups for startups</li> </ol>
How do you convert a C++ string to an int? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c">How to parse a string to an int in C++?</a> </p> </blockquote> <p>How do you convert a C++ string to an int?</p> <p>Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).</p> <p>Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.</p>
<pre><code>#include &lt;sstream&gt; // st is input string int result; stringstream(st) &gt;&gt; result; </code></pre>
How do I convert CSV into an HTML table using Perl? <p>In my code, I want to view all data from a CSV in table form, but it only displays the last line. How about lines 1 and 2? Here's the data:</p> <pre><code>1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern 2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern 3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh </code></pre> <p>Here's the code:</p> <pre><code>#! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my $line; my $file; my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); $file='MyFile.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;) { ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; } close(F); print "&lt;HTML&gt;"; print "&lt;head&gt;"; print "&lt;body bgcolor='#4682B4'&gt;"; print "&lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt;"; print "&lt;div align='left'&gt;"; print "&lt;TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'&gt;"; print "&lt;TR&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;RECORD No.&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER No.&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DATE&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TIME&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE NAME&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TEST PROGRAM&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE FAMILY&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DIE LOT&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;LOADBOARD&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER &lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SERIAL NUMBER&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER CONFIG&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;PACKAGE&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SOCKET&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 1&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 2&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 3&lt;/td&gt;"; print "&lt;/tr&gt;"; print "&lt;TR&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f1&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f2&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f3&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f4&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f5&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f6&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f7&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f8&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f9&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f10&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f11&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f12&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f13&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f14&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f15&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f16&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f17&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f18&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f19&lt;/TD&gt;"; print "&lt;/tr&gt;"; print "&lt;/TABLE&gt;"; print "&lt;/body&gt;"; print "&lt;html&gt;"; </code></pre>
<p>You need to output the table rows <em>inside</em> the while loop, as that's where you are reading the lines.</p> <p>So change the code so that it</p> <ul> <li>outputs table headers</li> <li>reads the file line by line outputting table rows</li> <li>outputs table footer</li> </ul> <p>Here's how your loop might look if a little simplified...</p> <pre><code>while ($line=&lt;F&gt;) { print "&lt;tr&gt;"; my @cells= split ',',$line; foreach my $cell (@cells) { print "&lt;td&gt;$cell&lt;/td&gt;"; } print "&lt;/tr&gt;"; } </code></pre>
Apache commons httpclient - disable debugging / lower debuglevel <p>i am using the apache commons httpclient in a lotus notes java agent and it works fine. BUT when establishing a proxy connection the log will be spamed with the following line :</p> <pre><code>[INFO] AuthChallengeProcessor - basic authentication scheme selected </code></pre> <p>Do you know how to disable the integrated loging or how to set a lower debug level ? Its a "feature" from the httpclient itself, so code from my side is not needed :-)</p> <p>Thanks.</p>
<p>you should be able to set the logging level to something less spammy. there are a few default <a href="http://hc.apache.org/httpclient-3.x/logging.html" rel="nofollow">logging options</a>, so it depends on the logging method you chose.</p> <p>it sounds like your logging level is set to "debug" or "info" and should be set at "notice" or above (to avoid info and below level warnings)</p>
Can you use an alias in the WHERE clause in mysql? <p>I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias:</p> <pre><code>sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating </code></pre>
<p>You could use a HAVING clause, which <em>can</em> see the aliases, e.g.</p> <pre><code> HAVING avg_rating&gt;5 </code></pre> <p>but in a where clause you'll need to repeat your expression, e.g. </p> <pre><code> WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))&gt;5 </code></pre> <p>BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause.</p> <p>From the <a href="http://dev.mysql.com/doc/refman/5.0/en/select.html">MySQL Manual</a>:</p> <blockquote> <p>It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See <a href="http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html">Section B.1.5.4, “Problems with Column Aliases”</a>.</p> </blockquote>
How do I remove a cookie that I've set on someone's computer? <p>I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.</p>
<p>Set the cookie again, as if you hadn't set it the first time, but specify an expiration date that is in the past.</p>
What is the technical term for C# or Java type languages? <p>This is probably a very simple question, but what is the technical term for this class of language? </p> <p>They use an "intermediate" assembly type language which is sent through the JVM or CLR. They both are object oriented and they both depend on an intermediary such as the Java Virtual Machine or the Common Language Runtime to compile into native machine laguage. </p> <p>Unlike Asm/C/C++ they don't compile directly into native machine language and require intensive memory allocation knowledge. They both use garbage collection. </p> <p>Is there a technical term which seperates Java and C# from C++? </p>
<p>A key difference between C++ and .NET/Java is the automatic reclaiming of memory that is no longer required. This is known as <strong>garbage collection</strong>. For this property, they are known as <strong>managed</strong> platforms.</p> <p>Both Java/.NET delay the compilation of bytecode into native code until the last minute. For this property they are known as <strong>JIT-compiled</strong> (Just In Time).</p> <p>The C#/Java/C++ languages are known as <strong>imperative, object-oriented</strong> languages.</p> <p>The type system in both .NET and Java only allows verifiable invocation of methods. For this property they are known as <strong>statically typed</strong>. </p> <p>C#/Java/C++ are <strong>Turing complete</strong>, meaning that, in practice, they can produce any calculation.</p>
Removing one Installer from another installer <p>I have created a custom intall dll &amp; everything is working fine.I just want to call another installer's Uninstall method from my current installation.When i do this i get error code 1618(signifies another installer is already running).However when i call the uninstall of the same product form a test project it is working fine.Could anyone suggest a solution to this.Can i uninstall another application from current installer?</p>
<p>AFAIK calling an installer (either to install or uninstall) from another installer is not supported. It was supported in earlier versions of Windows Installer, but is now deprecated, and even then I'm not sure uninstallation of an other product was supported. The recommended way now is to use a bootstrapper to check for and install any prerequisites. Theoretically you should also be able to uninstall a product using a custom bootsrapper, however writing one is not a trivial exercise. Also silently uninstalling something from a users machine is not necessarily a nice thin. Using the Visual Studio 2005 Generic Bootstrapper you should be able to generate a bootstrapper that checks if the other product is installed and asks the user to uninstall it.</p>
Are there design patterns on modelling a structure containing Teams, Roles and Skills? <p>I need to model a system where by there will be a team who will consist of users who perform roles in the team and have skills assigned to them.</p> <p><em>i.e. a team A 5 members, one performs the team leader role, all perform the reply to email role, but some have an extra skill to answer the phone</em></p> <p>I'm trying to determine how I can best model this. </p> <p>This problem must have been solved before, are there any good resources on how to model this?</p> <p>EDIT: I need to determine what a user is allowed to do, which could be because they are in a certain team, perform a certain role or have been assigned a certain skill</p>
<p>I Googled this, so take it with a grain of salt. I found this <a href="http://www.riehle.org/computer-science/research/1997/ubilab-tr-1997-1-1.pdf" rel="nofollow">paper</a> on Role Modeling and Objects. On page 30 there is a Role Pattern. Hopefully this is not a wild goose chase for you. Here is the summary</p> <blockquote> <p>The Role pattern lets you design a Component which can be extend at runtime with new Context objects, called Roles. A Component is extended with Roles according to the Context Object pattern. The Component corresponds to a Decorator’s Component, and a Role corresponds to a Context Object. State integration of a role-playing Component is achieved by applying Property and Strategy. Property is used to define the Component’s state space, and Strategy is used to provide the Property dependent behavior.</p> </blockquote>
Please recommend me a professional keepalive solution for our monitoring server <p>I'm looking for a tool that can be installed on our monitoring server and which allows us to perform scheduled requests to our web sites in order to keep them from shutting down (asp.net).</p> <p>I don't want to use a web service since we already have a dedicated monitoring server. Our monitoring software doesn't really have the ability to do this without using some ugly workaround.</p> <p>I could probably write my own but I'm a bit short on time atm.</p>
<p>What about using <a href="http://users.ugent.be/~bpuype/wget/" rel="nofollow">wget for Windows</a> and a scheduled task?</p>
Update column from another table - mySQL 3.5.2 <p>I've tried a couple of approaches to update a column in a mySQL database table from another table but am not having any luck. </p> <p>I read somewhere that version 3.5.2 does not support multi-table updates and I need a code-based solution - is that correct?</p> <p>If not can anybody point me in the right direction using sql? </p> <pre><code>UPDATE products SET products_ordered = ( SELECT SUM(products_quantity) FROM orders_products WHERE products_id = products.products_id ); </code></pre> <p>or:</p> <pre><code>Create temporary table my_temp_table as SELECT products_id, SUM(products_quantity) as total FROM orders_products GROUP BY products_id UPDATE products, my_temp_table SET products.products_ordered = my_temp_table.total WHERE products.products_id = my_temp_table.products_id </code></pre>
<p>When I used to use MySQL that did not support either subqueries or multi-table updates, I used a trick to do what you're describing. Run a query whose results are themselves SQL statements, and then save the output and run that as an SQL script.</p> <pre><code>SELECT CONCAT( 'UPDATE products SET products_ordered = ', SUM(products_quantity), ' WHERE product_id = ', products_id, ';') AS sql_statement FROM orders_products GROUP BY products_id; </code></pre> <p>By the way, there is no such version MySQL 3.5.x as far as I know. I think you may have reported that wrong. Or else you're using another product such as mSQL.</p> <p><strong>Edit:</strong> I forgot to add a semicolon into the SQL statement generated by the query above.</p>
Style sheet images aren't reloaded by Firefox or Safari <p>We have found out that Firefox (at least v3) and Safari don't properly cache images referenced from a css file. The images are cached, but they are never refreshed, even if you change them on the server. Once Firefox has the image in the cache, it will never check if it has changed.</p> <p>Our css file looks like this:</p> <pre><code>div#news { background: #FFFFFF url(images/newsitem_background.jpg) no-repeat; ... } </code></pre> <p>The problem is that if we now change the newsitem_background.jpg image, all Firefox users will still get the old image, unless they explicitly refresh the page. IE on the other hand, detects that the image has changed and reloads it automatically.</p> <p>Is this a known problem? Any workarounds? Thanks!</p> <p>EDIT: The solution is not to press F5. I can do this. But our clients will just visit our web site, and get the old, outdated graphics. How would they know they would need to press F5?</p> <p>I have installed Firebug and confirmed what I already suspected: Firefox just doesn't even try to retrieve images referenced from a css file, to find out if they have been changed. When you press F5, it does check all images, and the web server nicely responds with 304, except for those that <em>have</em> changed, where it responds with 200 OK.</p> <p>So, is there a way to urge Firefox to <em>automatically</em> update an image that is referenced from a css file? Surely I'm not the only one with this problem?</p> <p>EDIT2: I tested this with localhost, and the image response doesn't contain any caching information, it's:</p> <pre><code>Server Microsoft-IIS/5.1 X-Powered-By ASP.NET Date Tue, 14 Oct 2008 11:01:27 GMT Content-Type image/jpeg Accept-Ranges bytes Last-Modified Tue, 14 Oct 2008 11:00:43 GMT Etag "7ab3aa1aec2dc91:9f4" Content-Length 61196 </code></pre> <p>EDIT3: I've done some more reading and it looks like it just can't be fixed, since Firefox, or most browser, will just assume an image doesn't change very often (expires header and all).</p>
<p>I would just add a querystring value to the image url. I usually just create a "version number" and increment it every time the image changes:</p> <pre><code>div#news { background: url(images/newsitem_background.jpg?v=00001) no-repeat; ... } </code></pre>
To which kind of problem is functional programming well suited? <p>Functional programming seems to be a paradigm in computer science which has more and more echo.</p> <p>I wonder which kind of problems are better solved with a functional programming approach rather than with a more traditional object oriented approach.</p> <p>Thank you.</p>
<p>This is close to these other questions.</p> <p><a href="http://stackoverflow.com/questions/36504/why-functional-languages">Why functional languages?</a></p> <p><a href="http://stackoverflow.com/questions/128057/what-are-the-benefits-of-functional-programming">What are the benefits of functional programming?</a></p>
Trapping messages in MFC - Whats the difference? <p>I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..).</p> <h1>1 - Via Message map:</h1> <pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() </code></pre> <h1>2 - Via afx_message:</h1> <pre><code>afx_msg type OnSize(...); </code></pre> <p>They seem to be used interchangeably, which one should be used or does it depend on other factors?</p>
<p>Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, <code>OnSize</code>).</p> <pre><code>class CClassWnd : public CBaseClassWnd { ... afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP }; </code></pre> <p><code>afx_msg</code> is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention.</p> <p>The message map is then defined in the class's .cpp file:</p> <pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ON_WM_SIZE() END_MESSAGE_MAP() </code></pre> <p>These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The <code>ON_WM_SIZE</code> macro allows the <code>wParam</code> and <code>lParam</code> message parameters in the <code>WM_SIZE</code> message to be decoded into more meaningful values for the message handler function (<code>nType</code>, <code>cx</code>, and <code>cy</code> in this case). MFC provides macros for most window messages (<code>WM_LBUTTONDOWN</code>, <code>WM_DESTROY</code>, etc).</p> <p>You can find more information on how message maps work in MFC <a href="http://msdn.microsoft.com/en-us/library/0x0cx6b1.aspx" rel="nofollow">here</a> on MSDN.</p>
Are PHP short tags acceptable to use? <p>Here's the information <a href="http://www.php.net/manual/en/language.basic-syntax.php">according to the official documentation</a>:</p> <blockquote> <p>There are four different pairs of opening and closing tags which can be used in PHP. Two of those, <code>&lt;?php ?&gt;</code> and <code>&lt;script language="php"&gt; &lt;/script&gt;</code>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and <strong>generally not recommended</strong>.</p> </blockquote> <p>In my experience most servers <em>do</em> have short tags enabled. Typing</p> <pre><code>&lt;?= </code></pre> <p>is far more convenient than typing</p> <pre><code>&lt;?php echo </code></pre> <p>The programmers convenience is an important factor, so <strong>why</strong> are they not recommended?</p>
<p>They're not recommended because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts <em>do</em> support shorttags but "lots" isn't all of them. If you want to share your scripts, it's best to use the full syntax.</p> <p>I agree that <code>&lt;?</code> and <code>&lt;?=</code> are easier on programmers than <code>&lt;?php</code> and <code>&lt;?php echo</code> but it is possible to do a bulk find-and-replace as long as you use the same form each time (and don't chuck in spaces (eg: <code>&lt;? php</code> or <code>&lt;? =</code>)</p> <p>I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them.</p> <p>As ThiefMaster mentions in the comments, <strong><a href="http://php.net/manual/en/migration54.new-features.php">as of PHP 5.4, <code>&lt;?= ... ?&gt;</code> tags are supported everywhere, regardless of shorttags settings</a></strong>. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use <code>&lt;?php echo ... ?&gt;</code>.</p> <p>Also, you need to know that <strong><a href="http://php.net/manual/en/language.basic-syntax.phptags.php">ASP tags &lt;% , %> , &lt;%= , and script tag are removed from PHP 7</a></strong>. So if you would like to support long-term portable code and would like switching to the most modern tools consider changing that parts of code.</p>
How can I do access control via an SQL table? <p>I'm trying to create an access control system. </p> <p>Here's a stripped down example of what the table I'm trying to control access to looks like:</p> <pre><code>things table: id group_id name 1 1 thing 1 2 1 thing 2 3 1 thing 3 4 1 thing 4 5 2 thing 5 </code></pre> <p>And the access control table looks like this:</p> <pre><code>access table: user_id type object_id access 1 group 1 50 1 thing 1 10 1 thing 2 100 </code></pre> <p>Access can be granted either by specifying the id of the 'thing' directly, or granted for an entire group of things by specifying a group id. In the above example, user 1 has been granted an access level of 50 to group 1, which should apply unless there are any other rules granting more specific access to an individual thing.</p> <p>I need a query that returns a list of things (ids only is okay) along with the access level for a specific user. So using the example above I'd want something like this for user id 1:</p> <pre><code>desired result: thing_id access 1 10 2 100 3 50 (things 3 and 4 have no specific access rule, 4 50 so this '50' is from the group rule) 5 (thing 5 has no rules at all, so although I still want it in the output, there's no access level for it) </code></pre> <p>The closest I can come up with is this:</p> <pre><code>SELECT * FROM things LEFT JOIN access ON user_id = 1 AND ( (access.type = 'group' AND access.object_id = things.group_id) OR (access.type = 'thing' AND access.object_id = things.id) ) </code></pre> <p>But that returns multiple rows, when I only want one for each row in the 'things' table. I'm not sure how to get down to a single row for each 'thing', or how to prioritise 'thing' rules over 'group' rules.</p> <p>If it helps, the database I'm using is PostgreSQL.</p> <p>Please feel free to leave a comment if there's any information I've missed out. </p> <p>Thanks in advance!</p>
<p>I just read a paper last night on this. It has some ideas on how to do this. If you can't use the link on the title try using Google Scholar on <a href="http://portal.acm.org/citation.cfm?id=1316701" rel="nofollow">Limiting Disclosure in Hippocratic Databases.</a></p>
How to dynamically set which properties get bound to a DataGridView? <p>My DataGridView needs to support a number of types and these types may have any number of public properties, not all of which I want to display.</p> <p>Can anyone suggest a way to dynamically customise a DataGridView's columns when binding a class a datasource? Is there an attribute that will tell a control whether to use a property as a column for example?</p> <p>Advice appreciated.</p>
<p>By default (with auto column generation enabled), it will simply obtain (via ComponentModel) the <code>[Browsable(true)]</code> properties, (or those that omit this attribute).</p> <p>If this is the <em>only</em> use of binding for this data, you could add <code>[Browsable(false)]</code> to the properties you don't want to show. Note that this will also prevent regular data-binding (i.e. <code>TextBox</code>, <code>PropertyGrid</code>, etc) to those properties.</p> <p>In reality, I expect it would be better to create your own attribute, and use that to find the properties you want to display via reflection (and build the columns yourself).</p>
Can an Adobe AIR Application run via the command line output to console? <p>I have an AIR application that takes command-line arguments via onInvoke. All is good, but I cannot figure out how to print some status messages back to the user (to stdout / console, so to speak). Is it possible?</p> <p>Even a default log file for traces would be fine, but I can't find any info about it anywhere. Do I need to create my own log file? Now that'd be silly.</p>
<p>Take a look at <a href="http://www.mikechambers.com/blog/2008/01/17/commandproxy-net-air-integration-proof-of-concept/" rel="nofollow">CommandProxy</a>. It is a low level wrapper around your AIR application that lets you send command from AS3 back to the proxy for communicating with the underlying OS. You should be able to add a means of writing to the command line via such a method.</p>
ASP.NET: Popup browser windows and session cookies <p>SUMMARY: When browsing an ASP.NET website using Windows Explorer, popup windows do not "borrow" the session cookie from the parent window.</p> <p>DETAILS:</p> <p>I'm working on an ASP.NET website (.NET 2.0). I use FormsAuthentication. It is a requirement to use cookies to handle the session.</p> <p>On a page I have a button. When the user clicks it, a popup window is opened. The popup displays an ASPX page that uses session variables, previously set from the parent browser window. I've been testing the website using IE (6, 7, 8) and Firefox 2.0. On all these browsers, the popup window has access to the same session as the parent browser window and everything works ok.</p> <p>I now have a bug raised by the client, stating that the popup window displays an error. Looking at the log file, I can see that it is a NullReferenceException at the moment the popup page tries to access the session variables. Talking with the client, he said that he opened the main website in Windows Explorer !!!</p> <p>I've managed to recreate the issue on a test machine and saw that the popup is using a new session.</p> <p>The machine must have Win XP an IE6 installed ! With IE7 the website works ok.</p>
<p>My suspicion here is that when opened from Windows Explorer (not that I fully understand what you mean by this), the session cookie that is being sent back is not stored anywhere and thus not available for the pop up window to include with its request. I don't see how you can get around this. Is it not possible to tell the client that this means of accessing the application is not supported?</p>
Retrieving values in reflected types from reflected properties <p>I need to access some members marked internal that are declared in a third party assembly.</p> <p>I would like to return a value from a particular internal property in a class. Then I'd like to retrieve a value from a property on that returned value. However, these properties return types that are also internal and declared in this third party assembly.</p> <p>The examples of doing this I've seen are simple and just show returning int or bool. Can someone please give some example code that handles this more complex case?</p>
<p>You just keep digging on the returned value (or the PropertyType of the PropertyInfo):</p> <p>u</p> <pre><code>sing System; using System.Reflection; public class Foo { public Foo() {Bar = new Bar { Name = "abc"};} internal Bar Bar {get;set;} } public class Bar { internal string Name {get;set;} } static class Program { static void Main() { object foo = new Foo(); PropertyInfo prop = foo.GetType().GetProperty( "Bar", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object bar = prop.GetValue(foo, null); prop = bar.GetType().GetProperty( "Name", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object name = prop.GetValue(bar, null); Console.WriteLine(name); } } </code></pre>
Embedding Intellisense Xml Documentation in Assembly? <p>I have an assembly containing very thorough XML-based documentation, which is used through Sandcastle to generate the help-files for the product. We also use the output XML files for providing proper Intellisense in Visual Studio when programmers use the assembly obviously.</p> <p>In order to do this, it seems we have do both supply the user with the assembly ("assembly.dll") and the documentation ("assembly.xml"). </p> <p>Is it somehow possible to embed the documentation within the assembly, so we'd only have to supply the single assembly-file and Visual Studio would be able to extract the information? Maybe embedded as a resource or something like that?</p>
<p>Unfortunately you will need to supply both as Visual Studio only knows to look at XML documents for Intellisense.</p>
Find all storage devices attached to a Linux machine <p>I have a need to find all of the writable storage devices attached to a given machine, <strong>whether or not</strong> they are mounted.</p> <p>The dopey way to do this would be to <em>try</em> every entry in <code>/dev</code> that corresponds to a writable devices (<code>hd* and sd*</code>)......</p> <p>Is there a better solution, or should I stick with this one?</p>
<p><code>/proc/partitions</code> will list all the block devices and partitions that the system recognizes. You can then try using <code>file -s &lt;device&gt;</code> to determine what kind of filesystem is present on the partition, if any.</p>
How to decode a CSR File? <p>I ran accross a CSR file (Certificate Signing Request) and I need to extract some information from it.</p> <p>There's a way to decode it using .NET Framework?</p>
<p>It's not .NET, but for interactive use, try the OpenSSL utilities. Specifically:</p> <pre><code>openssl req -text -in request.csr </code></pre>
Be notified when visual/logical child added/removed <p>I am currently looking for a way to be notified when a child is added to the visual or logical children.</p> <p>I am aware of the Visual::OnVisualChildrenChanged method, but it does not apply to me since I can't always inherit and override this function. I am looking for an event.</p> <p>So, is there a way for the owner of a FrameworkElement/Visual to be notified when a child is added?</p>
<p>Isn't it easier to extend </p> <pre><code>System.Windows.Controls.UIElementCollection </code></pre> <p>to do the notification and use</p> <pre><code>protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) </code></pre> <p>?</p>
Mounting/Unmounting USB disks on Windows <p>On Windows Server, by default, external USB disks don't always get mounted. I'd like my program (written in C#) to be able to detect external USB disks, identify them, and then mount them.</p> <p>When it's finished, it should do whatever the programmatic equivalent of "Safely Remove Hardware" in order to flush and unmount the disk.</p> <p>Any pointers?</p>
<p>This article at The Code Project may help:</p> <p><a href="http://www.codeproject.com/KB/system/DriveDetector.aspx" rel="nofollow">http://www.codeproject.com/KB/system/DriveDetector.aspx</a></p>
Is it possible to host a TCP endpoint in an IIS6 hosted service? <p>I created a wcf service based on ServiceHostFactory, and i'm hosting it in IIS6. If i use a HTTP endpoint everything works just fine, but when i try to switch to TCP it goes bad.</p> <p>Is it even possible to do this in II6?</p> <p>I have a more specific question posted here, that asks for a solution, but i would be happy with (for starters if not) with just an answer (and perhaps an example) to this - less specific question.</p> <p><a href="http://stackoverflow.com/questions/201004/why-cant-i-connect-to-a-wcf-service-with-nettcp-but-i-can-with-http">http://stackoverflow.com/questions/201004/why-cant-i-connect-to-a-wcf-service-with-nettcp-but-i-can-with-http</a></p>
<p>IIS 5.1 and IIS 6 can only host HTTP bindings. IIS7 has WAS (Windows Activation Service) which allows hosting of endpoints bound to any transport protocol... so it would be capable of TCP.</p> <p>If you must host with IIS 6, then you're stuck with the HTTP bindings. If not, consider self-hosting in a Windows Service.</p>
What is the most efficient way to handle en expired session with ASP.NET 2.0 <p>On the site we are building. We need to be able to redirect the user to a default page when his session has ended.</p> <p>At first sight we used the Session_End with a Response.Redirect to do this job.</p> <pre><code>Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) Response.Redirect("~/global/exit.aspx") End Sub </code></pre> <p>But it generates a crapload of <em>Response is not available in this context</em> errors. Naturally we don't want to spam our servers error logs.</p> <p>What is the most efficient way to handle session ending with ASP.NET 2.0?</p>
<p>We added the following code to the global.asax.cs file: </p> <pre><code> private void IsAuthenticated() { string vFileName = Path.GetFileName(HttpContext.Current.Request.Path); string vExt = Path.GetExtension(vFileName).ToLower(); if ((vFileName != "Login.aspx") &amp;&amp; (vExt == ".aspx")) { if (HttpContext.Current.Session["LoggedIn"] == null) { HttpContext.Current.Response.Redirect("~/Login.aspx"); } } } void Application_PostAcquireRequestState(object sender, EventArgs e) { IsAuthenticated(); } </code></pre> <p>NS: The first line in our Global .asax file is : </p> <pre><code>&lt;%@ Application Inherits="???.Global" Language="C#" %&gt; </code></pre>
C# Inheritance <p>I had a coworker see this the other day and I'm not quite sure why this happened. Can anyone explain it?</p> <p>We have class A:</p> <pre><code>using System; using System.Data; public class A { protected DataTable _table; public A() { } } </code></pre> <p>We have class B that inherits from class A (assume there in the same namespace):</p> <pre><code>using System; public class B : A { public B() { } } </code></pre> <p>In the constructor of class B, if I try this._table, it doesn't compile? Why does it not?</p> <p>But to get it to work, I have to add using System.Data; and everything works fine.</p> <p><strong>Why does .NET not do this for me? So that when I try to access the protected member, it knows that its a System.Data.DataTable?</strong></p> <p>forgive me if the classes are 100% correct...</p>
<p>This is not a language issue - if anything, you could call it an IDE issue, for not adding the using statement when creating the new class. Even then, the IDE does not know you will be accessing this member, and I prefer to keep my "usings" as minimal as possible. In any case, the fact that B extends A does not tell the compiler anything about which namespaces it must search for the types referenced in B.</p> <p>Also, I would strongly suggest you change your access of the <code>_table</code> member to use a getter property.</p>
Visual Studio debugger tips & tricks for .NET <p>I've been working for years with VS's debugger, but every now and then I come across a feature I have never noticed before, and think "Damn! How could I have missed that? It's <strong>so</strong> useful!"</p> <p>[Disclaimer: These tips work in VS 2005 on a C# project, no guarantees for older incarnations of VS or other languages] </p> <h3>Keep track of object instances</h3> <p>Working with multiple instances of a given class? How can you tell them apart? In pre-garbage collection programming days, it was easy to keep track of references - just look at the memory address. With .NET, you can't do that - objects can get moved around. Fortunately, the watches view lets you right-click on a watch and select 'Make Object ID'. </p> <blockquote> <blockquote> <p><img src="http://img403.imageshack.us/img403/461/52518188cq3.jpg" alt="watches view" /> </p> </blockquote> </blockquote> <p>This appends a {1#}, {2#} etc. after the instance's value, effectively giving the instance a unique label. It looks like this: </p> <blockquote> <blockquote> <p><img src="http://img383.imageshack.us/img383/7351/11732685bl8.jpg" alt="numbered instance" /></p> </blockquote> </blockquote> <p>The label is persisted for the lifetime of that object.</p> <h3>Meaningful values for watched variables</h3> <p>By default, a watched variable's value is it's type. If you want to see its fields, you have to expand it, and this could take a long time (or even timeout!) if there are many fields or they do something complicated.</p> <p>However, some predefined types show more meaningful information :</p> <ul> <li>strings show their actual contents</li> <li>lists and dictionaries show their elements count etc.</li> </ul> <p><img src="http://img205.imageshack.us/img205/4808/37220487md1.jpg" alt="meaningful info" /></p> <p>Wouldn't it be nice to have that for my own types? </p> <p>Hmm... </p> <p>...some quality time with .NET Reflector shows how easily this can be accomplished with the <code>DebuggerDisplay</code> attribute on my custom type:</p> <pre><code>[System.Diagnostics.DebuggerDisplay("Employee: '{Name}'")] public class Employee { public string Name { get { ... } } ... } </code></pre> <p>... re-run, and...</p> <p><img src="http://img60.imageshack.us/img60/926/79816018ha1.jpg" alt="ta da!" /></p> <p>There's a lot more info on the subject here: <a href="http://msdn.microsoft.com/en-us/magazine/cc163974.aspx" rel="nofollow">MSDN</a></p> <h3>Break on all exceptions</h3> <p>... even the ones that are handled in code! I know, I'm such a n00b for not knowing about this ever since I was born, but here it goes anyway - maybe this will help someone someday:</p> <p>You can force a debugged process to break into debug mode each time an exception is thrown. Ever went on a bug hunt for hours only to come across a piece of code like this?</p> <pre><code>try { runStrangeContraption(); } catch(Exception ex) { /* TODO: Will handle this error later */ } </code></pre> <p>Catching all exceptions is really handy in these cases. This can be enabled from <em>Debug > Exceptions... (Ctrl-Alt-E)</em>. Tick the boxes in the 'Thrown' column for each type of exception you need.</p> <p><hr /></p> <p>Those were a few forehead-slapping moments for me. Would you care to share yours?</p>
<pre><code>try { // do something big } catch { // breakpoint set here: throw CantHappenException("something horrible happened that should never happen."); } </code></pre> <p>How do you see the exception that was originally thrown? In a watch window, enter $exception</p>
How can I code desktop monitoring software? <p>I have to develop a tool for monitoring helpdesk agents. I can figure out how to capture keyboard events and mouse events; however I need to capture the control that emitted/consumed the event too. Is it possible to find that out?</p>
<p>You need windows hooks to pick up the events. These are really the province of native code. Try asking again with Win32 tag replacing the C# tag.</p>
How should I add multiple identical elements to a div with jQuery <p>I need to add multiple empty divs to a container element using jQuery.</p> <p>At the moment I am generating a string containing the empty html using a loop</p> <pre><code>divstr = '&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;...&lt;div&gt;&lt;/div&gt;'; </code></pre> <p>and then injecting that into my container:</p> <pre><code>$('#container').html(divstr); </code></pre> <p>Is there a more elegant way to insert multiple, identical elements?</p> <p>I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable <code>.repeat()</code> plugin?</p>
<p>If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.</p> <p>John Resig explains the technique and includes a performance benchmark:</p> <p><a href="http://ejohn.org/blog/dom-documentfragments/">http://ejohn.org/blog/dom-documentfragments/</a></p> <pre><code>var i = 10, fragment = document.createDocumentFragment(), div = document.createElement('div'); while (i--) { fragment.appendChild(div.cloneNode(true)); } $('#container').append(fragment); </code></pre> <p>I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.</p>
Identifying COM components in a .NET application <p>I've inherited a .NET application that pulls together about 100 dlls built by two teams or purchased from vendors. I would like to quickly identify whether a given dll is a .NET assembly or a COM component. I realize that I could just invoke ildasm on each dll individually and make a note if the dll does not have a valid CLR header, but this approach seems clumsy and difficult to automate.</p>
<p>You can always try to add the "Assembly Version" column to the Explorer Window, and note which ones are blank to find the non-.NET assemblies.</p>
How do I un-escape XML entities easily in .NET <p>I have some code which returns InnerXML for a XMLNode.</p> <p>The node can contain just some text (with HTML) or XML.</p> <p>For example:</p> <pre><code>&lt;XMLNode&gt; Here is some &amp;lt;strong&amp;gt;HTML&amp;lt;/strong&amp;gt; &lt;XMLNode&gt; </code></pre> <p>or</p> <pre><code>&lt;XMLNode&gt; &lt;XMLContent&gt;Here is some content&lt;/XMLContnet&gt; &lt;/XMLNode&gt; </code></pre> <p>if I get the InnerXML for <code>&lt;XmlNode&gt;</code> the HTML tags are returned as XML entities.</p> <p>I cannot use InnerText because I need to be able to get the XML contents. So all I really need is a way to un-escape the HTML tags, because I can detect if it's XML or not and act accordingly.</p> <p>I guess I could use HTMLDecode, but will this decode all the XML encoded entities?</p> <p><strong>Update:</strong> I guess I'm rambling a bit above so here is a clarified scenario:</p> <p>I have a XML document that looks like this:</p> <pre><code>&lt;content id="1"&gt; &lt;data&gt;&amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt;&lt;/data&gt; &lt;/content id="2"&gt; &lt;content&gt; &lt;data&gt; &lt;dataitem&gt;A test&lt;/dataitem&gt; &lt;/data&gt; &lt;/content&gt; </code></pre> <p>If I do:</p> <pre><code>XmlNode xn1 = document.SelectSingleNode("/content[@id=1]/data"); XmlNode xn2 = document.SelectSingleNode("/content[@id=2]/data"); Console.WriteLine(xn1.InnerXml); Console.WriteLine(xn2.InnerXml); </code></pre> <p>xn1 will return </p> <pre><code> &amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt; </code></pre> <p>xn2 will return <code>&lt;dataitem&gt;A test&lt;/dataitem&gt;</code></p> <p>I am already checking to see if what is returned is XML (in the case of xn2) so all I need to do is un-escape the <code>&amp;lt;</code> etc in xn1.</p> <p>HTMLDecode does this, but I'm not sure it would work for everything. So the question remains would HTMLDecode handle all the possible entities or is there a class somewhere that will do it for me.</p>
<p>why not inserting them as &amp;lt; and &amp;gt; ? you avoid mixing xml and custom markup stuff with this...</p>
How to integrate Geronimo's transaction manager in Tomcat? <p>Does Geronimo provides a standalone transaction manager? And if it does, is it possible to use it in Tomcat?</p>
<p><a href="http://openejb.apache.org/" rel="nofollow">Apache OpenEJB</a> is embedded implementation of Geronimo EJB container that includes Transaction Manager. OpenEJB can be embedded into Tomcat which is one of its intended usages.</p>
How do I create a named log in $TOMCAT_HOME/logs for my servlet? <p>I'm currently logging via the simplest of methods within my servlet using Tomcat. I use the ServletConfig.getServletContext().log to record activity. This writes to the localhost.YYYY-MM-DD.log in $TOMCAT_HOME/logs.</p> <p>I don't want to get away from the simplicity of this logging mechanism unless absolutely necessary. But I would like to name my log file. Rather than "localhost".YYYY-MM-DD.log, is there a way to have it write to "myAppName".YYYY-MM-DD.log. I know I could create my own mechanism, but again, I looking for simplicity here.</p> <p>I'm hoping to stay away from a complete framework like Log4j.</p>
<p>For Tomcat 6.x, you can change the logging configuration in conf/logging.properties.</p> <p>But I prefer a separate configuration with Log4j...</p>
Where can I find examples of element heavy web forms? <p>I would like to look at some examples of some good form layouts (web-based) that have a lot of input fields. I do a lot of web application development and a lot of my forms are input element heavy so I am always looking for good ideas on how to display my forms. For example I have a few list boxes and a lot of text boxes and some drop downs on a page along with displaying history of changes to the form.</p>
<p>I always like visiting <a href="http://wufoo.com/gallery/">Wufoo</a> whenever I need some form inspiration.</p>
Do you know of any IDEs that are localized to Spanish? <p>I have a buddy that's having a hard time with the language barrier. I tried to think of any IDEs that are also available in Spanish, but couldn't think of any. Any ideas?</p>
<p>Microsoft Visual Studio is avaible in spanish<br /> <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio" rel="nofollow">http://en.wikipedia.org/wiki/Microsoft_Visual_Studio</a><br /> <a href="http://msdn.microsoft.com/en-gb/vstudio/default.aspx" rel="nofollow">http://msdn.microsoft.com/en-gb/vstudio/default.aspx</a></p> <p>Spanish version of the msdn page:<br /> <a href="http://msdn.microsoft.com/es-es/vstudio/default.aspx" rel="nofollow">http://msdn.microsoft.com/es-es/vstudio/default.aspx</a></p>
Linq to SQL: .FirstOrDefault() not applicable to select new { ... } <p>I just asked <a href="http://stackoverflow.com/questions/201686/linq-to-sql-select-optimization">this question</a>. Which lead me to a new question :)</p> <p>Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:</p> <pre><code>var person = (from p in [DataContextObject].Persons where p.PersonsID == 1 select new p).FirstOrDefault(); if (person == null) { // handle 0 "rows" returned. } </code></pre> <p>But I can't use <code>FirstOrDefault()</code> when I do:</p> <pre><code>var person = from p in [DataContextObject].Persons where p.PersonsID == 1 select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }; // Under the hood, this pattern generates a query which selects specific // columns which will be faster than selecting all columns as the above // snippet of code does. This results in a performance-boost on large tables. </code></pre> <p>How do I check for 0 "rows" returned by the query, using the second pattern? <br /> <br /> <br /> <br /> <strong>UPDATE:</strong></p> <p>I think my build fails because I am trying to assign the result of the query to a variable (<code>this._user</code>) declared with the type of <code>[DataContext].User</code>.</p> <pre><code>this._user = (from u in [DataContextObject].Users where u.UsersID == [Int32] select new { u.UsersID }).FirstOrDefault(); </code></pre> <p><em>Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".</em></p> <p>Any thoughts on how I can get around this? Would I have to make my own object?</p>
<p>Why can you keep doing the samething? Is it giving you an error?</p> <pre><code>var person = (from p in [DataContextObject].Persons where p.PersonsID == 1 select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }).FirstOrDefault(); if (person == null) { // handle 0 "rows" returned. } </code></pre> <p>It is still a reference object just like you actual object, it is just anonymous so you don't know the actual type before the code is compiled.</p>
How do I solve "index unique_schema_migrations already exists" in Rails? <p>Running <code>rake db:migrate</code> followed by <code>rake test:units</code> yields the following:</p> <pre><code>rake test:functionals (in /projects/my_project) rake aborted! SQLite3::SQLException: index unique_schema_migrations already exists: CREATE UNIQUE INDEX "unique_schema_migrations" ON "ts_schema_migrations" ("version") </code></pre> <p>The relevant part of <code>db/schema.rb</code> is as follows:</p> <pre><code>create_table "ts_schema_migrations", :id =&gt; false, :force =&gt; true do |t| t.string "version", :null =&gt; false end add_index "ts_schema_migrations", ["version"], :name =&gt; "unique_schema_migrations", :unique =&gt; true </code></pre> <p>I'm not manually changing this index anywhere, and I'm using Rails' default SQLite3 adapter with a brand new database. (That is, running <code>rm db/*sqlite3</code> before <code>rake db:migrate</code> doesn't help.)</p> <p>Is the <code>test:units</code> task perhaps trying to re-load the schema? If so, why? Shouldn't it recognize the schema is already up to date?</p>
<p>In SQLite, index name uniqueness is enforced at the database level. In MySQL, uniqueness is enforced only at the table level. That's why your migrations work in the latter and not the former: you have two indexes with the same name on different tables.</p> <p>Rename the index, or find and rename the other <code>unique_schema_migrations</code> index, and your migrations should work.</p>
Using server-side XML Parser to generate HTML content <p>Is it possible using a server side XML parser to have it create an HTML blob that is then included in an existing HTML page?</p>
<p>Is the existing HTML page already being served by the same server? If so, then yes - arguably that's a rough description of what almost all web frameworks do, to a greater or lesser extent: insert some dynamic content within a static template.</p> <p>Which bit are you concerned about?</p>
can realloc Array, then Why use pointers? <p>This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please mention any situation where the above statement can contradict.</p> <p>Thank you.</p>
<p>You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].*</p> <p>Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C.</p> <p>I would strongly suggest that you read <a href="http://rads.stackoverflow.com/amzn/click/0131103628"><em>The C Programming Language</em></a> by Kernighan and Ritchie and a solid C++ text like <a href="http://rads.stackoverflow.com/amzn/click/0072228970"><em>C++ From the Ground Up</em></a> by Herbert Schildt.</p> <p>Using dynamic memory, pointers, offsets, etc are all fundamental to using these two languages. Not knowing how they work, and why they exist will be a likely reason for potential employers to turn you down.</p> <p>*the compiler <strong>shouldn't</strong> let you reallocate anything that's been allocated statically, but if it does, the behavior is undefined</p>
How can I determine the last time any record changed in a specific Sql Server 2000 database? <p>I have a SQL Server 2000 database instance that is rarely updated. I also have a database table which has no columns holding each row's created date or modified date. </p> <p>Is there any way that I can determine the last time an update or insert was performed on the database as a whole, so that I can at least put a bound on when the specific records in the table may have changed?</p> <p>Note: I am looking for information about transactions that have already occurred. Triggers may help we should I require this again in the future, but does not address the problem I'm trying to describe.</p> <p>If it can be done, how can I do it?</p>
<p>The database's log file may have some information that is useful to your quest. AFAIK, the database itself doesn't store a "last updated" date.</p>
How do I set up a timer to prevent overlapping ajax calls? <p>I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:</p> <pre><code>$(function() { // Wire up search textbox $('input.Search').bind("keyup", update); }); update = function(e) { // Get text from search box // Pass to web method and bind to concessions grid $.ajax({ ... success: function(msg) { displayResults(msg, filterParams); }, }); } displayResults = function(msg, filterParams) { // Databind results grid using jTemplates // Show results on map: Pass parameters to KML generator and overlay on map } </code></pre> <p>Depending on the search, there may be hundreds of results; and so the work that happens in <code>displayResults</code> is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map). </p> <p>I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the <code>update</code> function?</p>
<p>Instead of calling <code>update()</code> directly, call a wrapper that checks to see if there are any pending delayed updates:</p> <pre><code>$('input.Search').bind("keyup", delayedUpdate); function delayedUpdate() { if (updatePending) { clearTimeout(updatePending); } updatePending = setTimeout(update, 250); } function update() { updatePending = false; //$.ajax(... } </code></pre> <p>You should also probably add:</p> <pre><code>$('input.Search').bind("blur", update); </code></pre> <p>This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there's a pending delayed update (cancel the delayed update first).</p>
Run a XNA compiled game from DVD or CD on XBOX 360? <p>Is it possible to run a XNA game compiled for XBOX 360 from a DVD or CD, or does it have to be copied onto the HD?</p> <p>Is it possible to include a library which is not a part of the .net compact framework in a XBOX 360 project?</p>
<p>XNA games must be copied to the 360 using the XNA game launcher. They can not be loaded off a CD/DVD.</p> <p>You can use other libraries on the 360, but they have to be compiled using the XBox's .net libraries. So unless you have access to source code, or are willing to decompile and change all references to framework libraries to Xbox ones and then remove any calls which don't exist on the 360, you shouldn't try.</p>
What's a nice way of building a wParam or lParam in C#? (Something friendlier than shift operators?) <p>When the WIN32 docs says something like:</p> <pre><code>wParam The low-order word specifies the edit control identifier. The high-order word specifies the notification message. </code></pre> <p>What's a nice way of building that wParam?</p>
<pre><code>public static ushort LowWord(uint val) { return (ushort)val; } public static ushort HighWord(uint val) { return (ushort)(val &gt;&gt; 16); } public static uint BuildWParam(ushort low, ushort high) { return ((uint)high &lt;&lt; 16) | (uint)low; } </code></pre>
Is there a convenient way to wrap std::pair as a new type? <p>Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.</p> <p>Often times I should really be rolling my own class instead of just using std::pair. It's pretty easy to see when things start breaking down - when the code becomes littered with make_pair, first, and second, its very hard to remember what is what - an <code>std::pair&lt;int, int&gt;</code> conveys less meaning than a type <code>Position</code>.</p> <p>What have you found are the best ways to wrap the functionality of std::pair in a type that conveys real meaning?</p> <p>Here are some things I have considered:</p> <pre><code>typedef std::pair&lt;int, int&gt; Position; </code></pre> <p>This at least gives the type a meaningful name when passing it around, but the type isn't enforced, its still really just a pair, and most of the same problems still exist. This is however very simple to write.</p> <pre><code>struct Position : public std::pair&lt;int, int&gt; { typedef std::pair&lt;int, int&gt; Base; Position() : Base() {} Position(const Position &amp;x) : Base(x) {} Position(int a, int b) : Base(a, b) {} int &amp;row() { return first; } const int &amp;row() const { return first; } int &amp;col() { return second; } const int &amp;col() const { return second; } }; </code></pre> <p>This is better, since we can access the variables via a reasonably descriptive name. The problem here is that you can still access first and second, so its easy for the abstraction to leak. Also, accessing simple variables via functions makes the syntax annoying.</p> <p>The obvious next step is to make the inheritance private:</p> <pre><code>struct Position : private std::pair&lt;int, int&gt; { typedef std::pair&lt;int, int&gt; Base; Position() {} Position(const Position &amp;x) : Base(x) {} Position(int a, int b) : Base(a, b) {} int &amp;row() { return first; } const int &amp;row() const { return first; } int &amp;col() { return second; } const int &amp;col() const { return second; } bool operator&lt;(const Position &amp;x) const { return Base(*this) &lt; Base(x); } // other forwarding operators as needed... }; </code></pre> <p>So now at least we have gotten rid of the access to first and second, but now a new problem pops up. When we want to store the type in an std::set, we now don't have access to the operator&lt; overload since we don't have access to first and second. This means we have to define a forwarding function for each operator overload we want. For me this is usually ==, !=, and &lt;, but there could be others that I'd want. Yes I know I probably shouldn't overload operator&lt; just to stick it in an associative container, but it makes everything so darn simple... And defining these operators for each new type is a pain, and we STILL have to access via functions. We can fix that:</p> <pre><code>struct Position { Position() {} Position(const Position &amp;x) : row(x.row), col(x.col) {} Position(int row, int col) : row(row), col(col) {} int row, col; }; bool operator&lt;(const Position &amp;a, const Position &amp;b) { return a.row &lt; b.row || (!(b.row &lt; a.row) &amp;&amp; a.col &lt; b.col); } // more overloads as needed </code></pre> <p>So now we have simple variable access, but now defining overloaded operators is even more of a pain, because instead of just forwarding them to the pair's implementation, we actually have to re-implement them each time...</p> <p>Are there any solutions I have overlooked that make this easy without the drawbacks? If there aren't which would you tend to prefer?</p>
<p>This is what <a href="http://www.boost.org/doc/libs/1_36_0/libs/tuple/doc/tuple_users_guide.html" rel="nofollow">Boost.Tuple</a> was made for.</p> <p>But you should probably be using <a href="http://en.cppreference.com/w/cpp/utility/tuple" rel="nofollow">std::tuple</a> now...</p>
ASP.NET MVC Preview 5 on Mono <p>Does anyone have any information about getting the current versions of ASP.NET MVC (Preview 5) working on Mono 2.0? There was info on the old versions (Preview 2, maybe Preview 3), but I've seen no details about making Preview 5 actually work.</p> <p>The <a href="http://www.mono-project.com/Roadmap" rel="nofollow">Mono Project Roadmap</a> indicates ASP.NET 3.5 for Mono 2.4 (next year). Any ideas on how to get this useful before then?</p> <p>More details: The basic MVC Preview 5 template seems to work, so long as I avoid the root directory. If I request the root, I get:</p> <pre><code>Server Error in '/' Application The virtual path '' maps to another application. Description: HTTP 500. Error processing request. Stack Trace: System.Web.HttpException: The virtual path '' maps to another application. at System.Web.HttpContext.RewritePath (System.String filePath, System.String pathInfo, System.String queryString, Boolean setClientFilePath) [0x00000] at System.Web.HttpContext.RewritePath (System.String path, Boolean rebaseClientPath) [0x00000] at System.Web.HttpContext.RewritePath (System.String path) [0x00000] at MvcApplication1._Default.Page_Load (System.Object sender, System.EventArgs e) [0x00000] at System.Web.UI.Control.OnLoad (System.EventArgs e) [0x00000] at System.Web.UI.Control.LoadRecursive () [0x00000] at System.Web.UI.Page.ProcessLoad () [0x00000] at System.Web.UI.Page.ProcessPostData () [0x00000] at System.Web.UI.Page.InternalProcessRequest () [0x00000] at System.Web.UI.Page.ProcessRequest (System.Web.HttpContext context) [0x00000] Version information: Mono Version: 2.0.50727.42; ASP.NET Version: 2.0.50727.42 </code></pre>
<p>Well a potential is that RewritePath to / has some sort of bug, so just avoid that. Changing the RewritePath(Request.ApplicationPath) to:</p> <pre><code>HttpContext.Current.RewritePath("/Home/Index"); </code></pre> <p>Seems to fix the problem, and at least the demo works so far. </p>
How hard is it to incorporate full text search with SQL Server? <p>I am building a C#/ASP.NET app with an SQL backend. I am on deadline and finishing up my pages, out of left field one of my designers incorporated a full text search on one of my pages. My "searches" up until this point have been filters, being able to narrow a result set by certain factors and column values. </p> <p>Being that I'm on deadline (you know 3 hours sleep a night, at the point where I am looking like something the cat ate and threw up), I was expecting this page to be very similar to be others and I'm trying to decide whether or not to make a stink. I have never done a full text search on a page before.... is this a mountain to climb or is there a simple solution?</p> <p>thank you. </p>
<p>First off, you need to enabled Full text Searching indexing on the production servers, so if thats not in scope, your not going to want to go with this.</p> <p>However, if that's already ready to go, full text searching is relatively simple.</p> <p>T-SQL has 4 predicates used for full text search:</p> <ul> <li>FREETEXT</li> <li>FREETEXTTABLE</li> <li>CONTAINS</li> <li>CONTAINSTABLE</li> </ul> <p>FREETEXT is the simplest, and can be done like this:</p> <pre><code>SELECT UserName FROM Tbl_Users WHERE FREETEXT (UserName, 'bob' ) Results: JimBob Little Bobby Tables </code></pre> <p>FREETEXTTABLE works the same as FreeTEXT, except it returns the results as a table.</p> <p>The real power of T-SQL's full text search comes from the CONTAINS (and CONTAINSTABLE) predicate...This one is huge, so I'll just paste its usage in:</p> <pre><code>CONTAINS ( { column | * } , '&lt; contains_search_condition &gt;' ) &lt; contains_search_condition &gt; ::= { &lt; simple_term &gt; | &lt; prefix_term &gt; | &lt; generation_term &gt; | &lt; proximity_term &gt; | &lt; weighted_term &gt; } | { ( &lt; contains_search_condition &gt; ) { AND | AND NOT | OR } &lt; contains_search_condition &gt; [ ...n ] } &lt; simple_term &gt; ::= word | " phrase " &lt; prefix term &gt; ::= { "word * " | "phrase * " } &lt; generation_term &gt; ::= FORMSOF ( INFLECTIONAL , &lt; simple_term &gt; [ ,...n ] ) &lt; proximity_term &gt; ::= { &lt; simple_term &gt; | &lt; prefix_term &gt; } { { NEAR | ~ } { &lt; simple_term &gt; | &lt; prefix_term &gt; } } [ ...n ] &lt; weighted_term &gt; ::= ISABOUT ( { { &lt; simple_term &gt; | &lt; prefix_term &gt; | &lt; generation_term &gt; | &lt; proximity_term &gt; } [ WEIGHT ( weight_value ) ] } [ ,...n ] ) </code></pre> <p>This means you can write queries such as:</p> <pre><code>SELECT UserName FROM Tbl_Users WHERE CONTAINS(UserName, '"little*" NEAR tables') Results: Little Bobby Tables </code></pre> <p>Good luck :)</p>
Does Windows Powershell have a Try/Catch or other error handling mechanism? <p>In a script, when a command-let or other executable statement errors out, is there a try/catch type of mechanism to recover from these errors? I haven't run across one in the documentation.</p>
<p>You use a <code>Trap [exception-type] {}</code> block before the code you want to handle exceptions for.</p>
Calling a C# web service from with PHP with a long parameter <p>We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.</p> <p>This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?</p> <p>Thanks for any info.</p>
<p>Most PHP installations won't support 64 bit integers - 32 is the max. You can check this by reading the PHP_INT_SIZE constant (4 = 32bit, 8 = 64bit) or read the PHP_INT_MAX value.</p> <pre><code>&lt;?php echo PHP_INT_SIZE, "\n", PHP_INT_MAX; ?&gt; </code></pre> <p>If the web service class he is using is trying to type-convert a string representation of a 64 bit integer, then yes, it's mostly likely being truncated or converted into a float. You can sort of see this behavior with this simple test</p> <pre><code>&lt;?php echo intval( "12345678901234567890" ); // prints 2147483647, the max value for a 32 bit signed int. </code></pre> <p>Without knowing the details of his implementation, it's difficult to postulate on what a good solution/workaround might be.</p>
When should I write Static Methods? <p>So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields. </p> <p>One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:</p> <pre><code>var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg"); </code></pre> <p>As for static fields, is creating singelton-objects their best use? </p>
<p>Static methods are usually useful for operations that don't require any data from an instance of the class (from <code>this</code>) and can perform their intended purpose solely using their arguments.<br /> A simple example of this would be a method <code>Point::distance(Point a, Point b);</code> that calculates the distance between two points and don't require an instance.</p> <p>Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.</p>
How do I reuse a command in bash with different parameters? <p>I have two scripts that often need to be run with the same parameter:</p> <pre><code>$ populate.ksh 9241 &amp;&amp; check.ksh 9241 </code></pre> <p>When I need to change the parameter (<strong>9241</strong> in this example), I can go back and edit the line in history. But since I need to change the number in two places, I sometimes make a typo. I'd like to be able to change the parameter just once to change it in both places.</p>
<p>In bash:</p> <pre><code>!!:gs/9241/9243/ </code></pre> <p>Yes, it uses <code>gs///</code>, not <code>s///g</code>. :-)</p> <p>(zigdon's answer uses the last command starting with <code>pop</code>, such as <code>populate.sh</code>. My answer uses the last command, full stop. Choose which works for you.)</p>
How do I detect a null reference in C#? <p>How do I determine if an object reference is null in C# w/o throwing an exception if it is null?</p> <p>i.e. If I have a class reference being passed in and I don't know if it is null or not.</p>
<p>testing against null will never* throw an exception</p> <pre><code>void DoSomething( MyClass value ) { if( value != null ) { value.Method(); } } </code></pre> <hr> <p>* never as in <em>should never</em>. As @Ilya Ryzhenkov points out, an <em>incorrect</em> implementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on <a href="http://gregbee.ch/blog/implementing-object-equality-in-dotnet" rel="nofollow">implementing object equality in .NET</a>. </p>
What causes error 4063 - Database ...databasename... has not been opened yet <p>I have an scheduled agent that is trying to access a database on another server. When it runs I get an error 4063 - Database ...databasename... has not been opened yet.</p> <p>The servers is listed in the ACL as manager.</p> <p>What are some other possible causes for this errors?</p>
<p>Does the other server trust the server executing the agent? Check the server document -> Security -> Trusted servers.</p>
Web Apps for Source Code Discussion <p>Are there any web apps that allow for source code collaboration? I'm thinking of something that could look at an SVN repo/local folder/etc. and publish the code with support for threaded discussions under each file or class. Ideally I want to find something that I could deploy/host myself, so being based in PHP would be a huge plus.</p>
<p>Look at Attlassian Crucible (<a href="http://www.atlassian.com/software/crucible/">http://www.atlassian.com/software/crucible/</a>)</p> <p>And no, I am not associated with Atlassian in any way :)</p>
Is there a way to set timeouts in tomcat? <p>Can I set timeouts for JSP pages in tomcat either on a per page or server level?</p>
<p>In the Tomcat server.xml file, the Connector element also has a connectionTimeout attribute in milliseconds.</p>
Is there a human readable programming language? <p>I mean, is there a coded language with human style coding? For example:</p> <pre><code>Create an object called MyVar and initialize it to 10; Take MyVar and call MyMethod() with parameters. . . </code></pre> <p>I know it's not so useful, but it can be interesting to create such a grammar.</p>
<p>How about <a href="http://lolcode.com/home">LOLCODE</a>?</p> <pre><code>HAI CAN HAS STDIO? VISIBLE "HAI WORLD!" KTHXBYE </code></pre> <p>Simplicity itself!</p>
DOCTYPE RSS & HTML entities <p>I have an <strong>"ldquo"</strong>, <strong>"rdquo"</strong> and several other entities under my RSS feed. Seems like if I add</p> <pre><code>&lt;!DOCTYPE rss [ &lt;!ENTITY % HTMLspec PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent"&gt; %HTMLspec; </code></pre> <p>below the <strong>xml</strong> tag and above the <strong>rss</strong> tag then I'll be able to include those entities. I added but it doesn't seem to work. Does anyone knows what I missing? Thanks</p>
<p>it doesn't seem likely that many feed readers will know what to do with that. i would recommend sticking with numbered entity references. for example, change <code>&amp;ldquo;</code> to <code>&amp;#8220;</code>. you can get the full entity reference <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html" rel="nofollow">right here from w3c</a>.</p> <p>additionally, you can read <a href="http://myst-technology.com/public/item/11878" rel="nofollow">this article</a> and <a href="http://dotjay.co.uk/2006/sep/named-html-entities-in-rss" rel="nofollow">this one</a> which gives some good tips on this topic.</p>
Flash AS2.0 - Increase Label's Font Size <p>I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0.</p> <p>I have a label component, and I'm dynamically assigning it text from an xml document. For example:</p> <pre><code>label.text = "&lt;b&gt;" + xml_node.firstChild + "&lt;/b&gt;"; </code></pre> <p>This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using <code>&lt;font&gt;</code> tags won't work.</p> <p>Am I missing something? How do I make the font larger? ActionScript is just so picky!</p>
<p>When you say "label component", do you mean a Flex 2 label, or a TextField?</p> <p>In the latter case, the font tag should work just fine. will set the font to 24px text for example. If it doesn't, you can use the stylesheet class to specify a font size and then assign it to the TextField.</p> <p>In the case of of Flex 2 label, use label.setStyle("fontSize", 24) to set it to 24px text for example.</p>
Unit tests framework for databases <p>I´m looking for a unit tests framework for database development. I´m currently developing for SQL Server 2000, 2005 and 2008. Do you know of any good frameworks with similar functionality as JUnit and NUnit?<br /> Perhaps it´s better to ask, what do you use to unit test your stored procedures and user defined functions?</p>
<p>There is TSQLUnit... Link here: <a href="http://tsqlunit.sourceforge.net/" rel="nofollow">http://tsqlunit.sourceforge.net/</a></p>
Is there really no way to follow up dataset parent relation in xaml binding? <p>Suppose I have a dataset with those two immortal tables: Employee &amp; Order <br/> <strong>Emp</strong> -> ID, Name <br/> <strong>Ord</strong> -> Something, Anotherthing, EmpID <br/> And relation <strong>Rel</strong>: Ord (EmpID) -> Emp (ID) <br/></p> <p>It works great in standard master/detail scenario <br/> (show employees, follow down the relation, show related orders), <br/> but what when I wan't to go the opposite way (show Ord table with Emp.Name)? <br/></p> <p>Something like this:<br/></p> <pre><code>&lt;stackpanel&gt; // with datacontext set from code to dataset.tables["ord"] &lt;TextBox Text="{Binding Something}"/&gt; &lt;TextBox Text="{Binding Anotherthing}"/&gt; &lt;TextBox Text="{Binding ???}"/&gt; // that's my problem, how to show related Emp.Name &lt;/stackpanel&gt; </code></pre> <p>Any ideas? I can create value converter, but if I wan't to use dataset instance which I get from parent module it gets tricky.</p>
<p>If you want to synchronize the contents of multiple controls, you will need to have them share the same binding source through the <strong>DataContext</strong> set on a common parent control. Here is an example:</p> <pre><code>&lt;StackPanel&gt; &lt;StackPanel.Resources&gt; &lt;ObjectDataProvider x:Key="ds" ObjectType="{x:Type mynamespace:MyDataSet}" /&gt; &lt;/StackPanel.Resources&gt; &lt;!-- We set the data context to the collection of rows in the table --&gt; &lt;StackPanel DataContext="{Binding Source={StaticResource ds}, Path=USERS.Rows}"&gt; &lt;ListBox ItemsSource="{Binding}" DisplayMemberPath="NAME" IsSynchronizedWithCurrentItem="True" /&gt; &lt;TextBox Text="{Binding Path=NAME}"/&gt; &lt;TextBox Text="{Binding Path=COUNTRIESRow.NAME}"/&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; </code></pre> <p>Setting the <strong>IsSynchronizedWithCurrentItem</strong> property to 'True' will cause the <strong>ListBox.SelectedItem</strong> property to be automatically synchronized with the <strong>CollectionView.CurrentItem</strong> of the binding source, that is the collection of rows set at the <strong>DataContext</strong>. This means that the currently selected row in the ListBox becomes the binding source for the two TextBox controls.</p>
Best way to list files in Java, sorted by Date Modified? <p>I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.</p> <p>Edit: My current solution, as suggested, is to use an anonymous Comparator:</p> <pre><code>File[] files = directory.listFiles(); Arrays.sort(files, new Comparator&lt;File&gt;(){ public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); </code></pre>
<p>I think your solution is the only sensible way. The only way to get the list of files is to use <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html#listFiles%28%29">File.listFiles()</a> and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a> that uses <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html#lastModified%28%29">File.lastModified()</a> and pass this, along with the array of files, to <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort%28T%5b%5d,%20java.util.Comparator%29">Arrays.sort()</a>.</p>
Anybody know why SQL Server 2005 throws "'SQLOLEDB' failed with no error message available, result code: E_FAIL(0x80004005). "? <p>We've got a web system running SQL Server 2005 for the back end, and ASP.Net for the front end (using .net 2.0).</p> <p>Every now and then, the system barfs out the error in the title: 'SQLOLEDB' failed with no error message available, result code: E_FAIL(0x80004005). </p> <p>The web system runs just fine 24/7, and then every now and then will toss this out on a select or some such. I've tried re-running the exact select that throws the error, but (of course) it works fine when I do it. And, to answer the obvious follow-up question, no we haven't done any code changes or upgrades to speak of lately.</p> <p>Has anyone ever run into this before? Nosing around on google seems to only turn up situations where Access has some kind of file issue (permissions, missing data file, etc.)</p>
<p>Firstly, it's probably not SQL Server throwing out the error, and if it is, it's probably not while running the SQL statement itself, but if it is, it's almost certainly going to be peculiar to a login that doesn't have permissions, not the SQL command itself.</p> <p>The 0x80004005 error is a general permissions failure, and it can occur in just about anything, but it's most likely to be in another layer.</p> <p>I've seen it in authentication when the account the application is running under does not have access to the network to open a connection to the SQL Server. The SQL Server never even sees the request, but the client will say that the server cannot be found.</p> <p>If it's intermittent, that could point to an intermittent domain controller issue, but that would depend on how your Windows Servers and Active Directory are set up, and how your application is connecting to SQL Server.</p> <p>To solve this one, your netadmins will need to really know their Windows logging functionality and track it down for you.</p>
Best way of doing an SVn checkout/update on a web hosting package <p>I want to deploy my site on my web hosting package by doing a checkout through subversion. I do not have SSH access to my hosting package, which is just a basic LAMP web hosting package, but I do know that there is an SVN client installed on the web server.</p> <p>I was thinking of writing some sort of script (PHP or Shell) that can do different functions. Like a checkout, update, switch to another tag etc. and that I can call externally in some sort of fashion.</p> <p>Any input on best practices, things to look out for and how to go about this is very much appreciated.</p> <blockquote> <p><strong>UPDATE</strong>: I have been using the following technique for the past couple of weeks now. I've carefully crafted (and well tested) a couple shell scripts that I can execute from cron through cPanel. Whenever cron has completed a job it will email me the console output of the job. this way I can monitor if all commands succeeded. Since I only do updates on the server and no commits, I haven't run into any issues concerning Subversion. Of course, in my .htaccess files I have created a rule that will deny any access to the hidden .svn folders.</p> </blockquote>
<p>I would hesitate to manage your site on your web host with Subversion unless you have shell access. When performing Subversion operations, there might be things that require your interactive attention which you wouldn't be able to provide through a script interface.</p> <p>What I might suggest instead, is to maintain a local checkout directory that mirrors your remote directory. When you want to make a change to your live site, do an svn update on your local checkout, to make it look exactly like you want, then use your favourite mirroring tool (<code>rsync</code> or something) to push the site up to your web host.</p> <p>Alternately, you could switch web hosts to one where you have shell access. I manage some web sites this way using Git and it works really well.</p>
How to get current datetime on Windows command line, in a suitable format for using in a filename? <p><strong>EDIT</strong>: Now that it's 2016 I'd use powershell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="http://stackoverflow.com/a/19799236/8479">http://stackoverflow.com/a/19799236/8479</a></p> <hr> <p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p> <p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p> <p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p> <p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p> <pre><code>rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem Now use the timestamp by in a new ZIP file name. "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code </code></pre> <p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p> <p>I'm using Windows Server 2003 and Windows&nbsp;XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p>
<p>See <a href="http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/">Windows Batch File (.bat) to get current date in MMDDYYYY format.</a>:</p> <pre><code>@echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% </code></pre> <p>If you prefer the time in 24hr/military format, you can replace the second FOR line with this: </p> <pre><code>For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) </code></pre> <blockquote> <p>C:> .\date.bat <br /> 2008-10-14_0642</p> </blockquote> <p>If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:</p> <pre><code>@echo off for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^&gt;NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] </code></pre> <blockquote> <p>C:>test.cmd<br /> Local date is [2012-06-19 10:23:47.048]</p> </blockquote> <p><strong>EDIT</strong>: Added the time as well as the date as originally requested in your question <strong>EDIT</strong>: Added a region-independent variation using WMIC</p>
compiling only part of the source tree with ant <p>Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only <em>part</em> of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though!</p> <p>This can be easily achieved from the command line with:</p> <pre><code>javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java </code></pre> <p>Now, how can you do that with ant? The javac ant <a href="http://ant.apache.org/manual/Tasks/javac.html">task compiles everything</a>:</p> <blockquote> <p>The source and destination directory will be recursively scanned for Java source files to compile.</p> </blockquote> <p>One can use the <code>excludes</code> and <code>includes</code> parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the <code>includes</code> (not automatic dependency lookup), and <strong>even worst</strong> that <a href="http://ant.apache.org/manual/dirtasks.html#patternset">excludes has priority on includes</a>:</p> <blockquote> <p>When both inclusion and exclusion are used, only files/directories that match at least one of the include patterns and don't match <em>any</em> of the exclude patterns are used.</p> </blockquote> <p>Thus, you cannot use </p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" excludes="**/*.java" includes="src/path/to/MyClass.java" /&gt; </code></pre> <p>Because it will not compile anything :-(</p> <p>Is there any way of achieving that simple command line <code>javac</code> with ant?</p> <hr> <p>EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer):</p> <p>1) I did read the documentation (see links above), but it's unclear that with just <code>includes</code> you are actually also excluding everything else</p> <p>2) When you just <code>includes</code> ant logs something like</p> <pre><code>[javac] Compiling 1 source file to /my/path/to/build </code></pre> <p>even if the dependencies make it compiling (much) more than just one source file.</p>
<p>Why are you excluding as well as including? If you have at least one include, then files are only compiled if they're explicitly included. So this should work:</p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includes="src/path/to/MyClass.java" /&gt; </code></pre> <p>Or more flexibly:</p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"&gt; &lt;include name="src/path/to/MyClass.java"/&gt; &lt;include name="src/path/to/AnotherClass.java"/&gt; &lt;/javac&gt; </code></pre> <p>To include only certain packages or classes in a jar, use a fileset attribute</p> <pre><code>&lt;jar jarfile="${outlib}/something.jar"&gt; &lt;fileset dir="${build.dir}"&gt; &lt;include name='src/path/to/classes' /&gt; &lt;/fileset&gt; &lt;/jar&gt; </code></pre> <p>Again, you can use multiple includes to combine separate packages. Experiment with includes and <a href="http://ant.apache.org/manual/">read the documentation</a> and you're sure to find the answer you need.</p>
Undo changes to SQL Server 2005 database <p>I've ran some "ALTER" scripts on the database [SQL Server Server 2005], and overwrote some sprocs. Is there any way to undo changes and get my old sprocs back?</p> <p>Is there a way to get the scripts that were executed out of the .LDf file? That way i can re-run my initial "create" script for my sprocs.</p> <p>I don't have a backup file with old sprocs.</p> <p>p.s. i backed the DB up as per <a href="http://stackoverflow.com/users/4337/gulzar">@Gulzar's</a> deleted answer, and looks like I'm "hosed".</p> <p>@Pittsburgh DBA: thanx for the solution, but it doesn't seem to work after the backup.</p> <p><strong>MORAL: Wait for 10 minutes before trying the suggested answers out</strong></p> <p><hr></p> <p><strong>Update from Gulzar</strong>: What I meant was a file backup before trying anything (to be safe). Not a SQL Server backup.</p>
<p>FIRST: DO NOT TAKE ANY BACKUPS JUST YET.</p> <p>There are several tools on the market to do this sort of thing. </p> <p>You might try this one:</p> <p><a href="http://www.apexsql.com/sql_tools_log.asp" rel="nofollow">ApexSQL Log</a></p>
JQuery: Current, Well-Formatted, Printable Documentation? <p>I'm looking for a current (1.2), well-formatted, printable version of the jQuery documentation. I've checked the alternative resources page and see the PDF versions from CF and Java, but both are out of date.</p> <p>The jQuery site has the API browser with "Printable Version" in the toolbox, but it prints terribly, and I don't really want to print one page or tab at a time.</p> <p>I have a hard time believing that there is no print doc for a tool this popular - all I want is a simple listing with descriptions and examples ON PAPER.</p> <p>Am I missing something?</p> <p>I can buy one of the books if I need to, but not sure which is for the current version.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Update:</strong> I can see that somebody voted this down. I know it's a pretty basic question, but it is not asked lightly or frivolously. I have made a pretty solid effort to find this on my own, and am pretty good at finding information when I need it.</p> <p>Perhaps the person who thought the question not worth asking knows where to find the print doc?</p>
<p>take a look at <a href="http://charupload.wordpress.com/2007/12/07/jquery-documentation-chm/" rel="nofollow">this page</a>.</p> <p>it has compiled html help file (CHM) for latest jQuery 1.3.</p> <p>that guy also compiles another useful CHM manuals.</p>
How do I discriminate between data binding and user actions on WinForm controls <p>I have what must be a typical catch-22 problem. I have a .NET WinForm control that contains a textbox and a checkbox. Both controls are data bound to properties on a data class instance. The textbox is for price, the check box to indicate that the price is a price override. Also on the data class is a property that holds the item's original price.</p> <p>I would like the controls to respect the following rules:</p> <ul> <li>When the user enters a value into the price textbox, the checkbox is automatically checked to indicate they are overriding the price value</li> <li>When the check box is un-checked, the item's price is restored to the original price.</li> </ul> <p>When the user unchecks the checkbox, the event handler tests the checked state, and sets the item's price property to the original price value. However, the price value being databound, a bind event is fired, which updates the textbox value, which fires the text changed event handler which re-checks the checkbox. </p> <p>I've attempted to trap the conditions where I'm explicitly updating something that would trigger a control change event. This only works for part of it though. The textbox change event fires other times that are outside my control, such as when databinding fires when the form is initially shown.</p> <p>I've been searching around and I guess I'm just not coming up with the right search terms to find what I'm looking for. It seems that databinding is all wonderful and nifty until you need to do something pratical with it, like having two bound controls interact with each other. There just doesn't seem to be a way to discriminate between what triggered the control events.</p> <p>I've also looked at the events available on the binding source component but there doesn't seem to be anything there that is any more useful. I can handle the event that fires after binding is complete, but that's after the problems occur.</p> <p>Anyone have any suggestions?</p>
<p>I would suggest not handling the logic in the form code, but rather in the data class. All you need in the form is a couple of lines to set up the data binding. The data class can then take care of the rest:</p> <p>Form</p> <pre><code>Private _dc As DataClass Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load _dc = New DataClass txtPrice.DataBindings.Add("text", _dc, "Price") chkOverride.DataBindings.Add("checked", _dc, "override") End Sub </code></pre> <p>Data Class</p> <pre><code>Private _originalPrice As Double = 50 Private _price As Double = _originalPrice Public Property Price() As Double Get Return _price End Get Set(ByVal value As Double) If (_price &lt;&gt; value) Then _price = value Override = _price &lt;&gt; _originalPrice End If End Set End Property Private _override As Boolean Public Property Override() As Boolean Get Return _override End Get Set(ByVal value As Boolean) If _override &lt;&gt; value Then _override = value If Not _override Then Price = OriginalPrice End If End Set End Property </code></pre> <p>No need to handle any CheckedChanged or TextChanged events in the form.</p>
Include directory in VS 2003 <p>Where is the setting in Visual Studio 2003 to set the include path for individual projects? I know about the VC Directories option in Tools>Options but that is machine specific and won't help when I hand this off to other developers. </p>
<p><img src="http://www.lemurproject.org/images/VS_Net_AdditionalIncludes.jpg" alt="alt text" /></p>
How to make a bilingual site without creating a separate ASP page for each language? <p>I need ideas on how to go about table layout problem. I want to set different width of the columns dependent on the picked language.</p>
<p>You can have language specific CSS, and then simply load the appropriate CSS based on language.</p> <p>In the CSS you can add styles to your table for defining the layout.</p>
Why do my XSL transformed links come out relative to the base? <pre><code>&lt;a&gt; &lt;xsl:attribute name="href"&gt; &lt;xsl:value-of select="link" /&gt; &lt;/xsl:attribute&gt; &lt;xsl:attribute name="target"&gt;new&lt;/xsl:attribute&gt; &lt;xsl:value-of select="title" /&gt; &lt;/a&gt; </code></pre> <p>Thats my template, and in my code:</p> <pre><code> sb.Append("&lt;title&gt;"); sb.AppendFormat("{0} - {1}", f.UserName, f.PointTypeDesc); sb.Append("&lt;/title&gt;"); sb.Append("&lt;link&gt;"); sb.AppendFormat("{0}", HttpUtility.UrlEncode(url)); sb.Append("&lt;/link&gt;"); </code></pre> <p>url is "http://www.cnn.com"</p> <p>But it renders as: "http://localhost/<a href="http://www.cnn.com" rel="nofollow">http://www.cnn.com</a>"</p> <p>any ideas?</p>
<p>It seems to me that the problem must be with HttpUtility.UrlEncode. Have you checked the contents of the xml that you're creating? The XSL looks correct to me, although it could be written more tersely as:</p> <pre><code>&lt;a href="{@link}" target="new"&gt; &lt;xsl:value-of select="title"/&gt; &lt;/a&gt; </code></pre>
What is the best datatype to use for storing moderate amounts of text in SQL Server (2005)? <p>What is the best datatype to use for storing moderate amounts of text in SQL Server (2005)?</p> <p>For example, imagine a table, storing information on downloads available on a website. I want a title for the download which is brief, say varchar(20). A path, say varchar(255) then I want to store some user friendly text about the download - a description. In some cases it could be as short as the title, other times you may need a few of paragraphs of explanation.</p> <p>What's best? A varchar with a size of say 4000, or a varchar(max) or something else?</p>
<p>The PAD (Portable Application Description) specification highest character limit for program description is 2000 chars *see Program Descriptions section.</p> <p><a href="http://www.asp-shareware.org/pad/spec/spec.php" rel="nofollow">http://www.asp-shareware.org/pad/spec/spec.php</a></p> <p>Download site submission tools use this spec to make it easier for authors to submit their software. Also I think there are a couple lists you can download that follow the PAD spec.</p> <p>So I would suggest varchar(2000) based on that fact I wouldn't want to store more than I need to. One record would be fine with varchar(max), but when you have thousands the cost of storage might go up.</p> <p>Edit: varchar(max) can be 2GB - 1, that's why I would limit it. <a href="http://msdn.microsoft.com/en-us/library/ms176089(SQL.90).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms176089(SQL.90).aspx</a></p>
Memory in SWF (Flash Player) <p>Are there any limitations on the amount of memory that the flash player can use? If you have a swf that over time gets a lot of data from the server, then more and more data will be kept in memory... Is there a limitation on this?</p> <p>Thx, Lieven Cardoen</p>
<p>Not in any version of Flash that runs on desktop PCs. As long as your application keeps using more memory, desktop Flash will keep requesting it from the OS, until the OS runs out of memory or something crashes. Of course you the developer should limit your memory usage as appropriate, but Flash won't force you to do so.</p> <p>In Flash Lite (the mobile version designed for cell phones), the host application imposes preconfigured limits on memory usage, but that's probably not what you care about. :) </p>
Creating sine or square wave in C# <p>How do I generate an audio sine or square wave of a given frequency?</p> <p>I am hoping to do this to calibrate equipment, so how precise would these waves be?</p>
<p>You can use <a href="http://codeplex.com/naudio" rel="nofollow">NAudio</a> and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a <a href="http://en.wikipedia.org/wiki/WAV" rel="nofollow">WAV</a> file. If you used 32-bit floating point samples you could write the values directly out of the sin function without having to scale as it already goes between -1 and 1.</p> <p>As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses. </p> <p>Here's some example code that makes a 1&nbsp;kHz sample at a 8&nbsp;kHz sample rate and with 16 bit samples (that is, not floating point):</p> <pre><code>int sampleRate = 8000; short[] buffer = new short[8000]; double amplitude = 0.25 * short.MaxValue; double frequency = 1000; for (int n = 0; n &lt; buffer.Length; n++) { buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate)); } </code></pre>
C# streaming sockets, how to separate messages? <p>Kinda long title, but anyways...</p> <p>I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams<br /> <a href="http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html" rel="nofollow">http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html</a><br /> <a href="http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html" rel="nofollow">http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html</a></p> <p>But I can't seem to figure it out in C#.</p> <pre><code>StreamWriter writer = new StreamWriter(tcpClient.GetStream()); writer.Write(data.Length + data); </code></pre> <p>This doesn't work very well at all. Could someone give me a nudge in the right direction?</p>
<p>Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:</p> <pre><code> byte[] data = ... int len = data.Length; byte[] prefix = Bitconverter.GetBytes(len); stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes stream.Write(data, 0, data.Length); </code></pre> <p>Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, <a href="http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/SubStream.cs" rel="nofollow">this class</a> can be used to get a Stream that won't read too much.</p> <p>If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block.</p> <p>For info, <a href="http://code.google.com/p/protobuf-net/" rel="nofollow">protobuf-net</a> is a binary serializer designed around Google's "protocol buffers" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, <a href="http://code.google.com/p/protobuf-net/source/browse/trunk/QuickStart/3%20Sockets.cs" rel="nofollow">for example here</a></p>
How to manage a simple PHP session using C++ cURL (libcurl) <p>I'm writing a C++ client which is using libcurl for communicating with a PHP script.</p> <p>The communication should be session based, and thus the first task is to login and make the PHP script set up a session.</p> <p>I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and communicating session id.</p> <p>I can't find any example on the curl homepage which demonstrates a simple session management use case.</p> <p>I'm assuming it has something to do with one or many of the following options in curl:</p> <pre><code>CURLOPT_COOKIE CURLOPT_COOKIEFILE CURLOPT_COOKIEJAR CURLOPT_COOKIESESSION CURLOPT_COOKIELIST </code></pre> <p>But I can't really see the big picture just from the documentation of CURLOPT_COOKIESESSION for instance.</p> <p>Anybody who has done this, please share a simple piece of code which shows the concept.</p> <p>Regards</p> <p>Robert</p>
<p>As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session:</p> <pre><code>CURL *Handle = curl_easy_init(); // Read cookies from a previous session, as stored in MyCookieFileName. curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, MyCookieFileName ); // Save cookies from *this* session in MyCookieFileName curl_easy_setopt( Handle, CURLOPT_COOKIEJAR, MyCookieFileName ); curl_easy_setopt( Handle, CURLOPT_URL, MyLoginPageUrl ); assert( curl_easy_perform( Handle ) == CURLE_OK ); curl_easy_setopt( Handle, CURLOPT_URL, MyActionPageUrl ); assert( curl_easy_perform( Handle ) == CURLE_OK ); // The cookies are actually saved here. curl_easy_cleanup( Handle ); </code></pre> <p>I'm not positive that you need to set both COOKIEFILE and COOKIEJAR, but the documentation makes it seem that way. In any case, you have to set one of the two in order to enable cookies at all in CURL. You can do something as simple as:</p> <pre><code>curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, "" ); </code></pre> <p>That won't read any cookies from disk, but it will enable session cookies for the duration of the curl handle.</p>
getting the last modified date of a html file <p>how can i figure out the last modified date of a html file im importing into my web app?</p> <p>The html file is on another server and different users can make updates, when i retrieve the page i want to be able see when it was last updated so i can label the updated date on my homepage. I</p>
<p>Use the <code>document.lastModified</code> Javascript property.</p> <p>quirksmode has a nice function to format the date too: <a href="http://www.quirksmode.org/js/lastmod.html">http://www.quirksmode.org/js/lastmod.html</a></p>
What should I call a REBOL function that does list comprehensions? <p>REBOL has no built-in way to perform list comprehensions. However, REBOL has a powerful facility (known as <code>parse</code>) that can be used to create domain-specific languages (DSLs). I've used <code>parse</code> to create such a mini-DSL for list comprehensions. In order to interpret the expression, the block containing the comprehension is passed to a function, which for lack of a better term I've called <code>comprehend</code>.</p> <p><strong>Example:</strong></p> <pre><code>comprehend [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])] </code></pre> <p>For some reason, <code>comprehend</code> doesn't sound right to me, but something like <code>eval</code> is too general.</p> <p>I haven't found any other language that requires a keyword or function for list comprehensions. They are pure syntactic sugar wherever they exist. Unfortunately I don't have that option. So, seeing that I must have a function, what's a good, succinct, logical name for it?</p>
<p>How about <code>select</code>?</p> <p><code>select [(a * b) for a in 1x100 for b in 4x10 where (all [odd? a odd? b])]</code></p>
MSSQL2000: get list of role members <p>I know a role name and want to find all users in this role. How do I acheive this in SQL Server 2000 (in the SQL script, not in Management Studio or other tool)?</p>
<p>You can use the following stored procedures:</p> <p>For fixed server roles, the stored procedure is <a href="http://msdn.microsoft.com/en-us/library/ms188772.aspx" rel="nofollow">sp_helpsrvrolemember</a>:</p> <pre><code>exec sp_helpsrvrolemember 'role' </code></pre> <p>For general roles, the stored procedure is <a href="http://msdn.microsoft.com/en-us/library/ms178021.aspx" rel="nofollow">sp_helprolemember</a>:</p> <pre><code>exec sp_helprolemember 'role' </code></pre>