instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Do they set <code>display: none</code> or <code>visibility: hidden</code>?</p> <p>I'm pretty sure <code>display: none</code> takes the element out of the normal flow, whilst <code>visibility: hidden</code> just hides the element but still has a reserved space for it.</p> <p>Should I just go download the unpacked version and study it or does someone have a quick answer?</p>
<p>It uses <code>display</code>.</p> <p>Edit: And from John Sheehan's comment on this answer, which I agree with:</p> <blockquote> <p>You should go view the unpacked source anyway just to familiarize yourself with it</p> </blockquote> <p>Edit 2: Comments have mentioned using Firebug to discover what is happening. Indeed, I actually went to the jQuery docs and used the Safari Web Inspector to see what happened on the <code>hide()</code> demo to be sure of my answer.</p>
<p>It uses display, and for this type of thing you can use Firebug to actually examine what happens to the DOM. </p>
29,594
<p>I have the following HTML</p> <pre><code>&lt;div&gt; &lt;img id="image1" src="http://valleywag.com/assets/resources/2008/03/BlackGoogleLogo.jpg" alt="Why doesn't this float correcly?" style="border-width: 0px; float: left;" /&gt; &lt;div id="divText" style="font-family: Arial, Helvetica, sans-serif; font-size: 11px;" class="txt-Normal"&gt; &lt;div style="background-color: Green; color: White;"&gt; &lt;p&gt; &lt;strong&gt;&lt;span style="font-size: xx-large;"&gt;This is going to be big title&lt;/span&gt;&lt;/strong&gt; &lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;Foo&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;Bar&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;FooBar&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;BarFoo&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The text does not float around the image. It does not matter whether the browser IE or Firefox.</p> <p>How can I fix this to float around the image?</p>
<p>The text does float around the image for me in IE6 and FireFox2. Is there any CSS that you're leaving out for us to test?</p> <p>Here is what I see: </p> <p><a href="http://img214.imageshack.us/img214/6906/ff2topie6bottomhz5.gif" rel="nofollow noreferrer">Example 1 http://img214.imageshack.us/img214/6906/ff2topie6bottomhz5.gif</a></p> <p>The HTML example you provided <em>is</em> in an HTML document right? If so, what doctype are you using?</p> <p>If you are trying to make all of the text line up with the right side of the image, you may need to float your text's container left as well. That will produce an output like this:</p> <p><a href="http://img518.imageshack.us/img518/4619/bothfloatedsd7.gif" rel="nofollow noreferrer">Both Elements Floated http://img518.imageshack.us/img518/4619/bothfloatedsd7.gif</a></p> <p>You can do this by modifying your code like this:</p> <pre><code>&lt;div id="divText" style="font-family: Arial, Helvetica, sans-serif; font-size: 11px; float:left;" class="txt-Normal"&gt; </code></pre>
<p>The text is wrapping around the image for me in Firefox2. Can you maybe post a screenshot so I understand the problem better?</p> <p>If you mean the bullets overlap the image (which I do notice) then the best I can suggest is margin-right on the image or disable the bullet-style:</p>
46,722
<p>I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to write code that simulates a click on the "background" of the page?</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" &gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" &gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("main").focus(); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main"&gt; &lt;form action="/"&gt; &lt;p&gt; &lt;input type="text" id="input"/&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>I would imagine using <code>blur()</code> would do the trick:</p> <pre><code>&lt;script type="text/javascript"&gt; YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("input").blur(); }); &lt;/script&gt; </code></pre>
<p>Your idea is right, but there is a little problem.</p> <pre><code>document.getElementById(&quot;main&quot;).focus(); &lt;div id=&quot;main&quot;&gt; </code></pre> <p>as shown in your code, actually the div HTMLElement doesn't have a focus method.</p> <p>so you can call other elements that have a focus method or call <code>blur()</code> on the input element</p>
27,154
<p>By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.</p>
<p>I think what you want is:</p> <pre><code>:set wrap! </code></pre> <p>This will toggle line wrapping.</p> <p>More about using ! (bang) to alter commands can be found at:</p> <pre><code>:help :_! </code></pre>
<p>I happen to like tpope’s unimpaired plugin, where <code>yow</code> will toggle wrap settings. </p>
30,824
<p>I've used HttpWebRequests to post data to HTTPS websites before, and I've never had todo anything different than a regular HTTP Post.</p> <p>Does anyone know if there are any tricks involved that I missed to ensure that this is done properly?</p>
<p>Check for certification errors, this i a common issue <a href="http://www.west-wind.com/weblog/posts/48909.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/48909.aspx</a></p>
<p>HTTPS requests are the same as HTTP (only using SSL certificates).</p> <p>However you should manually ensure that the certificates do not have errors (even warnings), or the request will probably fail.</p>
30,248
<p>How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?</p> <p>i.e. an <code>encode()</code> function such that:</p> <pre><code>encode("“£”") -&gt; "&amp;#8220;&amp;#163;&amp;#8221;" </code></pre> <p><code>decode()</code> would also be useful:</p> <pre><code>decode("&amp;#8220;&amp;#163;&amp;#8221;") -&gt; "“£”" </code></pre> <p>PHP's <code>htmlenties()</code>/<code>html_entity_decode()</code> pair does not do the right thing:</p> <pre><code>htmlentities(html_entity_decode("&amp;#8220;&amp;#163;&amp;#8221;")) -&gt; "&amp;amp;#8220;&amp;pound;&amp;amp;#8221;" </code></pre> <p>Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:</p> <pre><code>htmlentities(html_entity_decode("&amp;#8220;&amp;#163;&amp;#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") -&gt; "&amp;ldquo;&amp;pound;&amp;rdquo;" </code></pre>
<p><a href="http://php.net/manual/en/function.mb-encode-numericentity.php" rel="noreferrer"><code>mb_encode_numericentity</code></a> does that exactly.</p>
<p>It's a bit of a workaround, but I read a bit about <code>iconv()</code> and i don't think it'll give you numeric entities (not put to the test)</p> <pre><code>function decode( $string ) { $doc = new DOMDocument( "1.0", "UTF-8" ); $doc-&gt;LoadXML( '&lt;?xml version="1.0" encoding="UTF-8"?&gt;'."\n".'&lt;x /&gt;', LIBXML_NOENT ); $doc-&gt;documentElement-&gt;appendChild( $doc-&gt;createTextNode( $string ) ); $output = $doc-&gt;saveXML( $doc ); $output = preg_replace( '/&lt;\?([^&gt;]+)\?&gt;/', '', $output ); $output = str_replace( array( '&lt;x&gt;', '&lt;/x&gt;' ), array( '', '' ), $output ); return trim( $output ); } </code></pre> <p>This however, I have put to the test. I might do the reverse later, just don't hold your breath ;-)</p>
14,401
<p>I've read the Wikipedia articles for both <a href="http://en.wikipedia.org/wiki/Procedural_programming" rel="noreferrer">procedural programming</a> and <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional programming</a>, but I'm still slightly confused. Could someone boil it down to the core?</p>
<p>A functional language (ideally) allows you to write a mathematical function, i.e. a function that takes <em>n</em> arguments and returns a value. If the program is executed, this function is logically evaluated as needed.<sup>1</sup></p> <p>A procedural language, on the other hand, performs a series of <em>sequential</em> steps. (There's a way of transforming sequential logic into functional logic called <a href="http://en.wikipedia.org/wiki/Continuation_passing_style" rel="noreferrer">continuation passing style</a>.)</p> <p>As a consequence, a purely functional program always yields <em>the same value</em> for an input, and the order of evaluation is not well-defined; which means that uncertain values like user input or random values are hard to model in purely functional languages.</p> <hr> <p><sup>1</sup> As everything else in this answer, that’s a generalisation. This property, evaluating a computation when its result is needed rather than sequentially where it’s called, is known as “laziness”. Not all functional languages are actually universally lazy, nor is laziness restricted to functional programming. Rather, the description given here provides a “mental framework” to think about different programming styles that are not distinct and opposite categories but rather fluid ideas.</p>
<p>To Understand the difference, one needs to to understand that "the godfather" paradigm of both procedural and functional programming is the <strong>imperative programming</strong>.</p> <p>Basically procedural programming is merely a way of structuring imperative programs in which the primary method of abstraction is the "procedure." (or "function" in some programming languages). Even Object Oriented Programming is just another way of structuring an imperative program, where the state is encapsulated in objects, becoming an object with a "current state," plus this object has a set of functions, methods, and other stuff that let you the programmer manipulate or update the state.</p> <p>Now, in regards to functional programming, the <em>gist</em> in its approach is that it identifies what values to take and how these values should be transferred. (so there is no state, and no mutable data as it takes functions as first class values and pass them as parameters to other functions).</p> <p>PS: understanding every programming paradigm is used for should clarify the differences between all of them.</p> <p>PSS: In the end of the day, programming paradigms are just different approaches to solving problems.</p> <p>PSS: <a href="https://www.quora.com/Are-procedural-and-imperative-programming-the-same/answer/Mark-Sheldon-15" rel="nofollow noreferrer">this</a> quora answer has a great explanation.</p>
4,327
<p>I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?</p>
<p>I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. <strong>EDIT:</strong> now with code snippet!</p> <pre><code>INSERT INTO TABLE_2 SELECT DISTINCT * FROM TABLE_1 GO DELETE FROM TABLE_1 GO INSERT INTO TABLE_1 SELECT * FROM TABLE_2 GO </code></pre>
<p>I'm not sure if this works with DELETE statements, but this is a way to find duplicate rows:</p> <pre><code> SELECT * FROM myTable t1, myTable t2 WHERE t1.field = t2.field AND t1.id &gt; t2.id </code></pre> <p>I'm not sure if you can just change the "SELECT" to a "DELETE" <em>(someone wanna let me know?)</em>, but even if you can't, you could just make it into a subquery.</p>
11,721
<p>I've got C# code that accesses MySQL through ODBC.</p> <p>It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?</p>
<p>MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time:</p> <pre><code>INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015); </code></pre> <p>I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself.</p>
<p>When using MySQL 4.x a few years ago, we ran into a hard limit on query size that was not configurable. </p> <p>This probably won't help you much as:</p> <ol> <li>I don't remember what the hard limit was.</li> <li>You're probably not using MySQL 4.x. </li> <li>We weren't using transactions.</li> </ol> <p>Good luck!</p>
13,608
<p>What characters are valid in a Java class name? What other rules govern Java class names (for instance, Java class names cannot begin with a number)?</p>
<p>You can have almost any character, including most Unicode characters! The exact definition is in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8" rel="noreferrer">the Java Language Specification under section 3.8: Identifiers</a>.</p> <blockquote> <p>An <em>identifier</em> is an unlimited-length sequence of <em>Java letters</em> and <em>Java digits</em>, the first of which must be a <em>Java letter</em>. ...</p> <p>Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.</p> <p>An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.</p> </blockquote> <p>However, see <a href="https://stackoverflow.com/questions/61615/should-you-use-international-identifiers-in-javac">this question</a> for whether or not you should do that.</p>
<p>Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:</p> <p><a href="http://www.oracle.com/technetwork/java/codeconventions-135099.html" rel="nofollow">http://www.oracle.com/technetwork/java/codeconventions-135099.html</a></p>
9,121
<p>I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?</p>
<p>When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.</p>
<p>The Form class doesn't provide any kind of reference to the 'parent' Form, so there's no direct way to access the parent (unless it happens to be the MDI parent as well, in which case you could access it through the MDIParent property). You'd have to pass a reference to the parent in the constructor of the child, or a property and then remember to set it, and then use that reference to force the parent to close.</p>
6,223
<p>I upgraded to an Mk9 dual extruder, and it came with thermocouples installed instead of the thermistors I had before. </p> <p>No matter what I did with the thermocouples, the indicated temperature jumped around by as much as 30C or more. In short, after several weeks of fiddling I never got the thermocouples to work well, and replaced them with thermistors, which have been fine.</p> <p>So my question is: what is required to get thermocouples to give reliable, consistent, accurate readings? Are they just incredibly touchy?</p> <p>Some things I tried include:</p> <ul> <li><p>Of course, one must add circuitry (typically a thermocouple amplifier board such as <a href="http://wiki.ultimaker.com/Thermocouple_Sensor_Board_v1">http://wiki.ultimaker.com/Thermocouple_Sensor_Board_v1</a>), to convert the tiny voltage differences to larger differences usable with Arduino or similar analog inputs.</p></li> <li><p>Place those boards close to the thermocouples, but far enough that they are at pretty stable temperature themselves.</p></li> <li><p>Have absolutely no wire extensions of splices, changes of wire types (material), etc.</p></li> <li><p>Avoid doing repeated measurements too fast.</p></li> <li><p>I replaced a thermocouple board with 5V through a potentiometer to the analog input pin, to rule out problems in the Arduino, pin configurations, or software, and got stable readings.</p></li> <li><p>I checked for shorts-to-ground from the heater block, both sides of the thermocouples, the heater itself, etc. None found.</p></li> <li><p>The thermocouple wires are surrounded by a braided shield (not common or shorted to either thermocouple wire); I tried grounding that at either end and at both ends, to the heat block, the printer frame, the power-supply ground, and the RAMPS board ground. These had various effects (sometimes large), but I couldn't find any configuration that made the readings stable (much less accurate!).</p></li> </ul> <p>Anything I'm missing?</p> <p>Thanks!</p> <p>Steve</p>
<p>Thermocouples work by passively generating VERY small voltages via the Seebeck effect -- usually a few tens of millivolts. They're literally just a pair of wires made from two different special alloys, electrically connected together at the "hot" end. That wire junction can be mounted inside whatever kind of attachment tip or lug is desired.</p> <p>The fact that they're very simple and passive devices makes them extremely precise and consistent between TCs of the same type, MUCH more so than thermistors. Any type-K thermocouple in the world will give you the same accurate output +/-1-2C or so. You can even cut a thermocouple in half, re-twist the ends of the wires together, and it'll still work! </p> <p>However, the very small (millivolts) signal they generate is quite susceptible to electrical noise and circuit design. The signal voltage has to be greatly amplified to be useful. So it doesn't take much EMR from your heater or stepper wires to interfere with the TC reading. A frequent problem with TC circuits in 3d printers is the dreaded GROUND LOOP -- if the "hot" tip is electrically connected to the hot block, voltage and current on the heater and motor wires can induce small currents through the TC wires that totally screw up the millivolt signal. The amplifier picks up these stray voltages and it throws off the temp read. So, there are some important guidelines for keeping noise out of the TC wires:</p> <ul> <li>The TC wires must be electrically insulated from the mounting hardware (eye lug, thermowell, whatever your extruder has). You can check this with a multimeter -- you want infinite / out of range resistance from the TC leads to the mounting tip and hot block. While you're at it, make sure your heater cartridge wires aren't shorting to the hot block -- that's unsafe and can also cause problems with TCs.</li> <li>Keep the two TC wires close together, and not immediately parallel to noise sources like PWM-controlled heaters or stepper wiring. If you must run the TC in a bundle with the other wires, TWIST the heater/stepper wiring pairs. (For steppers, twist each coil pair to a different pitch if possible. You don't need to twist the separate coil pairs to each other.) </li> </ul> <p>Another common issue with TC circuits is the COLD JUNCTION COMPENSATION. A thermocouple doesn't measure tip temperature, it measures the DIFFERENCE in temperature between the hot tip and the cold junction where the TC is connected to either the amp or copper wiring. The TC amp has an onboard thermistor that it uses to add the temp at the cold junction to the measured signal from the thermocouple. There are a few things you need to do to make sure the cold-junction compensation works properly:</p> <ul> <li>You should run TC wire all the way from the "hot" tip to the TC amp. You CAN splice it and install plugs, but only with more type-K TC wire and proper type-K thermocouple plugs. These use the same metal as the TC wire so they don't generate undesired junction voltages that interfere with the TC signal. If you splice copper wire between the TC and the amp, any temp differences along the copper will not be measured! This is a particularly big problem if you splice to copper inside a warm enclosure and then run copper to an amp outside the enclosure.</li> <li>The amp should not be super hot. The onboard thermistor is designed to accurately measure temperatures reasonably close to room temp, not hot-block temps. </li> <li>There should not be large temperature gradients near the amp or between the TC wire termination and the actual amp chip. Place the amp far enough away from the hot end and other heat sources (like stepper motors) that it isn't experiencing weird temp profiles.</li> </ul> <p>If you do the above, the TC will output a good signal, and the amp will read it properly. But there's one more hitch. The mainboard has to know how to understand the amp's output. 3D printer control boards that are designed exclusively for TCs, like Mightyboards, usually use digital communication between the amp and the main control chip (MCU). This is high-reliability and does not require any special firmware configuration -- support is baked in. But if you're strapping an external TC amp onto a board that is expecting thermistors, <strong>you will have to tell the firmware how to read the signal from the amp.</strong> The most common technique is for the amp to output a linear voltage signal to the MCU's normal thermistor input (ADC). Then you configure the firmware to use the appropriate "thermistor table" (really a voltage lookup table) for that particular amp. Depending on your controller board, you also may need to make sure the regular thermistor pull-up/pull-down resistors aren't affecting the amp's output.</p> <p>So you need to make sure:</p> <ul> <li>You don't have electrical noise issues</li> <li>The cold-junction compensation is working as intended</li> <li>The firmware and controller board is configured correctly for your amp chip's output</li> </ul> <p>If you do all that, a TC should give superior accuracy and reliability over a thermistor. </p>
<p>It sound like you just have a defective thermocouple. But, I just did a google search for "Why are thermocouples inaccurate" and found <a href="http://www.temprel.com/support/troubleshoot-thermocouple.aspx" rel="nofollow">this article</a> on identifying bad thermocouples and preventative maintenance. I never thought of a lot of the tips in the article, but I haven't had such drastic temperature errors either.</p>
126
<p>What, if any, considerations (HTML, CSS, JavaScript) should you take when designing for Google Chrome? </p>
<p>Chrome uses Webkit, the same engine as is used by Safari, OmniWeb, iCab and more. Just code everything based on the standards and verify in each browser.</p>
<p>Are you designing specifically <em>for</em> Chrome, or do you want to make sure your pages work well with Chrome?</p> <p>Assuming it's the latter, then just use the same design considerations you'd do for any browser. If applicable, keep in mind that many phones and video game consoles have web browsers now.</p> <p>Chrome uses a new JavaScript engine, so you'll have to test your JavaScript using Chrome as well as Safari. The HTML and CSS may render pretty much the same, but they use different JavaScript engines.</p>
6,785
<p>I'm writing a number of articles meant to teach beginning programming concepts through the use of poker-related topics. Currently, I'm working on the subject of shuffling.</p> <p>As <a href="http://www.codinghorror.com/blog/archives/001015.html" rel="nofollow noreferrer" title="The Danger of Naivete">Jeff Atwood points out on CodingHorror.com</a>, one simple shuffling method (iterating through an array and swapping each card with a random card elsewhere in the array) creates an uneven distribution of permutations. In an actual application, I would just use the <a href="http://en.wikipedia.org/wiki/Knuth_shuffle" rel="nofollow noreferrer" title="Knuth Fisher-Yates shuffle">Knuth Fisher-Yates shuffle</a> for more uniform randomness. But, I don't want to bog down an explanation of programming concepts with the much less coder-friendly algorithm.</p> <p>This leads to the question: Just how much of an advantage would a black-hat have if they knew you were using a naive shuffle of a 52-card deck? It seems like it would be infinitesimally small.</p>
<p>The knuth shuffle is an insignificant change compared to the naive shuffle: Just swap with any card in the remaining (unshuffled) section of the deck instead of anywhere in the entire deck. If you think of it as repeatedly choosing the next card in order from the remaining unchosen cards, it's pretty intuitive, too.</p> <p>Personally, I think teaching students a poor algorithm when the proper one is no more complicated (and easier to visualise!) is a bad approach.</p>
<p>Subjective.</p> <blockquote> <p>It seems like it would be infinitesimally small.</p> </blockquote> <p>Agree.</p>
12,234
<p>What is the best way to handle large numeric inputs in C++ (for example <code>10^100</code>)? </p> <p>For algorithms I usually switch over to ruby and I sometimes use strings.</p> <p>Any other good methods?</p>
<p>It sounds like you're looking for a way to enter Arbitrary Precision numbers. here are two libraries you could use: <a href="http://gmplib.org/" rel="nofollow noreferrer">GMP</a> and <a href="https://github.com/LuaDist/mapm" rel="nofollow noreferrer">MAPM</a></p>
<p>Well I think the best way to do such arithmetic calculation is by using strings. Give input as command line arguments and then manipulate the whole logic using string functions like <code>atoi()</code> and <code>itoa()</code>! But, hey can this be done for multiplication and Division? I think in this way <code>strlen</code> of strings entered doesn't matter for programming for compiler until the logic is fine.</p>
14,303
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt; s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and dirty:</p> <pre><code>&gt;&gt;&gt; elem = s.pop() &gt;&gt;&gt; s.add(elem) </code></pre> <p>But do you know of a better way? Ideally in constant time.</p>
<p>Two options that don't require copying the whole set:</p> <pre><code>for e in s: break # e is now an element from s </code></pre> <p>Or...</p> <pre><code>e = next(iter(s)) </code></pre> <p>But in general, sets don't support indexing or slicing.</p>
<p>Another option is to use a dictionary with values you don't care about. E.g.,</p> <pre><code> poor_man_set = {} poor_man_set[1] = None poor_man_set[2] = None poor_man_set[3] = None ... </code></pre> <p>You can treat the keys as a set except that they're just an array:</p> <pre><code> keys = poor_man_set.keys() print "Some key = %s" % keys[0] </code></pre> <p>A side effect of this choice is that your code will be backwards compatible with older, pre-<code>set</code> versions of Python. It's maybe not the best answer but it's another option.</p> <p>Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:</p> <pre><code> poor_man_set = {} poor_man_set[1] = None poor_man_set[2] = None poor_man_set[3] = None poor_man_set = poor_man_set.keys() </code></pre>
8,455
<p>I have a composite control that adds a TextBox and a Label control to its Controls collection. When i try to set the Label's AssociatedControlID to the ClientID of the Textbox i get this error</p> <pre><code>Unable to find control with id 'ctl00_MainContentPlaceholder_MatrixSetControl_mec50_tb' that is associated with the Label 'lb'. </code></pre> <p>Ok so a little background. I got this main-composite control that dynamically adds a number of 'elements' to its control collection. One of these elements happen to be this 'MatrixTextBox' which is the control consisting of a TextBox and a Label.</p> <p>I hold the Label and TextBox as protected class variables and init them in CreateChildControls:</p> <pre><code> ElementTextBox = new TextBox(); ElementTextBox.ID = "tb"; Controls.Add(ElementTextBox); ElementLabel = new Label(); ElementLabel.ID = "lb"; Controls.Add(ElementLabel); </code></pre> <p>I tried setting the</p> <pre><code>ElementLabel.AssociatedControlID = ElementTextBox.ClientID; </code></pre> <p>both right after adding the controls to the Controls collection and even in PreRender - both yield the same error. What am i doing wrong?</p>
<p>I think you <strong>mustn't use the ClientID</strong> property of the ElementTextBox, but the <strong>ID</strong>. ClientID is the page-unique ID you'd have to use in Javascript, e.g. in the document.getElementyById and is not the same as the server-side ID - especially if you have a masterpage and/or controls in controls etc.</p> <p>So it should be:</p> <pre><code>ElementLabel.AssociatedControlID = ElementTextBox.ID; </code></pre> <p>Hope this helps.</p>
<p>Possibly helpful to other readers that encounter the error:</p> <p>Note that setting AssociatedControlID fails too if you're associating the label with an input control at runtime without explicitly setting the ID of the input control first. This is an issue that requires attention if you are creating multiple textboxes, checkboxes or radiobuttions with labels dynamically.</p> <pre><code>private void AddRadioButton(PlaceHolder placeholder, string groupname, string text) { RadioButton radio = new RadioButton(); radio.GroupName = groupname; radio.ID = Guid.NewGuid().ToString(); // Always set an ID. Label label = new Label(); label.Text = text; label.AssociatedControlID = radio.ID; placeholder.Controls.Add(radio); placeholder.Controls.Add(label); } </code></pre>
27,765
<p>I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is <code>RadioButton</code>)) is never hit and the RadioButton control is identified as a <code>Checkbox</code> control.</p> <pre><code> private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } </code></pre> <p>Two Questions:<br> 1. How do I identify which control is a radiobutton? <br> 2. How do I disable it so that it posts back its value?</p>
<p>I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls.</p> <pre><code> private static void DisableControl(WebControl control) { Type controlType = control.GetType(); if (controlType == typeof(CheckBox)) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (controlType == typeof(RadioButton)) { ((RadioButton)control).InputAttributes.Add("disabled", "true"); } else if (controlType == typeof(ImageButton)) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } </code></pre> <p>And the solution I used is to set SubmitDisabledControls="True" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'><a href="https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx</a>.</p>
<p>Off the top of my head, I think you have to check the "type" attribute of the checkbox to determine if it's a radio button.</p>
5,211
<p>I am preparing to use continuous integration for the first time. I will be using Nant for the automated build and testing tasks, and am trying to find the appropriate CI tool to poll the repository and execute the Nant script.</p> <p>I have so far loosely researched the following:</p> <ul> <li>Hudson</li> <li>Cruise Control</li> <li>Draco</li> </ul> <p>My sense so far is that since most of the work will be done by Nant, Draco would be fine because it is supposed to be easy to install/setup. Cruise Control and Hudson, on the other hand might provide better reporting options.</p> <p>What is the best way to perform Continuous Integration when using Nant for the build and test tasks?</p>
<p>We use <a href="http://confluence.public.thoughtworks.org/display/CCNET" rel="nofollow noreferrer">CruiseControl.NET</a> as our CI server along with our full build system being in NAnt. It has worked exceptionally well over the past 5 years. I've since looked into other alternatives and have not been able to find any compelling reason(s) to switch.</p> <p>CruiseControl.NET has amazing support for different source control systems. Also, I enjoy how extensible their application is as we've built a few systems that integrate into it.</p>
<p>I can't speak for the applications listed, but I'm a huge fan of buildbot: <br><a href="http://buildbot.net/trac" rel="nofollow noreferrer">http://buildbot.net/trac</a></p> <p>It will build/test on any platform that runs Python (so if your software is supposed to work on multiple OS's each can be covered), it is very easy to use, and extremely extensible.</p>
22,746
<p>I'm just learning how to use a 3D printer, I have an Anycubic Mega Zero 2.0.</p> <p>When I start printing the PLA filament doesn't want to adhere very well. I have leveled it out and all of my corners on my test print adhere well. However, when I go to print anything besides the test print I get basically a small bead - it doesn't smooth flat. If I try and adjust from there it starts pushing all the material around.</p> <p>This lack of adhesion and bead continue throughout the print making it flimsy. It's weird because it looks nice but it's not strong.</p> <p><a href="https://i.stack.imgur.com/8CAGr.jpg" rel="nofollow noreferrer" title="Print on bed"><img src="https://i.stack.imgur.com/8CAGr.jpg" alt="Print on bed" title="Print on bed" /></a></p> <p><a href="https://i.stack.imgur.com/XIqlp.jpg" rel="nofollow noreferrer" title="Flimsy printed filament"><img src="https://i.stack.imgur.com/XIqlp.jpg" alt="Flimsy printed filament" title="Flimsy printed filament" /></a></p> <p><a href="https://i.stack.imgur.com/HfpdH.jpg" rel="nofollow noreferrer" title="Finished print"><img src="https://i.stack.imgur.com/HfpdH.jpg" alt="Finished print" title="Finished print" /></a></p> <p><a href="https://i.stack.imgur.com/R6PeV.jpg" rel="nofollow noreferrer" title="Base of finished print"><img src="https://i.stack.imgur.com/R6PeV.jpg" alt="Base of finished print" title="Base of finished print" /></a></p>
<p>If you look at the multiple lines of the skirt, you see that none of the printed lines are touching the other laid down lines. This is an indication for under extrusion or a too large of a gap between the nozzle and the bed (or both). Considering you are talking about a bead/drop/blob of hot filament not adhering to the bed, this might be a good indication for a too large of a distance, if the gap is too large, the filament will not adhere to the bed and forms a blob. You could consider decreasing the gap by leveling with a thinner piece of paper or feeler gauge first. An alternative that might be quick to test is to re-define the bed height prior to printing using a plug-in in Ultimaker Cura or manually inserted in your G-code file. E.g. in you start code, add a move to a certain height and define that to a different height:</p> <pre><code>G1 Z0.2 ; move printer head to 0.2 mm height G92 Z0.24 ; re-define 0.2 to 0.24 mm, if the first layer prints at e.g. 0.2 mm, ; the printer will move down 0.04 mm </code></pre> <p>The images aren't very sharp, but, from one of the top layers it looks like you are indeed suffering from under extrusion. First, check if the filament can unwind freely without too much force from the spool. Second, under extrusion should be fixed by <a href="https://3dprinting.stackexchange.com/a/6484/5740">adjusting the steps per millimeter value</a>. Beware, a new printer should have the correct value already inserted in the firmware, you should definitely check the filament path for obstructions first.</p> <p>A glass bed should be pretty flat, but it has been reported that there are glass manufacturers that produce low quality glass beds with dents. If so, you could shim the middle of the heated bed. An alternative is to flash new firmware and mesh the glass bed and the printer will automatically adjust for the height; this is not recommended for beginners.</p> <p>You could also increase the temperature of the bed, PLA can be printed on a cold prepared bed, but works very well on beds at 50-60 °C. You could consider using an adhesive on the glass as well, certain hairsprays, certain glue sticks, and special adhesive print sprays like 3DLAC work very well.</p> <p>Last but not least, incorrect filament diameter can cause under extrusion, older versions of Cura are notorious for resetting the filament diameter to 2.85 mm when you need e.g. 1.75 mm.</p>
<p>If the print bed is contaminated with oil or fat, print bed adhesion may be too low. Cleaning with alcohol might help.</p>
2,001
<p>If I have the LINQ objects:</p> <pre><code>public class SampleDataContext : DataContext { public Table&lt;Customer&gt; Customers { get { return this.GetTable&lt;Customer&gt;(); } } public SampleDataContext( string connectionString ) : base( connectionString ) { } } [Table( Name="dbo.tblCustomers" )] public class Customer { private Guid? customerID; [Column( Storage="customerID", DbType="uniqueidentifier NOT NULL", IsPrimaryKey=true )] public Guid? CustomerID { get { return this.customerID; } set { this.customerID = value; } } private string customerName; [Column( Storage = "customerName", DbType = "nvarchar(255) NOT NULL" )] public string CustomerName { get { return this.customerName; } set { this.customerName = value; } } } </code></pre> <p>and somewhere else in application:</p> <pre><code>public static void DoSomethingWithCustomer( Customer customer ) { // some operations // now, I want save changes to the database } </code></pre> <p>how can I get instance of DataContext which tracks changes of the "customer" object?</p> <p><strong>Edit: Why I don't want pass the DataContext into method.</strong></p> <p>1) Passing always 2 objects instead of 1 is "ugly" pattern for whole application.</p> <ul> <li>Methods will need next parameter for every business object.</li> <li>Collection will needs changed from "List" to "List>".</li> </ul> <p>Both points will more hard to maintain - developer must every-time sets the correct instance of DataContext (easy to create a bug), despite the DataContext know that the concrete object is(or not) attached to another DataContext.</p> <p>2) I want (current version of application use it) process "any" business logic on collection of objects which came from different "places" ( floating windows by drag &amp; drop for example ).</p> <p>Currentyl we use custom typed DataSets, so informations about changes are in the data rows (DataRow = business object) and wasn't problem to get it, or create a clone and then save it into database.</p>
<p>Kevin - I feel your pain... when you are building business logic around your business objects, there are times when you simply <em>have</em> to have access to the DataContext to which an object belongs, since not knowing the DataContext menas having to put your code in places that reduce the maintainability of your code.</p> <p>I wrote the following code (VB, I'm afraid), which presents a Context property which can be placed onto a data object, and then used to return the DataContext (if any) that the object is attached to.</p> <pre><code>Private Const StandardChangeTrackerName As String = &quot;System.Data.Linq.ChangeTracker+StandardChangeTracker&quot; Private _context As DataClasses1DataContext Public Property Context() As DataClasses1DataContext Get Dim hasContext As Boolean = False Dim myType As Type = Me.GetType() Dim propertyChangingField As FieldInfo = myType.GetField(&quot;PropertyChangingEvent&quot;, BindingFlags.NonPublic Or BindingFlags.Instance) Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me) Dim delegateType As Type = Nothing For Each thisDelegate In propertyChangingDelegate.GetInvocationList() delegateType = thisDelegate.Target.GetType() If delegateType.FullName.Equals(StandardChangeTrackerName) Then propertyChangingDelegate = thisDelegate hasContext = True Exit For End If Next If hasContext Then Dim targetField = propertyChangingDelegate.Target Dim servicesField As FieldInfo = targetField.GetType().GetField(&quot;services&quot;, BindingFlags.NonPublic Or BindingFlags.Instance) If servicesField IsNot Nothing Then Dim servicesObject = servicesField.GetValue(targetField) Dim contextField As FieldInfo = servicesObject.GetType.GetField(&quot;context&quot;, BindingFlags.NonPublic Or BindingFlags.Instance) _context = contextField.GetValue(servicesObject) End If End If Return _context End Get Set(ByVal value As DataClasses1DataContext) _context = value End Set End Property </code></pre> <p>Here is a C# version:</p> <pre><code>public DataContext GetMyDataContext() { // Find the StandardChangeTracker listening to property changes on this object. // If no StandardChangeTracker is listening, then this object is probably not // attached to a data context. var eventField = this.GetType().GetField(&quot;PropertyChangingEvent&quot;, BindingFlags.NonPublic | BindingFlags.Instance); var eventDelegate = eventField.GetValue(this) as Delegate; if (eventDelegate == null) return null; eventDelegate = eventDelegate.GetInvocationList().FirstOrDefault( del =&gt; del.Target.GetType().FullName == &quot;System.Data.Linq.ChangeTracker+StandardChangeTracker&quot;); if (eventDelegate == null) return null; // Dig through the objects to get the underlying DataContext. // If the following fails, then there was most likely an internal change // to the LINQ-to-SQL framework classes. var targetField = eventDelegate.Target; var servicesField = targetField.GetType().GetField(&quot;services&quot;, BindingFlags.NonPublic | BindingFlags.Instance); var servicesObject = servicesField.GetValue(targetField); var contextField = servicesObject.GetType().GetField(&quot;context&quot;, BindingFlags.NonPublic | BindingFlags.Instance); return (DataContext)contextField.GetValue(servicesObject); } </code></pre> <p>Take care to note that the object can only locate it's DataContext if it is currently attached to the context with ChangeTracking switched on. This property relies on the fact that the DataContext has subscribed to the object's OnPropertyChanging event to monitor changes over the lifespan of the object.</p> <p>If this was helpful, please up-vote this post.</p> <p>For more info on using reflection to find event handlers:</p> <ul> <li><a href="https://weblogs.asp.net/avnerk/reflecting-over-an-event" rel="nofollow noreferrer">http://weblogs.asp.net/avnerk/archive/2007/03/29/reflecting-over-an-event.aspx</a></li> <li><a href="https://web.archive.org/web/20131213074318/http://bobpowell.net/eventsubscribers.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20131213074318/http://bobpowell.net/eventsubscribers.aspx</a></li> </ul>
<p>The simplest thing to do is to pass the DataContext into your method.</p> <p>However, you may also consider changing your design so that you follow the rule that "a single method should have only one purpose", in which case you wouldn't want to "Save" in the same method that you "Modify".</p>
34,871
<p>Does anyone know if there is an implementation of <code>javax.jms.QueueConnectionFactory</code> for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.</p>
<p>I think you need three jars</p> <pre><code>com.ibm.mq.jar com.ibm.mqbind.jar com.ibm.mqjms.jar </code></pre> <p>You instantiate a <em>MQQueueConnectionFactory</em> and i hope you can take it from there.</p> <p>And here's more info: <a href="http://www.ibm.com/developerworks/websphere/techjournal/0502_woolf/0502_woolf.html" rel="noreferrer">IBMs HOWTO</a></p> <p>Oh, and MQ can do "real" JMS instead of MQ - only the JMS implementation seemed to have problems closing the Channel properly - at least in our environment.</p>
<p>Although Bobby's article referenced in the other response is good, I would want to use a more current version of the JMS classes than from 2005! Most of the development has been in enhancing JMS function and performance. The classes have been simplified and repackaged into fewer jars as well so it's easier to deploy.</p> <p>I'd recommend going to the WMQ Infocenter for the version of JMS classes you have (6.0 or 7.0) and looking for the Using Java manual. Inside there is a section on environment variables. Make sure you have the jars listed in the CLASSPATH for your specific version. The infocenter is linked from the <a href="http://www-01.ibm.com/software/integration/wmq/library/" rel="nofollow noreferrer">WMQ Library</a> page.</p> <p>If you can use the latest version, download the <a href="http://www-01.ibm.com/support/docview.wss?rs=171&amp;uid=swg24019253&amp;loc=en_US&amp;cs=utf-8&amp;lang=en" rel="nofollow noreferrer">MQC7 SupportPac</a>. This is the WMQ client code and includes the latest jars.</p> <p>Once you get the client installed, the sample code can be found in C:\Program Files\IBM\WebSphere MQ\tools\jms\samples\simple</p>
35,996
<p>on KDE, there's a possibility to execute a command when some event happen. for example one can execute a script when kmail receives a mail or when a akregator fetches a new feed.</p> <p>I want to execute the script on a way I can retrieve the mail/feed subject in my script. is there a possibility to specify the program to execute:</p> <pre><code>myprogram &lt;SUBJECT&gt; ? </code></pre> <p>possibly specify it as an argument or an environment variable.</p>
<p>With my <a href="http://pd.acm.org/" rel="noreferrer">ACM membership</a>, I get access to both Safari and Books24x7 (this includes Apress).</p> <p>The selection is reduced from the total offering of those sites (600 in Safari only available to professional members and 500 in Books24x7 available to both student and professional members), but I find it's well worth the ACM annual membership, especially when you factor in the other benefits.</p> <p>There is a discount for first year members: <a href="http://learnmore.acm.org/joinacm5.html" rel="noreferrer">http://learnmore.acm.org/joinacm5.html</a></p> <p>Our local library (<a href="http://nutrias.org" rel="noreferrer">nutrias.org</a>) does have ebooks for free also, but I haven't looked to see if they have technical books. In addition, they are term-limited with DRM (yuk).</p>
<p>Here in Santa Clara county, California, we can access the library e-resources, including Safari, from the library's website.</p>
21,639
<p>I have a const char arr[] parameter that I am trying to iterate over,</p> <pre><code>char *ptr; for (ptr= arr; *ptr!= '\0'; ptr++) /* some code*/ </code></pre> <p>I get an error: assignment discards qualifiers from pointer target type</p> <p>Are const char [] handled differently than non-const?</p>
<p>Switch the declaration of *ptr to be.</p> <pre><code>const char* ptr; </code></pre> <p>The problem is you are essentially assigning a const char* to a char*. This is a violation of const since you're going from a const to a non-const. </p>
<p>The const declaration grabs whatever is to the left. If there is nothing it looks right.</p>
32,117
<p>In my specific case, I have two kinds of "messages" that I need to retrive and paginate.</p> <p>Let's omit the details, and just say that the first kind is in a model called Msg1 and the other is called Msg2</p> <p>The fields of these two models are completely different, the only fields that are common to the two models are "date" and "title" (and of course, id).</p> <p>I can get <code>Msg1.objects.all()</code> and <code>Msg2.objects.all()</code> but can I combine these two queries into one query, sort it by date, and paginate it?</p> <p>I need to preserve the lazy nature of the query.</p> <p>The trivial solution is to <code>list(query)</code> both queries and combine them in a python list. but this is inefficient for obvious reasons.</p> <p>I looked through the django references on models and dp-api, but it doesn't seem that there is a way to combine queries of different models/tables into one.</p>
<p>I would suggest that you use <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id4" rel="noreferrer">Model inheritance</a>. </p> <p>Create a base model that contains date and title. Subclass Msg1 and Msg2 off it as described. Do all your queries (to fill a page) using the base model and then switch to the derived type at the last moment. </p> <p>The really great thing about inheritance is that django then allows you to use the base model in foreign keys from other models, so you can make your whole application more flexible. Under the hood it is just a table for the base model with a table per sub-model containing one-to-one keys.</p>
<p>"combine these two queries into one query, sort it by date, and paginate it?"</p> <ol> <li><p>That's the SQL union. Leave the Django ORM and use a SQL union. It's not brilliantly fast because SQL has to create a temporary result, which it sorts.</p></li> <li><p>Create the temporary result, which can be sorted. Since a list has a sort method, you'll have to merge the two results into one list.</p></li> <li><p>Write a merge algorithm that accepts two query sets, paginating the results.</p></li> </ol> <hr> <p>Edit. Here's a merge algorithm.</p> <pre><code>def merge( qs1, qs2 ): iqs1= iter(qs1) iqs2= iter(qs2) k1= iqs1.next() k2= iqs2.next() k1_data, k2_data = True, True while k1_data or k2_data: if not k2_data: yield k1 try: k1= iqs1.next() except StopIteration: k1_data= False elif not k1_data: yield k2 try: k2= iqs2.next() except StopIteration: k2_data= False elif k1.key &lt;= k2.key: yield k1 try: k1= iqs1.next() except StopIteration: k1_data= False elif k2.key &lt; k1.key: # or define __cmp__. yield k2 try: k2= iqs2.next() except StopIteration: k2_data= False else: raise Exception( "Wow..." ) </code></pre> <p>You can fold in pagination:</p> <pre><code>def paginate( qs1, qs2, start=0, size=20 ): count= 0 for row in merge( qs1, qs2 ): if start &lt;= count &lt; start+size: yield row count += 1 if count == start+size: break </code></pre>
40,365
<p>Suppose you have several applications which share the same code and most of the other resources, but have a somewhat different look and feel, some labels change, etc. (think branding). If each web app is to go in its own WAR file, where do you put the shared resources?</p> <p>I already use the classpath to share classes and property files. But what about javascript and css files? Is the best way to create and deploy one extra WAR file that will serve these shared files to whatever other application requires them?</p> <p>I also thought of a build script that does some magic and from a common source spews out the (slightly) different WARs, but I don't like it because it just complicates stuff unnecessarily when you need to build/test/run a single application.</p> <p>Any other tips and tricks would be appreciated.</p>
<p>You can deploy both WARs in the same EAR and put common resources in the EAR. Then put the appropriate dependencies in the manifest of the web apps to link to the jar files in the ear.</p>
<p>Thanks for the replies so far, but I'm afraid I forgot to mention that the WARs will be deployed in different environments that are completely isolated from each other.</p> <p>So maybe having a common WAR deployed next to the actual application is the only option. I think I'll go with the following:</p> <ul> <li>WAR1, WAR2 containing app-specific stuff</li> <li>CommonWAR containg common stuff (no kidding)</li> <li>EAR1: WAR1 + CommonWAR, to be deployed in env1</li> <li>EAR2: WAR2 + CommonWAR, to be deployed in env2</li> </ul>
43,364
<p>I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.</p> <p>Is there a way to make it so these changes are available for undo/redo?</p>
<p>Here's just some code I decided to mess around with:</p> <pre><code> string buffer = String.Empty; string buffer2 = String.Empty; public Form3() { InitializeComponent(); this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown); this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged); } void richTextBox1_TextChanged(object sender, EventArgs e) { buffer2 = buffer; buffer = richTextBox1.Text; } void richTextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control &amp;&amp; e.KeyCode == Keys.Z) { this.richTextBox1.Text = buffer2; } } private void button1_Click(object sender, EventArgs e) { richTextBox1.Text = "Changed"; } </code></pre> <p>It's basically me writing my own Undo feature. All I'm doing is storing the old value in one buffer variable, and the new value in a second buffer variable. Every time the text changes, these values get update. Then, if the user hits "CTRL-Z" it replaces the text with the old value. Hack? A little. But, it works for the most part.</p>
<p>Instead of replacing the text, you need to replace the selected text:</p> <pre><code>richTextBox.SelectAll(); richTextBox.SelectedText = NewText; </code></pre> <p>This was however tested with a current version of winforms, which has the same issue.</p>
34,725
<p>Can you think of a preferably cheap solution for me? I need a machine that pumps air out of my 3d printing enclosure, about 4 meters of pipe length. (From enclosure to window) What kind of pump or fan can pump air out of the enclosure (4m pipe length) at the lowest possible price and low volume?</p> <p>I need it for cooling purposes and for better general air quality in my room after opening the printer enclosure.</p> <p>It doesn't need to be top notch equipment, just enough for my purposes.</p>
<p>Air flows from places of higher pressure to those of less.</p> <h2>Minimal setup</h2> <p>I propose to look at a very simple setup which works for short lengths of pipe:</p> <ul> <li>Choose if you want a radial fan of a direct passing fan. get one, measure the intake and the outlet side holes</li> <li>cut a fan inlet-sized hole directly into the back of the enclosure.</li> <li>mount your fan onto it, most likely with some kind of foam to keep the airstream in.</li> <li>get a flexible air vent hose (I have seen ~$10/10€ for a 100mm one) and measure the inner diameter.</li> <li>print an adapter from the fan outlet to the vent hose.</li> <li>mount the adapter, then the hose, use clamps to secure it.</li> <li>lead the air vent hose to the window and out or into a wall through.</li> </ul> <p>Even if the airstream doesn't seem to be very fast, you could test it with smoke to see that it will blow out the air on the other end of the hose. The large diameter lets quite some air out with just a &quot;gentle&quot; airstream. This is not a very efficient system though, as we build up a pressure in the pipe the fan wors against.</p> <h2>efficiency gains</h2> <p>To gain efficiency, we should move the fan away from the machine and closer to the outlet. That means, we need to increase the fan power. If you can get your hand on, for example, an in-pipe motor, that would be a solution, but usually an expensive one. If you are good with electrics, you could use a blower from an electric cloths-drier. You might get a clothes-drier to strip the motor from really cheap, for example from a renovation, recycling facility or <a href="https://craigslist.org/" rel="nofollow noreferrer">Craigslist</a>, e-bay or any other auction or classifieds-page.</p> <p>Or you build your own from an electric motor (you could use your machine's power supply here), a housing made from wood and an impeller, which you can get as a &quot;Dryer Blower Wheel&quot; spare part for under $50. If you connect the power for its motor through a regulatable resistor, you could even control its spinning speed.</p> <p>To cope with the suction, we need to use aluminium flex pipe on the arm between machine and exhaust.</p> <h2>go big</h2> <p>If you want to go <em>industrial</em> like if you want to run a laser cutter, you will need to go industrial in the vent size too. You use pretty much the same diameter aluminium flex pipe and a much stronger motor than the drier one, and you don't mount the motor directly to the machine back but somewhere downstream as it's rather loud. For what to look for in that case, I found a very good article <a href="https://www.engraversjournal.com/article.php/2780/index.html" rel="nofollow noreferrer">here</a>. Note though, that this is not a small setup, but you could possibly vent a whole batch of printers through one pump, using some airstream cutoffs to control which ones get currently evacuated.</p>
<p>Well you can get a centrifugal fan and put it at either end of the pipe. You didn't specify a pipe diameter so I'll assume it's 1 inch. Just hook the pipe up to the exhaust. You will have to design and print an adapter.</p> <p><a href="https://i.stack.imgur.com/bHByf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bHByf.jpg" alt="enter image description here"></a></p>
1,253
<p>We use MKS Integrity for our source control. I have no control over that -- I just have to use it. </p> <p>What are some "gotchas" that I should know about and avoid? And, are there any neat things about the software that will allow me to use it better?</p> <p>I've already hit cases where the tree structure in the source control doesn't match that in my sandbox. In more than one case, a file exists in two places, and when I resynchronize, I get the current version, and then an older version overwrites it, and then it is no longer synchronized. It's a challenge to find the older file, since, of course, the tree structure doesn't match.</p>
<p>I have used Source Control since 1999. It's pretty reliable, we have never lost change history. We don't do anything fancy with branches so I can't answer your question.</p> <p>I assume you did resynchronize (F6) and update to head (F7).</p> <p>SI is built upon a command-line design. You might have more consistent results if you use the command-line versions (pj.exe etc). The documentation is not trivial.</p> <p>We're trying to migrate to Subversion, because MKS want ridiculous money for their latest enterprisey version.</p>
<p>I have used Source Control since 1999. It's pretty reliable, we have never lost change history. We don't do anything fancy with branches so I can't answer your question.</p> <p>I assume you did resynchronize (F6) and update to head (F7).</p> <p>SI is built upon a command-line design. You might have more consistent results if you use the command-line versions (pj.exe etc). The documentation is not trivial.</p> <p>We're trying to migrate to Subversion, because MKS want ridiculous money for their latest enterprisey version.</p>
45,749
<p>I am trying to localize a desktop app (C#) in VS2008.</p> <p>I have mastered localizing the forms for multiple languages and I also have a project resource file for general strings but I cannot fathom out how to create multiple language versions of this file! </p> <p>It doesn't seem to be documented anywhere. </p> <p>The consequence seems to be that if I want to produce, say, a German version of my application I have to edit the general resource file (Properties/Resources.resx), build and deploy the application, then re-edit the general resource file back to English. </p> <p>Every time I want to produce a new German version I would have to do the same. This seems so clunky compared to the tools for localising forms that I am sure there is a better way in VS2008. Does anyone know what it is?</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms165653.aspx" rel="nofollow noreferrer">Satellite Resource DLLs</a> (note: I've only used them in C++).<BR> This is a system where you can have a different resource DLL for each language that you want to support. There will be no more resources inside the application (at least none that might have to be localized), so the translation team will only have to make translations of the resource DLL into the appropriate languages.</p>
<p>Actually Visual Studio has this built in. On your form you wish to localize for a language change the property Localizable to true.</p> <p>Then change the Language property to the language you wish to set up a resource file for. In your case, choose German.</p> <p>Change all the text on the form to the German text. This will create an additional resx file for each language you change the Language Property too.</p> <p>Once you finish you can change to another language for another translated form resource file or switch back to default.</p> <p>Now when the computer is run on a machine set up to use a different language it will look for a resx file to match and switch all the controls to use the text provided in the resource file.</p> <p>You can also test this by changing the CurrentUICulture on the CurrentThread</p> <p>Here is a nice walk-through on MSDN as well:<br> <a href="http://msdn.microsoft.com/en-us/library/y99d1cd3(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/y99d1cd3(VS.80).aspx</a></p>
46,361
<p>One of the few annoying things about the Eclipse Java plug-in is the absence of a keyboard shortcut to build the project associated with the current resource. Anyone know how to go about it?</p>
<p>In the Preferences dialog box, under the General section is a dialog box called "Keys". This lets you attach key bindings to many events, including Build Project.</p>
<p>I believe <kbd>Ctrl</kbd>+<kbd>B</kbd> is already configured for this by default. Just need to have an edit window with focus.</p>
20,335
<p>If I'm deploying to servers with WebSphere 6.1 (Java 1.5), should I use IBM's JDK on my build box? Or will Sun's JDK compile to the same binary?</p> <p>If I should use IBM's, where can I get the Windows x64 version?</p>
<p>I would as much as possible try to keep development as close to production as possible. Ibm and Sun's JDK's certainly both satisfy the SDK certification, but they are by no means identical. Their instrumentation and memory management are at least slightly different. If nothing else, the bugs in the JDK will be different, which your code may only trip over in one scenario vs. another. It'll also probably only happen at 4 am, and when the moon is full especially when you have company over.</p> <p>I can't tell you where to get IBM's jdk, but if you've got a license to websphere at your company, you should have a contact at IBM to get you a link to that JDK.</p> <p>Good luck, and always try to minimize differences where possible.</p>
<p>They should compile to the same bytecode specification, although they may compile different bytecode (much as in the same way different C compilers generate different machine code). I don't think there would be any problems in running the resulting code - I've compiled Java 1.4 on a Mac and then deployed to IBM's J9 running on a PocketPC before with no problems (this was before J9 could handle Java 5 bytecode).</p> <p>Regardless, I'd definitely make your compilation platform a bullet point on your readme file so that your client can see if it is a problem.</p> <p>Alternatively, you could build and deploy with ANT, and use Sun's JDK with ANT.</p>
14,047
<p>I purchased two DQ542MA drivers in order to run two NEMA 17 steppers. After about five days of use I noticed that the green indicator light had gone out on both drivers. </p> <p>The DQ542MA driver running my NEMA 23 High Torque stepper was still running and it has been connected to that stepper for five months now. Using an Ohm meter to check I found that the <a href="https://www.mouser.com/ProductDetail/Littelfuse/0451010MRL?qs=sGAEpiMZZMtxU2g%2F1juGqdRmCQF0%252bT4VCAcmqQZMjh4%3D" rel="nofollow noreferrer">10amp 125v</a> LittleFuse connected to the power pins had blown on both drivers connected to the NEMA 17 steppers cutting off the power. </p> <p>I decided to test the still working driver by disconnecting it from the NEMA 23 stepper and corresponding pins on the motherboard and connecting and resetting it to work with one of the NEMA 17 steppers. The minute I turned my printer back on, the still working stepper (now attached to the NEMA 17 stepper) immediately blew the same fuse. I don't understand why the NEMA 17 steppers blew the fuses of the drivers, seeing as how both are properly set to a RMS of 1.69 and a pulse/rev of 400, and both are connected to a 24v PSU. </p> <p><strong>My question is:</strong> "When I fix the drivers should I solder in a <a href="https://www.mouser.com/ProductDetail/Littelfuse/0476015MRSN?qs=sGAEpiMZZMtxU2g%2F1juGqTi%252bNtKN7qu4p8sgPytjpHvp9IQs9yJn3A%3D%3D" rel="nofollow noreferrer">15amp 125v</a> LittleFuse to better help the power flow and prevent any further blown fuses?"</p>
<p>There are a lot of problems with the CH340 chipset drivers to be found on 3D SE and various forums on the internet. To use this cheap CH340 chip that is used by a number of Arduino compatible (clone) boards to provide USB connectivity (a USB bus converter chip that converts USB bus signals to serial interface) you need to install a correct working driver. </p> <p>For Mac OS X you can try to download a working version for the OS system you are using. You can try to use <a href="https://blog.sengotta.net/signed-mac-os-driver-for-winchiphead-ch340-serial-bridge/" rel="nofollow noreferrer">this driver installer</a> or <a href="https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver" rel="nofollow noreferrer">this driver installer</a>. Both reported to work with Mac OS.</p> <hr> <p><strong>Edit</strong>: If you are using OSX El Capitan, please read <a href="https://www.kiwi-electronics.nl/blog?journal_blog_post_id=7&amp;lang=en" rel="nofollow noreferrer">this</a>. To get the CH340 drivers to work you need to use the tool <strong>csrutil</strong>.</p> <blockquote> <ul> <li>Reboot and press CMD+R immediately after hearing the startup sound to boot to Recovery Mode</li> <li>Open Terminal</li> <li>Execute the following command: <code>csrutil enable --without kext</code></li> <li>Reboot</li> </ul> </blockquote> <p>More information is found <a href="https://tzapu.com/making-ch340-ch341-serial-adapters-work-under-el-capitan-os-x/" rel="nofollow noreferrer">here</a>!</p>
<p>What Cura version do you have? Cura only works with the Anet A8 via USB on versions 2.3 and lower according to this <a href="https://www.thingiverse.com/groups/anet-a8-prusa-i3/forums/general/topic:12212" rel="nofollow noreferrer">page</a>. The page is from thingiverse(A 3d printing forum + print files page)</p>
940
<p>I have been trying to change the background color of Eclipse's windows to black and customize the font colors. There doesn't seem to be a way to do this, at least not in an obvious way. I am using version 3.3.</p> <p>How do I do this or are there any plugin's that might be able to assist in doing this?</p>
<h3>To change background colour</h3> <ol> <li>Open menu *Windows → <em>Preferences</em> → <em>General</em> → <em>Editors</em> → <em>Text Editors</em> <ul> <li>Browse Appearance color options</li> <li>Select background color options, uncheck default, change to black</li> <li>Select background color options, uncheck default, change to colour of choice</li> </ul></li> </ol> <h3>To change text colours</h3> <ol> <li>Open <em>Java</em> → <em>Editor</em> → <em>Syntax Colouring</em> <ul> <li>Select element from Java</li> <li>Change colour</li> <li>List item</li> </ul></li> </ol> <h3>To change Java editor font</h3> <ol> <li>Open menu <em>Windows</em> → <em>Preferences</em> → <em>General</em> → <em>Appearance</em> → <em>Colors and Fonts</em> <ul> <li>Select <em>Java</em> → <em>Java Editor Text font</em> from list</li> <li>Click on change and select font</li> </ul></li> </ol>
<p>On Windows or Mac, you can find this setting under the <em>General</em> → <em>Editors</em> → <em>Text Editors</em> menu.</p>
22,521
<p>I launch a child process in Java as follows:</p> <pre><code>final String[] cmd = {"&lt;childProcessName&gt;"}; Process process = Runtime.getRuntime().exec(cmd); </code></pre> <p>It now runs in the background. All good and fine. </p> <p>If my program now crashes (it <em>is</em> still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies?</p> <p>If it helps, I'm using Mac OS X 10.5</p>
<p>As you said, <a href="https://web.archive.org/web/20080310051714/http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2" rel="nofollow noreferrer">addShutdownHook</a> is the way to go.</p> <p>BUT:</p> <ul> <li><p>There's no real guarantee that your shutdown hooks are executed if the program terminates. Someone could kill the Java process and in that case your shutdown hook will not be executed. (as said in this <a href="https://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully">SO question</a>)</p> </li> <li><p>some of the standard libraries have their own hooks which may run before yours.</p> </li> <li><p>beware of deadlocks.</p> </li> </ul> <p>Another possibility would be to <a href="http://wrapper.tanukisoftware.org/doc/english/index.html" rel="nofollow noreferrer">wrap your java program in a service</a>.</p>
<p>Adding shutdown hook is not a reliable method to kill the child processes. This is because Shutdown hook might not necessarily be executed when a force kill is performed from Task Manager.</p> <p>One approach would be that the child process can periodically monitor the PID of its parent. This way, Child process can exit itself when the parent exits.</p>
32,646
<p>Our clients use a vb6 version of our software.</p> <p>We are upgrading them to a .NET application written in C#...</p> <p>Is there less bulk using .net 2.0 than .net 3.5?</p> <p>My definition of less bulk would be: Smaller size, smaller installation time, etc.</p> <p>Most of them probably already have 2.0 anyway.</p> <p>I only ask because I would like to take advantage of LINQ in 3.5.</p>
<p>For taking advantage of LINQ, you need 3.5 (unless you want to use <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow noreferrer">LINQBridge</a> with 2.0).</p> <p>For a smaller installer, .Net 3.5 <strong>Sp1</strong> has a new feature called "<a href="http://weblogs.asp.net/scottgu/archive/2008/05/12/visual-studio-2008-and-net-framework-3-5-service-pack-1-beta.aspx" rel="nofollow noreferrer">Client Profile</a>".</p> <p>The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios. For example: it includes Windows Forms, WPF, and WCF. It does not include ASP.NET and those libraries and components used primarily for server scenarios. We expect this setup package to be about <strong>26MB</strong> in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package.</p>
<p>I would suggest that you go straight with visual studio 2008 and .net 3.5 sp1, 2.0 is the basis of 3.5 and you can easily start using 2.0 and then start to use 3.5 functionalities.</p> <p>Furthermore 3.5 SP1 also brings tweaks to the 2.0 framework which are nice to have.</p>
26,958
<p>I've got 2 monitors, and most of the time I've got some reference material open on one screen, and Visual Studio on the other. To really get in the zone, though, I need my code to be the only thing I see. Does anyone know if it's possible to have multiple code windows in Visual Studio? So far the best I can do is put debugger output and the solution explorer on my left monitor, and the rest of VS on the right. I would love to have code on both windows, however.</p>
<p>If you right click on the file tabs, there's an option for "New Vertical Tab group" Just maximize across both monitors and put the divider on the monitor divide and I think that's what you're after.</p>
<p>Instead of enlarging the VS2008 window to span the two monitors, you can display the 'Code Definition Window' on another monitor: just drag it outside the main window! I find this very handy to avoid switching between code windows: it is very often that one is interested in the definition of the symbol under the cursor...</p> <p>The same is true for other windows like the 'Class View', the 'Call Browser', etc. You can choose to keep them grouped in the same group with tabs, or drag each of them separately (click on the label of the tab to start the drag).</p>
12,721
<p>I created a windows service that's basically a file watcher that wont run unless a user is logged into the machine its on. The service is running on a Windows Server 2003 machine. It is designed to move the files that are put into one directory into a different directory based on keywords in the file names, but none of the files move until i log on, then all the files move at once.</p>
<p>You probably have to set the service to log on as a spesific user, try going into services, doubleclick the service and select "log in as account", and then provide your account details (domain\username and password).</p> <p>The LocalService account has extensive rights, but may lack the rights to spesific users files/folders for instance. You could alternatively try to grant file rights to the LocalService account spesifically. I would however try the "log in as" trick first, as it's a 1 minute job. If it works you could create a spesific account to run the service as, alternatively grant rights to LocalSystem.</p> <p>Btw: If it's networked files you might try the NetworkedService account.</p>
<p>There has to be some setup problem with your service. Windows Server doesn't have a problem running applications without a user logged in (otherwise, scheduled tasks would be a lot less useful).</p> <p>How did you <em>install</em> the service?</p>
46,869
<p>I have just imported a WAR file from an external site, which is basically a servlet into Eclipse IDE (the project runs on Apache-Tomcat). </p> <p>When I import it it has a folder called <strong>Web App Libraries</strong>. So here are a few of my newbie questions:</p> <ol> <li><p>I am unsure about what the exact purpose is of this folder is? What does it do, why would you choose to have it in your project? </p></li> <li><p>I see that it has a folder called <strong>Improted Classes</strong> and foobar.class files inside it - why?<br> <em>(These seemed to be mirrored in <strong>Web Content</strong> folder - although here you can modify the code as they are foobar.java.)</em></p></li> <li><p>There are references to foobar.jar files too - these are also mirrored in <strong>WEB-INF/lib</strong> folder too - why?</p></li> </ol> <p>I know these are basic type questions but I'm just getting to grips with Java and website dev, so apologies if they sound a bit dumb! - BTW if anyone knows any good online resource to understand more about project file structures like this, then let me know. I just need to get to grips with this stuff asap - as the project deadline is fairly soon.</p> <p>Cheers.</p> <p>Here's a screenshot just to help you visualise:</p> <p><img src="https://rantincsharp.files.wordpress.com/2008/12/eclipserestlet.gif" alt="alt text"></p>
<p>I assume this is a screenshot from the 'Project Explorer' view. It does not display exact folders and files structure, is adds a few candy constructed from project's metadata.</p> <ul> <li>To see real structure of your project, try switching to the 'Navigator' view.</li> <li>During a WAR file import, Eclipse basically does two things: <ul> <li>Creates a new web project and copies WAR's content to 'WebContent' subfolder of the new project.</li> <li>Based on the WAR, it constructs project's metadata (.project and .classpath files).</li> </ul></li> <li>The 'Web App Libraries' section displays list of jar files that the WAR contained (in WEB-INF/lib</li> <li>'Imported classes' (which I also see for a first time) seem to contain classes found in the imported WAR (WEB-INF/classes), for which Eclipse was not able to find any corresponding source files. To fix this, create a new Java source folder in the project and move the classes you now have in 'firstResource' folder to it. </li> </ul>
<p>Its simple, eclipse provides multiple view to your project structure. The view you are looking at is definitely the Package Explorer view. In that view, everything that has a special icon in front is a helper item which is there to help you out by simplifying access to certain stuff like external libraries (which are provided by software on your computer or eclipse itself or other project).</p> <p>In eclipse, go to menu->window->show view->navigator The Navigator view will tell you the real folder structure of your project.</p>
45,546
<p>Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?</p>
<p>Here's a nice fun LINQ example.</p> <pre><code>public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x =&gt; x % 2 == 0) .Select(x =&gt; Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } </code></pre>
<p>I think this may work.</p> <pre><code>public static byte[] StrToByteArray(string str) { Dictionary&lt;string, byte&gt; hexindex = new Dictionary&lt;string, byte&gt;(); for (int i = 0; i &lt;= 255; i++) hexindex.Add(i.ToString("X2"), (byte)i); List&lt;byte&gt; hexres = new List&lt;byte&gt;(); for (int i = 0; i &lt; str.Length; i += 2) hexres.Add(hexindex[str.Substring(i, 2)]); return hexres.ToArray(); } </code></pre>
41,591
<p>I'm trying to use the Kowalski graph algorithm for resolution theorem proving. The description of the algorithm at <a href="http://www.doc.ic.ac.uk/~rak/" rel="nofollow noreferrer">http://www.doc.ic.ac.uk/~rak/</a> is silent on what to do about the large number of duplicate clauses it generates. I'm wondering if there's a well-known technique for dealing with them?</p> <p>In particular, you can't simply suppress the generation of duplicate clauses, because the links that come with them are relevant.</p> <p>It seems to me that it's probably necessary to track the set of all clauses generated thus far, and when a duplicate is generated, add the new links to the existing instance instead. This probably needs to be maintained even when a clause is nominally deleted, for when it is regenerated.</p> <p>Duplication probably needs to be defined in terms of textual representation, rather than object equality, because literals of different clauses are distinct objects even when they are identical.</p> <p>Can anyone confirm whether I'm on the right track here? Also, the only significant online reference I could find to this algorithm was the link above, does anyone know of any others, or any existing code implementing it?</p>
<p>Is the list of types fixed or does it change?</p> <p>If fixed, I would encapsulate it in an enum:</p> <pre><code>public enum FilmType { Horror = 1, Comedy = 2 } </code></pre> <p>Then just cast. You can use attributes (and a few lines of bespoke code) to store an extra description per enum item.</p> <p>If the list changes I would probably read it once early on in the app, and cache the list in a lookup somewhere (perhaps static, perhaps in a specific cache). Then just do the lookups from the cached copy.</p> <p>You can take this further by adding properties that change between the two representations.</p>
<p>I always store my code look ups inside Enumeration files similar to this</p> <pre><code>public enum ReportStatus { [Description("Reports that are running")] Running, [Description("Reports that are pending to run")] Pending, [Description("Reports that have errored while running")] Error, [Description("Report completed successfully.")] Finished } </code></pre> <p>To read from the Description tags of the enum I use a class simliar to this example from <a href="http://monstersgotmy.net/post/Enumerations-and-Strings-Stop-the-Madness!.aspx" rel="nofollow noreferrer">Monsters Got My .NET</a>. This leaves you with the flexibility to store the ID, Code and Description of a look up type object in an enum at the same time.</p>
47,538
<p>I'm trying to grab an image from a web site using simpleXML and am getting a PHP error saying that I'm trying to call to a member function <code>xpath()</code> on a non-object.</p> <p>Below are the lines I'm trying to use to get the image's source tag: </p> <pre><code>$xpath = '/html/body/div/div/div[5]/div/div/div[2]/div/div[2]/img'; $html = new DOMDocument(); @$html-&gt;loadHTMLFile($target_URL); $xml = simplexml_import_dom($html); $source_image = $xml-&gt;xpath($xpath); $source_image = $source_image[0]['src']; </code></pre> <p>What am I doing wrong? It's pretty clear the second to last line has a problem, but I'm not sure what it is.</p>
<p>Try this code to first make sure that the document is being parsed correctly.</p> <pre><code>$xpath = '/html/body/div/div/div[5]/div/div/div[2]/div/div[2]/img'; $html = new DOMDocument(); @$html-&gt;loadHTMLFile($target_URL); $xml = simplexml_import_dom($html); if (!$xml) { echo 'Error while parsing the document'; exit; } $source_image = $xml-&gt;xpath($xpath); $source_image = $source_image[0]['src']; </code></pre>
<p>Problem solved. Was funning xpath on an empty string.</p>
45,835
<p>I have a method which takes params object[] such as:</p> <pre><code>void Foo(params object[] items) { Console.WriteLine(items[0]); } </code></pre> <p>When I pass two object arrays to this method, it works fine:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[] </code></pre> <p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[] </code></pre> <p>How do I pass a single object[] as a first argument to a params array?</p>
<p>A simple typecast will ensure the compiler knows what you mean in this case.</p> <pre><code>Foo((object)new object[]{ (object)"1", (object)"2" })); </code></pre> <p>As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.</p>
<p>One option is you can wrap it into another array:</p> <pre><code>Foo(new object[]{ new object[]{ (object)"1", (object)"2" } }); </code></pre> <p>Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:</p> <pre><code>Foo((object) new object[]{ (object)"1", (object)"2" }); </code></pre> <p>Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:</p> <pre><code>void Foo(object[] item) { // Somehow don't duplicate Foo(object[]) and // Foo(params object[]) without making an infinite // recursive call... maybe something like // FooImpl(params object[] items) and then this // could invoke it via: // FooImpl(new object[] { item }); } </code></pre>
5,701
<p>Could someone please explain? I couldn't find anything on the internet, everything talks about how to go about it in some way, but nothing says exactly what it is. </p> <p>Also, what is a fully trusted assembly and how do they differ from one another?</p> <p>I have a MS certification exam and this is the only topic that I just don't understand.</p> <p>EDIT: Thanks guys. Now I have a better understanding of security in .NET. I was able to pass my certification exam.</p>
<p>A <a href="http://blogs.msdn.com/eugene_bobukh/archive/2005/05/06/415217.aspx" rel="nofollow noreferrer">full-trust assembly</a> has an unrestricted set of <a href="http://msdn.microsoft.com/en-us/library/930b76w0.aspx" rel="nofollow noreferrer">code access security</a> permissions, which allows the code to access all resource types and perform privileged operations, subject only to operating system security. For example, if user Bob cannot access file Y, then neither can a full-trust assembly running in Bob's user space. </p> <p>A <a href="http://msdn.microsoft.com/en-us/library/ms364059(VS.80).aspx" rel="nofollow noreferrer">partial-trust assembly</a> means that the code runs at less than full trust. The .NET Framework has several predefined <a href="http://codebetter.com/jeffreypalermo/2005/07/05/asp-net-trust-levels-demystified-level-300" rel="nofollow noreferrer">trust levels</a> that you can use directly or customise to meet your specific security requirements. For example, you can prevent an assembly from accessing SQL databases by denying SQLClientPermission.</p> <p>The trust level of an assembly can also be diminished by its origin. For example, code coming from a network share (in older versions of .NET) is trusted less than code coming from the local computer, and as a result is limited in its ability to perform privileged operations. </p>
<p>Maybe some context will help.</p> <p>Think about something like browsing stackoverflow. There is the code off the browser itself that can do anything on your computer (delete files for example ) and there is the javascript code of the site. The javascript code can't do anything to your computer except the nifty fade effects and some other display magic.</p> <p>.net has the ability to provide such distinction between local application and remote ones. You can write application that will run on the local computer and will be able to do anything to the local computer. And this application can have a feature that download extension dll from the internet. Those extension will be able to do calculation and manipulate the display. But the code inside them want be able to delete files. Because it is not trusted.</p> <p>The details are wrong but this is the idea ( as far as i understand it).</p>
49,212
<p>Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?</p> <p>Here's the recursive solution for reference:</p> <pre><code>class Node &lt; ActiveRecord::Base has_many :products def json_hash if children.size &gt; 0 children.collect { |node| { node.name =&gt; node.json_hash }.to_json else { node.name =&gt; node.products.find(:all).collect(&amp;:name) }.to_json end end end </code></pre>
<p>There is a <a href="http://en.wikipedia.org/wiki/Tree_traversal" rel="nofollow noreferrer">wikipedia article</a> on tree traversal which shows different alternatives to the recursive solution you are using. It may be tricky to use them in your specific case, but it should be possible.</p> <p>However, my question to you is, is there a specific reason you want to use iteration instead of recursion? I don't think any of the iterative solutions will be nearly as clean. Are your trees so big that you are running out of stack space (they would have to be pretty big)? Otherwise, I'm not so sure an iterative solution will really be faster.</p> <p>I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate:</p> <p>Does the find method return a new array? If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there.</p> <p>So </p> <pre><code>{ node.name =&gt; node.products.find(:all).collect(&amp;:name) }.to_json </code></pre> <p>might become</p> <pre><code>{ node.name =&gt; node.products.find(:all).collect!(&amp;:name) }.to_json </code></pre> <p>EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing.</p> <p>So</p> <pre><code>class Node &lt; ActiveRecord::Base has_many :products def json_hash if children.size &gt; 0 children.collect { |node| { node.name =&gt; node.json_hash }.to_json else { node.name =&gt; node.products.find(:all).collect!(&amp;:name) }.to_json end end end </code></pre> <p>might become</p> <pre><code>class Node &lt; ActiveRecord::Base has_many :products def json_hash to_hash.to_json end def to_hash if children.size &gt; 0 children.collect { |node| { node.name =&gt; node.to_hash } else { node.name =&gt; node.products.find(:all).collect!(&amp;:name) } end end end </code></pre> <p>Whether this works and is more efficient I leave as an exercise for you ;-)</p>
<p>JSONifier!</p> <pre><code>node.to_json(:include=&gt;{:products=&gt;{:include=&gt;:product_parts}}) </code></pre>
6,249
<p>I'm playing with the wonderful <a href="http://hudson.gotdns.com/wiki/display/HUDSON/FindBugs+Plugin" rel="nofollow noreferrer">FindBugs plugin</a> for <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a>. Ideally, I'd like to have the build fail if FindBugs finds any problems. Is this possible?</p> <p>Please, don't try and tell me that "0 warnings" is unrealistic with FindBugs. We've been using FindBugs from Ant for a while and we usually do maintain 0 warnings. We achieve this through the use of general exclude filters and specific/targeted annotations.</p>
<p>Maybe you've already seen this option, but it can at least set your build to unstable when you have greater than X warnings. On your job configuration page, right below the Findbugs results input field where you specify your findbugs file pattern, should be an 'advanced' button. This will expand and give you an "Unstable Threshold" as well as Health Reporting that changes Hudson's weather indicator for the job based on the number of warnings.</p> <p>I wouldn't want my build to fail, but unstable seems reasonable if you are maintaining 0 warnings (and presumably 0 test failures).</p>
<p>You can not rely on find bugs so much , it is just an expert system that tells you that something <strong>may</strong> be wrong with your program during runtime. Personally I have seen a lot of warning generated by findbugs because it was not able to figure out the correctness of code (in fact).</p> <p>One example when you open a stream or jdbc connection in one method and close it in other, in this case findbugs expecting to see close() call in same method which sometimes is impossible to do.</p>
12,660
<p>I have a situation where in a web application a user may need a variable list of PDFs to be printed. That is, given a large list of PDFs, the user may choose an arbitrary subset of that list to print. These PDFs are stored on the file system. I need a method to allow users to print these batches of PDFs relatively easily (thus, asking the user to click each PDF and print is not an option) and without too much of a hit on performance.</p> <p>A couple of options I've thought about:</p> <p>1) I have a colleague who uses a PDF library that I could use to take the PDFs and combine them on the fly and then send that PDF to the user for printing. I don't know if this method will mess up any sort of page numbering. This may be an "ok" method but I worry about the performance hit of this.</p> <p>2) I've thought about creating an ActiveX that I would pass the PDFs off to and let it invoke the printing features. My concern is that this is needlessly complex and may present some odd user interactions.</p> <p>So, I'm looking for the best option to use in this scenario, which is probably not one of the ones I've gone through. </p>
<p>The best solution I have for you is number 1. There are plenty of libraries that will merge documents. From the one I've used the numbering should not be an issue since all the pages are all ready rendered. </p> <p>If you go with ActiveX you are going to limit yourself to IE which might be acceptable. The only other idea would be to use a smart client so you can have more control...then you could serve up the PDF's via a web service. </p>
<p>I agree with #1. You could do some tests to see what the performance hit would be like. </p>
47,621
<p>I want to build an Axis2 client (I'm only accessing a remote web service, I'm <em>not</em> implementing one!) with Maven2 and I don't want to add 21MB of JARs to my project. What do I have to put in my pom.xml to compile the code when I've converted the WSDL with ADB?</p>
<p>(<strong>Note:</strong> This response was provided by Aaron Digulla himself. What follows is the exact text of his own answer.)</p> <p>In maven2, the minimum dependency set to make an ADB client work ("ADB" as in the way you created the Java classes from the WSDL) is this:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-kernel&lt;/artifactId&gt; &lt;version&gt;1.4.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-adb&lt;/artifactId&gt; &lt;version&gt;1.4.1&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Hmmm... it seems I can't flag that as the correct answer. Can someone please copy this so I can flag his post?</p>
<p>For those using <strong>Gradle</strong>, here I exclude unnecessary libraries:</p> <pre><code>dependencies { ext.compileEx = { lib, exModules, exGroups -&gt; compile (lib) { exModules.each { exclude module : "$it" } exGroups.each { exclude group: "$it" } } } List axisExModules = [ 'axiom-compat', 'jaxen', 'apache-mime4j-core' ] List axisExGroups = [ 'javax.servlet', 'commons-fileupload', 'org.apache.woden', 'javax.ws.rs', 'org.apache.geronimo.specs', 'org.codehaus.woodstox' ] compileEx ('org.apache.axis2:axis2-adb:1.6.3', axisExModules, axisExGroups) compileEx ('org.apache.axis2:axis2-transport-local:1.6.3', axisExModules, axisExGroups) compileEx ('org.apache.axis2:axis2-transport-http:1.6.3', axisExModules, axisExGroups) } </code></pre> <p><a href="https://discuss.gradle.org/t/multiple-excludes-for-multiple-dependencies/11573/6?u=ivanrf" rel="nofollow">Here</a> is my original post in the Gradle forums.</p>
41,411
<p>The following code fails to compile stating "A local variable named 'st' cannot be declared in this scope because it would give a different meaning to 'st', which is already used in a 'child' scope to denote something else": </p> <pre><code> var l = new List&lt;string&gt;(); l.Find(st =&gt; st.EndsWith("12")); string st = "why this fails?"; </code></pre> <p>I understand why this won't work:</p> <pre><code> string preParent = ""; { string preParent = "Should fail cause we change the meaning"; } </code></pre> <p>When we do the following we get "CS0103: The name 'postParent' does not exist in the current context":</p> <pre><code> { string postParent=string.Empty; } postParent = "Should this work?"; </code></pre> <p>What I don't get is why is the compiler smart enough to see that postParent is not within scope, but won't let me define a new variable that has the same name as a variable used within a child scope (which is obviously out of scope at this point). </p> <p>Is the compiler simple enforcing scope by refusing to let me use the variable? If so this makes sense.</p> <p>===========</p> <p>Edited: </p> <p>I guess what I also find interesting is how you can have the same variable within two child scopes in a single method, so this is valid:</p> <pre><code> { string thisWorks= string.Empty; } { string thisWorks= "Should this work?"; } </code></pre> <p>I'm just a little curious that you can have two variables with the same name as long as they are at the same level (if you look at scope as a tree). This makes sense because you can have local variables in two methods of the same class with the same name. </p> <p>I'm just surprised that the compiler is able to differentiate and allow this, while it wouldn't allow the postParent variable. And is this a technical limitation or was this a design decision? That's what I'm really trying to get at;-)</p>
<p>Yes, the compiler is enforcing scope. Note that the scope of a variable is the lexical block it's part of - not just from the point of declaration onwards, but the whole scope. </p> <p>The compiler is complaining because the assignment to <code>postParent</code> is outside its scope (which is only the nested braces). If you tried to declare a new variable at the point where you're currently assigning to <code>postParent</code> the problem would be with the nested block, because the scope of <code>postParent</code> would include that nested block, even though it was before the declaration.</p> <p>Scopes are described in section 3.7 of the C# 3.0 specification.</p> <p>EDIT: To respond to your question edit.</p> <p>It's just two simple rules:</p> <ul> <li>you can't declare a local variable when another local variable with the same name is in scope</li> <li>the scope of a local variable is the block in which the declaration occurs</li> </ul> <p>I'm sure the language could have been designed such that the scope only began at the point of declaration, but I think it's simpler (in terms of language complexity) to consider scopes as just blocks - so all local variables declared in the same block have the same scope, for example. That makes life a lot simpler when considering captured variables, too - as what gets captured depends on the scope, and nested scopes make life interesting...</p> <p>EDIT: The language spec has this to say about the original lambda expression example - it's section 7.14.1:</p> <blockquote> <p>The optional anonymous-function-signature of an anonymous function defines the names and optionally the types of the formal parameters for the anonymous function. The scope of the parameters of the anonymous function is the anonymous-function-body. Together with the parameter list (if given), the anonymous-method-body constitutes a declaration space. For this reason, it is a compile-time error for the name of a parameter of the anonymous function to match the name of a local variable, local constant, or parameter whose scope includes the anonymous-method-expression or lambda-expression.</p> </blockquote> <p>Does that help?</p>
<p>You're declaring a variable in a limited scope and trying to use it outside of that scope. The compiler assumes you don’t want access to it so you can declare a variable with the same name somewhere else in the file. Your trying to do the old C trick of assuming the variable will live immediately outside of the scope. For example this used to work in older versions of C/C++ but no longer does.</p> <pre><code>for (int i=0; i&lt;10; i++) { cout &lt;&lt;”In the loop i is “&lt;&lt; i &lt;&lt; endl; } cout &lt;&lt; “outside of the loop i is “ &lt;&lt; i &lt;&lt; endl; //this only compiles with old C/C++ compilers. </code></pre>
37,952
<p>In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.</p> <p>The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.</p> <p>Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?</p>
<p>You can use a file system watcher to check when the file has been changed. It only becomes "changed" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.</p> <p>It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.</p> <pre><code> Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte) Dim FileOpen As Boolean Dim File As System.IO.FileStream = Nothing Dim StartTime As DateTime Dim MaxWaitSeconds As Integer = 120 StartTime = DateTime.Now FileOpen = False Do Try File = New System.IO.FileStream(FilePath &amp; FileName, IO.FileMode.Append) FileOpen = True Catch ex As Exception If DateTime.Now.Subtract(StartTime).TotalSeconds &gt; MaxWaitSeconds Then Throw New Exception("Waited more than " &amp; MaxWaitSeconds &amp; " To Open File.") Else Dim FileWatch As System.IO.FileSystemWatcher FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName) FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000) End If FileOpen = False End Try Loop While Not FileOpen If FileOpen Then File.Write(Data, 0, Data.Length) File.Close() End If End Sub </code></pre>
<p>Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar problems on some recent work I was doing.</p> <p>In short, I was trying to write to a file that was locked at the time. I ended up wrapping the write method up so it would automatically try the write again in a few ms after..</p> <p>Thinking out loud, Can you probe the file for a ReadOnly status? May be worth then having a wrapper for file IO which can stack up delegates for pending file operations or something.. Thoughts?</p>
4,404
<p>At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.</p> <pre><code>Queue&lt;MyData&gt; myDataQueue = new Queue&lt;MyData&gt;(); // Populate the queue here XmlSerializer mySerializer = new XmlSerializer(myDataQueue.GetType()); StreamWriter myWriter = new StreamWriter("myData.xml"); mySerializer.Serialize(myWriter, myDataQueue); myWriter.Close(); </code></pre>
<p>It would be easier (and more appropriate IMO) to serialize the <em>data</em> from the queue - perhaps in a flat array or <code>List&lt;T&gt;</code>. Since <code>Queue&lt;T&gt;</code> implements <code>IEnumerable&lt;T&gt;</code>, you should be able to use:</p> <pre><code>List&lt;T&gt; list = new List&lt;T&gt;(queue); </code></pre>
<p>if you want to use the built in serialization you need to play by its rules, which means default ctor, and public get/set properties for the members you want to serialize (and presumably deserialize ) on the data type you want to serialize (MyData)</p>
39,965
<p>I'd like to commit just a part of a file using TortoiseSVN, is there some way to do that?</p> <p>I'll give an example to make it clearer why I want to do that.</p> <p>I have a file with some defines that are replaced in the build process, something like this:</p> <pre><code>#define SOME_PATH "[SOME_PATH]" </code></pre> <p>This [SOME_PATH] tag is replaced in the build process but when I'm coding I have to change it so the actual path in my machine.</p> <p>So each time I commit I need to backup some lines, revert them, commit and then restore the backup, and this is kinda annoying.</p> <p>Is there some way to tell TortoiseSVN to "ignore" some changes in, say, Lines X,Y and Z?</p>
<p>The top voted answer is out-of-date.</p> <p>From the tortoiseSVN website: <a href="http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-commit.html" rel="noreferrer">http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-commit.html</a></p> <blockquote> <p>Commit only parts of files</p> <p>Sometimes you want to only commit parts of the changes you made to a file. Such a situation usually happens when you're working on something but then an urgent fix needs to be committed, and that fix happens to be in the same file you're working on.</p> <p>right click on the file and use Context Menu → Restore after commit. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.</p> <p>After the commit is done, the copy of the file is restored automatically, and you have the file with all your modifications that were not committed back.</p> </blockquote>
<p>What you are looking for is a feature of various distributed version-control systems such as <a href="http://darcs.net/" rel="nofollow noreferrer">darcs</a>.</p>
40,518
<p>Is there a way or tool for Vista I can use to search for content in Java files? (I do not have an Eclipse project set up for it) </p> <p>I used to be able to do it easily in the windows search tool when I had Windows 2000.</p> <p>Edit: I have already enabled "search file contents" and added additional file types as recommended by xsl and Grant Wagner, the search still returns no results...</p>
<p>Personally, I just use <a href="http://www.baremetalsoft.com/baregrep/" rel="nofollow noreferrer" title="BareGrep">BareGrep</a> (and previously, <a href="http://www.mythicsoft.com/agentransack/" rel="nofollow noreferrer" title="Agent Ransack">Agent Ransack</a>), which is fast, supports regexes and show lines that match.<br> <a href="http://tools.tortoisesvn.net/grepWin" rel="nofollow noreferrer" title="grepWin">grepWin</a> is nice too (can replace strings) but doesn't show lines.</p>
<p>There are tons of search tools. Simplest and smallest is the GNU grep.</p> <p>I personnally use Far (for many things, not just search).</p>
41,118
<p>I have a gradient image as a background for a table header(9x18pix). This image is called through a selector class. When the header content grows to 2 lines(vertical height increases), the bg image is tiling vertically and looks ugly. How can I stretch the bg image vertically without tiling?</p>
<p>You can't stretch it. Well not without some nasty CSS hacks, that will not really work in all available browsers. I wouldn't use them (unless your HTML code only targets a single browser, e.g. if it's a page for internal use and the browser being used is known). You can make it repeat in just one direction, though. This is what you usually want when having a gradient.</p> <pre><code>background-repeat: repeat-x; </code></pre> <p>Here's an example image:</p> <p><img src="https://i.stack.imgur.com/N6GUA.png" alt="alt text"></p> <p>Here's HTML code that uses it</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Gradient Test&lt;/title&gt; &lt;style type="text/css"&gt; th { color:brown; background-image:url(http://img222.imageshack.us/img222/6586/fillhz2.png); background-repeat:repeat-x; margin: 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;One line&lt;/th&gt; &lt;th&gt;Three&lt;br&gt;lines&lt;br&gt;of text&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Data&lt;/td&gt; &lt;td&gt;Data&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It will repeat, but only within one direction. Usually a gradient can be safely repeated within one direction, there is no need to stretch it.</p>
<p>First of all, I'm assuming you're using CSS to place this background image. You probably need to clarify that part of your answer. </p> <p>I don't believe there is a css function that you can use to make your background image stretch. As Mecki says, you can use background-repeat to tile the image horizontally, but that's not going to deal with the header expanding beyond the height of your original tile.</p> <p>The simplest way to deal with this would be to just make your background big enough to fit a couple of lines or more.</p> <p>So if you make the background say 40px tall or perhaps slightly larger, your not going to add a huge amount in terms of file size, but then you have a more flexible design.</p> <p>In general as far as layout and graphics go, it's always best to build in a bit of flexibility, to cope with browser inconsistencies and different user needs.</p>
33,181
<p>In many places, <code>(1,2,3)</code> (a tuple) and <code>[1,2,3]</code> (a list) can be used interchangeably.</p> <p>When should I use one or the other, and why?</p>
<p>From the <a href="http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types" rel="noreferrer">Python FAQ</a>:</p> <blockquote> <p>Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.</p> <p>Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.</p> </blockquote> <p>Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.</p>
<p><code>(1,2,3)</code> is a tuple while <code>[1,2,3]</code> is a list. A tuple is an immutable object while a list is mutable.</p>
2,419
<p>I am trying to update an old JavaScript function used to detect support for AJAX (i.e. the XmlHttpRequest object). I've looked online (including SO) and found various solutions but I'm not sure which is the most efficient for simply detecting support.</p> <p>The current function is:</p> <pre><code> function IsSyncAJAXSupported() { var isSyncAJAXSupported = true; var xmlHttp = null; var clsids = ["Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for(var i=0; i&lt;clsids.length &amp;&amp; xmlHttp == null; i++) { try { xmlHttp = new ActiveXObject(clsids[i]); } catch(e){} } if(xmlHttp == null &amp;&amp; MS.Browser.isIE) { isSyncAJAXSupported = false; } return isSyncAJAXSupported; } </code></pre> <p>In Firefox 3, the above gives errors because MS is undefined.</p> <p>I realise that using a library would be better but that's not an option for the short term. We are only supporting IE6 and above + recent versions of Firefox, Safari/WebKit and Opera.</p> <p>What's the best way of getting a true/false for XmlHttpRequest support?</p>
<p><strong>Don't!</strong></p> <p>Or rather, don't waste time doing what many other people have done better.</p> <p>Try grabbing the source of jQuery or somesuch and "borrow" their methods; they've already invested the time to supporting as many browsers as possible (especially true in jQuery's case) so save yourself the time.</p> <p>HTH</p>
<p><strong>Don't!</strong></p> <p>Or rather, don't waste time doing what many other people have done better.</p> <p>Try grabbing the source of jQuery or somesuch and "borrow" their methods; they've already invested the time to supporting as many browsers as possible (especially true in jQuery's case) so save yourself the time.</p> <p>HTH</p>
39,354
<p>I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on.</p> <p>Take the 3 tables below...</p> <pre><code>Vehicle Veh_ID - int (Primary Key) FK_Atr_VehicleColor - int Veh_Make - nvarchar(20) Veh_Model - nvarchar(50) Veh_LicensePlate - nvarchar(10) Attributes Atr_ID - int (Primary Key) FK_Aty_ID - int Atr_Name - nvarchar(50) AttributeTypes Aty_ID - int (Primary key) Aty_Name - nvarchar(50) </code></pre> <p>The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc...</p> <p>Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large?</p> <p>Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"?</p> <p>Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database.</p> <p>-- Note: could not use underscore outside of code view as everything between two underscores is <em>italicized</em>.</p>
<p>I believe it's a common practice to have separate denormalized table specifically for full-text indexing. This table is then updated by triggers or, as it was in our case, by SQL Server's scheduled task.</p> <p>This was SQL Server 2000. In SQL Server you can have an <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx" rel="nofollow noreferrer">indexed view</a> with full-text index: <a href="http://msdn.microsoft.com/en-us/library/ms187317.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187317.aspx</a>. But note that there are many restrictions on indexed views; for instance, <em>you can't index a view that uses OUTER join</em>.</p>
<p>As I understand it (I've used SQL Server a lot but never full-text indexing) SQL Server 2005 allows you to create full text indexes against a view. So you could create a view on</p> <pre><code>SELECT Vehicle.VehID, ..., Color.Atr_Name AS ColorName FROM Vehicle LEFT OUTER JOIN Attributes AS Color ON (Vehicle.FK_Atr_VehicleColor = Attributes.Atr_Id) </code></pre> <p>and then create your full-text index across this view, including 'ColorName' in the index.</p>
15,040
<p>I'm looking for your best solutions for creating a new message instance based on a pre-defined XSD schema to be used within a Biztalk orchestration.</p> <p>Extra votes go to answers with clear &amp; efficient examples or answers with quality referenced links.</p>
<p>There are several options when wanting to create a new instance of a message in a BizTalk orchestration.</p> <p>I've described the three I usually end up using as well as adding some links at the bottom of the answer.</p> <p>How to define which is the best method really depends - the XMLDocument method is in some regards the tidiest except that if your schema changes this can break without you knowing it. <a href="http://www.traceofthought.net/CommentView.aspx?guid=c1164c59-72e2-49e2-be7a-47e4e8dc46d4" rel="nofollow noreferrer">Scott Colestock</a> describes some methods of mitigating that risk.</p> <p>The BizTalk Mapping method is probably the simplest to understand and won't break when the schema changes. For small schemas this can be a good choice.</p> <p>For all of these methods an important thing to remember is that if you want to use distinguished fields or promoted properties you will want to create empty elements to populate. You will hit runtime <code>XLANG</code> errors if you try to assign values to elements that are missing (even though those elements may be optional)</p> <h2>BizTalk Map</h2> <p>The simplest option is to just use a BizTalk map - you don't even necessarily need to map anything into the created instance.</p> <p>To create empty elements you can just map in a string concatenation functoid with an empty string parameter.</p> <h2>Assign one message to another</h2> <p>If you want to create a new instance of a message you can simply copy one mesage to another message of the same schema, in a message assignment shape. </p> <h2>Use an XMLDocument variable</h2> <p>For this you create an orchestration variable of type <code>XMLDocument</code> and then in a <code>message assignment</code> use the <code>LoadXML</code> method to load an XML snippet that matches your schema. You then assign the <code>XMLDocument</code> to the desired BizTalk message.</p> <pre><code>varXMLDoc.LoadXml(@"&lt;ns0:SomeXML&gt;&lt;AnElementToPopulate&gt;&lt;/AnElementToPopulate&gt;&lt;/SomeXML&gt;"); msgYourMessage = varXMLDom; </code></pre> <p>The inclusion of <code>AnElementToPopulate</code> allows you to using property promotion to assign to it.</p> <p>I seldom remember the syntax to do this off the top of my head, <a href="http://blogs.objectsharp.com/post/2004/11/09/Constructing-BizTalk-2004-XML-Messages-(In-an-Orchestration)-Choices.aspx" rel="nofollow noreferrer">this</a> is my go to blog entry for reminding myself of the syntax.</p> <p>Another link <a href="http://www.sabratech.co.uk/blogs/yossidahan/2008/03/creating-message-from-scratch.html" rel="nofollow noreferrer">here</a> details some methods.</p>
<p>Check out my blog post - <a href="http://www.sabratech.co.uk/blogs/yossidahan/2008/10/fun-with-message-creation-in-biztalk.html" rel="nofollow noreferrer">Fun with Message Creation in BizTalk</a> - for a basic performance comparison between various options.</p>
40,384
<p>This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has </p> <pre><code>int add(int i, int j) </code></pre> <p>and the implementation "Add.cpp" which has</p> <pre><code>int add(int i, int j) { return i+j; } </code></pre> <p>Now let's say in a second project I want to use the add function. However, this code:</p> <blockquote> <p><strong>#include "..\SimpleMath\Add.h"</strong></p> </blockquote> <pre><code>int main() { add(1, 2); } </code></pre> <p>results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.</p>
<p>The reason for the error you're getting is that by including the header file you're telling the compiler that there is a symbol</p> <pre><code>int add (int, int) </code></pre> <p>That will be present during linkage, but you haven't actually included that symbol (the code for the function) in your project. A quick way to resolve the issue is to simply add Add.cpp to both projects. But the "nice" solution would probably be to make SimpleMath into a library instead of an application by changing the project type in the project properties.</p> <p>And by the way, you probably want some sort of mechanism in place to prevent multiple inclusion of that header file in place. I usually use <code>#pragma once</code> which should be fine if you stick with Visual C++ but that might not be entirely portable so if you want portability, go with the more traditional approach of wrapping the header file in an <code>#ifndef</code>-block, as such:</p> <pre><code>#ifndef __ADD_H #define __ADD_H int add (int i, int j); #endif </code></pre> <p>Good luck.</p>
<p>I just had this problem <strong>within the same project</strong>... After looking closely at my code I notices that the code trying to call the function was <strong>using an interface</strong> (through a pure virtual method call = 0). However, <strong>I forgot to add the "virtual" word</strong> in the interface class and the implementation class. Once I added the "virtual" the problem was solved.</p>
22,552
<p>In my user model, I have an attribute called "nickname" and validates as such:</p> <blockquote> <p>validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true</p> </blockquote> <p>However, it is currently letting this string pass as valid:</p> <p>a?c</p> <p>I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.</p>
<p>You need to anchor the pattern on both sides:</p> <pre><code>/^[a-zA-Z0-9]+$/ </code></pre>
<p>You need to anchor the pattern on both sides:</p> <pre><code>/^[a-zA-Z0-9]+$/ </code></pre>
24,748
<p>After reading <a href="https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730">this answer</a>, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.</p>
<pre><code>MasterCard: 5431111111111111 Amex: 341111111111111 Discover: 6011601160116611 American Express (15 digits) 378282246310005 American Express (15 digits) 371449635398431 American Express Corporate (15 digits) 378734493671000 Diners Club (14 digits) 30569309025904 Diners Club (14 digits) 38520000023237 Discover (16 digits) 6011111111111117 Discover (16 digits) 6011000990139424 JCB (16 digits) 3530111333300000 JCB (16 digits) 3566002020360505 MasterCard (16 digits) 5555555555554444 MasterCard (16 digits) 5105105105105100 Visa (16 digits) 4111111111111111 Visa (16 digits) 4012888888881881 Visa (13 digits) 4222222222222 </code></pre> <p><strong>Credit Card Prefix Numbers:</strong> </p> <pre><code>Visa: 13 or 16 numbers starting with 4 MasterCard: 16 numbers starting with 5 Discover: 16 numbers starting with 6011 AMEX: 15 numbers starting with 34 or 37 </code></pre>
<p>Most payment processors provide either a testing number (PayPal does this) or the ability to go into testing mode (in which no transactions actually get processed). Consult the documentation.</p>
9,242
<p>I'm trying to do a very simple button that changes color based on mouseover, mouseout and click, I'm doing this in prototype and the weird thing is if I used mouseover and mouseout, after I clicked on the button, the button wouldn't change to white, seems like it is because of the mouseout, here's my code</p> <pre><code>$("izzy").observe('mouseover', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); $("izzy").observe('mouseout', function() { $('izzy').setStyle({ color: '#666666' }); }); $("izzy").observe('click', function() { $('izzy').setStyle({ color: '#FFFFFF' }); }); </code></pre> <p>how can I fix it? Thanks.</p>
<p>Unless there's something else happening in mouse over and out, why not use css? </p> <pre><code>#izzy:hover { color: '#FFFFFF'; } </code></pre> <p>However, I'm a little confused as to what exactly you want to happen. Assuming you want the button white if it has been clicked or if the mouse is over it. I'd have the click event handler add a clicked class, like so:</p> <pre><code>$("izzy").observe('click', function() { $('izzy').addClass('selected'); }); </code></pre> <p>And the css as so</p> <pre><code>#izzy { color: '#666666'; } #izzy:hover, #izzy.selected { color: '#FFFFFF'; } </code></pre> <p>This has the advantage of separating the state - clicked/not-click and mouse over/not over - from the style - black or gray. Right now they're all mixed in together, creating confusion and opening yourself to bugs.</p>
<p>If you move the cursor away from the button after clicking on it, the last event is mouseout, so it happens no matter if you click or not.</p> <p>If you want to avoid the mouseout effect when it is clicked, try setting a flag when clicking and abortind the mouseout event if the flag is set.</p>
33,375
<p>I'm looking for a clear, concise and accurate answer. </p> <p>Ideally as the actual answer, although links to good explanations welcome.</p> <p>This also applies to VB.Net, but the keywords are different - <code>ByRef</code> and <code>ByVal</code>.</p>
<p>By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.</p> <pre><code>void Test1(string param) { param = "new value"; } string s1 = "initial value"; Test1(s1); // s1 == "initial value" </code></pre> <p>Using <code>out</code> or <code>ref</code> passes a reference to the variable specified in the call to the function. Any changes to the value of an <code>out</code> or <code>ref</code> parameter will be passed back to the caller.</p> <p>Both <code>out</code> and <code>ref</code> behave identically except for one slight difference: <code>ref</code> parameters are required to be initialised before calling, while <code>out</code> parameters can be uninitialised. By extension, <code>ref</code> parameters are guaranteed to be initialised at the start of the method, while <code>out</code> parameters are treated as uninitialised.</p> <pre><code>void Test2(ref string param) { param = "new value"; } void Test3(out string param) { // Use of param here will not compile param = "another value"; } string s2 = "initial value"; string s3; Test2(ref s2); // s2 == "new value" // Test2(ref s3); // Passing ref s3 will not compile Test3(out s2); // s2 == "another value" Test3(out s3); // s3 == "another value" </code></pre> <p><strong>Edit</strong>: As <a href="https://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105" title="dp">dp</a> points out, the difference between <code>out</code> and <code>ref</code> is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for <code>out</code> and implements <code>ref</code> (as <code>ByRef</code>) only, matching the support of the CLR.</p>
<p><code>out</code> means that the parameter will be initialised by the method:</p> <pre><code>int result; //not initialised if( int.TryParse( "123", out result ) ) //result is now 123 else //if TryParse failed result has still be // initialised to its default value (0) </code></pre> <p><code>ref</code> will force the underlying reference to be passed:</p> <pre><code>void ChangeMyClass1( MyClass input ) { input.MyProperty = "changed by 1"; input = null; //can't see input anymore ... // I've only nulled my local scope's reference } void ChangeMyClass2( ref MyClass input ) { input.MyProperty = "changed by 2"; input = null; //the passed reference is now null too. } MyClass tester = new MyClass { MyProperty = "initial value" }; ChangeMyClass1( tester ); // now tester.MyProperty is "changed by 1" ChangeMyClass2( ref tester ); // now tester is null </code></pre>
3,410
<p>Are there any things to be careful about when defining the <code>method_missing</code> method in Ruby? I'm wondering whether there are some not-so-obvious interactions from inheritance, exception throwing, performance, or anything else.</p>
<p>A somewhat obvious one: always redefine <code>respond_to?</code> if you redefine <code>method_missing</code>. If <code>method_missing(:sym)</code> works, <code>respond_to?(:sym)</code> should always return true. There are many libraries that rely on this.</p> <p><em>Later:</em></p> <p>An example:</p> <pre><code># Wrap a Foo; don't expose the internal guts. # Pass any method that starts with 'a' on to the # Foo. class FooWrapper def initialize(foo) @foo = foo end def some_method_that_doesnt_start_with_a 'bar' end def a_method_that_does_start_with_a 'baz' end def respond_to?(sym, include_private = false) pass_sym_to_foo?(sym) || super(sym, include_private) end def method_missing(sym, *args, &amp;block) return foo.call(sym, *args, &amp;block) if pass_sym_to_foo?(sym) super(sym, *args, &amp;block) end private def pass_sym_to_foo?(sym) sym.to_s =~ /^a/ &amp;&amp; @foo.respond_to?(sym) end end class Foo def argh 'argh' end def blech 'blech' end end w = FooWrapper.new(Foo.new) w.respond_to?(:some_method_that_doesnt_start_with_a) # =&gt; true w.some_method_that_doesnt_start_with_a # =&gt; 'bar' w.respond_to?(:a_method_that_does_start_with_a) # =&gt; true w.a_method_that_does_start_with_a # =&gt; 'baz' w.respond_to?(:argh) # =&gt; true w.argh # =&gt; 'argh' w.respond_to?(:blech) # =&gt; false w.blech # NoMethodError w.respond_to?(:glem!) # =&gt; false w.glem! # NoMethodError w.respond_to?(:apples?) w.apples? # NoMethodError </code></pre>
<p>Another gotcha:</p> <p><code>method_missing</code> behaves differently between <code>obj.call_method</code> and <code>obj.send(:call_method)</code>. Essentially the former one miss all private and non-defined methods, while later one doesn't miss private methods.</p> <p>So you <code>method_missing</code> will never trap the call when someone calling your private method via <code>send</code>.</p>
37,127
<p>I've been trying to find a free database creator for mac os, and i'm not being able to find any. Anyone know of a free one i could download?</p> <p>EDIT: I need that the application generate the sql (mysql in this case) also :)</p> <p>ty</p>
<p><a href="http://ondras.zarovi.cz/sql/demo/" rel="nofollow noreferrer">SQL Designer</a> is web-based.</p> <p>There's also more options at <a href="https://stackoverflow.com/questions/30474/database-schema-diagram-design-tool">this question</a>.</p>
<p>I think the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650" rel="nofollow noreferrer">Entity modeling stuff in XCode</a> might be of us to you...</p>
28,919
<p>WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a <a href="http://getfirebug.com/wiki/index.php/Console_API" rel="noreferrer">console documentation for Firebug</a>, but where can I find the console documentation for Safari/WebKit?</p>
<p>Supported methods were originally:</p> <ul> <li><code>console.log()</code></li> <li><code>console.error()</code></li> <li><code>console.warn()</code></li> <li><code>console.info()</code></li> </ul> <p>Newer versions of WebKit also add the following methods making the WebKit console API almost identical to <a href="http://getfirebug.com/wiki/index.php/Console_API" rel="noreferrer">Firebug's console API</a>:</p> <ul> <li><code>console.count()</code></li> <li><code>console.debug()</code></li> <li><code>console.profileEnd()</code></li> <li><code>console.trace()</code></li> <li><code>console.dir()</code></li> <li><code>console.dirxml()</code></li> <li><code>console.assert()</code></li> <li><code>console.time()</code></li> <li><code>console.profile()</code></li> <li><code>console.timeEnd()</code></li> <li><code>console.group()</code></li> <li><code>console.groupEnd()</code></li> </ul> <p>(New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari)</p>
<p>The Console object appearantly has a built-in 'API', in the form of a 'private property' you can reveal by doing this in the Webkit javascript-console</p> <pre><code>&gt; for(o in console) console.dir(o) _commandLineAPI log warn … </code></pre> <p>_commandLineAPI:</p> <pre><code>&gt; console.dir(_commandLineAPI) CommandLineAPI $0: "—" $1: "—" $2: "—" $3: "—" $4: "—" $$: bound: function () { $x: bound: function (xpath, context) { clear: bound: function () { copy: bound: function (object) { dir: bound: function () { dirxml: bound: function () { inspect: bound: function (object) { keys: bound: function (object) { monitorEvents: bound: function (object, types) { profile: bound: function () { profileEnd: bound: function () { unmonitorEvents: bound: function (object, types) { values: bound: function (object) { __proto__: CommandLineAPI </code></pre>
7,944
<p>With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations. </p> <p>Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option. </p>
<p>You can trace calls to malloc/free with ltrace:</p> <pre><code>#include &lt;stdlib.h&gt; int main (void) { void *ptr = malloc(10); free(ptr); return 0; } $ g++ test.cpp -o test $ ltrace -e malloc,free ./test malloc(10) = 0x804a008 free(0x804a008) = &lt;void&gt; +++ exited (status 0) +++ </code></pre> <p>To trace new/delete calls without recompiling you will probably need to use something like LD_PRELOAD to override the calls with your own versions, this is precisely what <a href="http://www.andreasen.org/LeakTracer/" rel="noreferrer">LeakTracer</a> does which might do what you want.</p>
<p>I have not tested this myself, but I am pretty sure these would work:</p> <ul> <li><p>Since you do not want to re-compile the library, giving meaningful output (vs. just "new called for 23 bytes") may require getting a stack trace. I remember using functions to navigate the stack, but I cannot find them right now. Maybe a call to system() and pstack(1) can do the trick.</p></li> <li><p>You can re-define operator new and delete, and put this new definition ahead of the std c++ library. This may not capture the calls from containers and standard components that the library in question is using. This would require a relink.</p></li> <li><p>Use can use LD_PRELOAD to change operator new and delete dynamically. This would not require a re-link if your application is dynamically linked.</p></li> </ul> <p>Hope these pointers help, I am sorry I do not have a recipe.</p>
37,272
<p>I'm looking for a reasonable way to represent searches as a RESTful URLs.</p> <p>The setup: I have two models, Cars and Garages, where Cars can be in Garages. So my urls look like:</p> <pre><code>/car/xxxx xxx == car id returns car with given id /garage/yyy yyy = garage id returns garage with given id </code></pre> <p>A Car can exist on its own (hence the /car), or it can exist in a garage. What's the right way to represent, say, all the cars in a given garage? Something like:</p> <pre><code>/garage/yyy/cars ? </code></pre> <p>How about the union of cars in garage yyy and zzz?</p> <p>What's the right way to represent a search for cars with certain attributes? Say: show me all blue sedans with 4 doors :</p> <pre><code>/car/search?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>or should it be /cars instead?</p> <p>The use of "search" seems inappropriate there - what's a better way / term? Should it just be:</p> <pre><code>/cars/?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>Should the search parameters be part of the PATHINFO or QUERYSTRING?</p> <p>In short, I'm looking for guidance for cross-model REST url design, and for search.</p> <p>[Update] I like Justin's answer, but he doesn't cover the multi-field search case:</p> <pre><code>/cars/color:blue/type:sedan/doors:4 </code></pre> <p>or something like that. How do we go from</p> <pre><code>/cars/color/blue </code></pre> <p>to the multiple field case?</p>
<p>For the searching, use querystrings. This is perfectly RESTful:</p> <pre><code>/cars?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.</p>
<p>My advice would be this:</p> <pre><code>/garages Returns list of garages (think JSON array here) /garages/yyy Returns specific garage /garage/yyy/cars Returns list of cars in garage /garages/cars Returns list of all cars in all garages (may not be practical of course) /cars Returns list of all cars /cars/xxx Returns specific car /cars/colors Returns lists of all posible colors for cars /cars/colors/red,blue,green Returns list of cars of the specific colors (yes commas are allowed :) ) </code></pre> <p>Edit:</p> <pre><code>/cars/colors/red,blue,green/doors/2 Returns list of all red,blue, and green cars with 2 doors. /cars/type/hatchback,coupe/colors/red,blue,green/ Same idea as the above but a lil more intuitive. /cars/colors/red,blue,green/doors/two-door,four-door All cars that are red, blue, green and have either two or four doors. </code></pre> <p>Hopefully that gives you the idea. Essentially your Rest API should be easily discoverable and should enable you to browse through your data. Another advantage with using URLs and not query strings is that you are able to take advantage of the native caching mechanisms that exist on the web server for HTTP traffic.</p> <p>Here's a link to a page describing the evils of query strings in REST: <a href="http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful" rel="nofollow noreferrer">http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful</a></p> <p>I used Google's cache because the normal page wasn't working for me here's that link as well: <a href="http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful" rel="nofollow noreferrer">http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful</a></p>
25,418
<p>How do I preview a url using ajax? I have seen this done with search engine plug ins and would like to learn how to do this. Specifically, I would like to be able to mouse over a link and see the preview of the webpage using ajax.</p>
<p>There's the <strong>easy</strong> solution, the <strong>hard</strong> solution, and the <strong>use-a-library</strong> solution.</p> <p><strong>use-a-library</strong> : I prefer always doing the use-a-library solution unless you have a darn good reason otherwise. One possible site which wraps the "hard solution" as a service for you: <a href="http://thumbnails.iwebtool.com/demo/" rel="nofollow noreferrer">http://thumbnails.iwebtool.com/demo/</a></p> <p><strong>easy</strong>: The easy solution is to just load the target webpage as a downscaled AJAXy window. You can use many of the Lightbox-class plugins for this task, particularly the ones which allow you to target arbitrary HTTP content for the Lightbox window. <a href="http://www.orangoo.com/labs/GreyBox/" rel="nofollow noreferrer">GreyBox</a> is my favorite of those which I have used before. <a href="http://particletree.com/features/lightbox-gone-wild/" rel="nofollow noreferrer">Lightbox Gone Wild</a> is also nice.</p> <p><strong>hard</strong>: Then there is the hard solution: you need to render the web page server side, cache the rendering as an image, and then serve up that image using Lightbox-esque Javascript (which is trivial next to the other requirements). How you would go about doing this is outside the scope of this box. Why would you do it this way? The preview generates MUCH faster for the client, and it hermetically seals the client's session away from things which might bust it in the target website -- poorly behaving Javascript and/or malware can cause Really Bad Things when you open them, even in an AJAXy window-within-a-window.</p>
<p>I think I know what he's driving at. What happens is that he wants a windows to appear on hover over a hyperlink (javascript), and for that windows to display a snapshot image of the website being referenced by the hyperlink.</p> <p>The ajax part connects to the server where you are hosting your site, asynchronously, and hits a page that goes and fetches an image of the site to display in a img tag.</p> <p>Now, how does one generate the image of the site? I would suggest that this is done in advance (for example as the content is being created) and that already-generated image is recalled. </p> <p>How to generate the images to begin with? I think that would be another question: "How to generate snapshot images of websites?"</p>
10,577
<p>I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX. I have a web service that provides data to the client. When the web service is called directly, it is properly compressed. However, when it is called via ASP.NET AJAX, the JSON response is not compressed.</p> <p>How can I get ASP.NET AJAX to send its JSON response with GZip compression?</p>
<p>This should work out of the box. To verify that my ASP.NET AJAX JSON responses use GZip compression:</p> <ol> <li><p>Download Fiddler (version 2.1.9 is the latest)</p></li> <li><p>Enable Fiddler in IE 7: Tools -> Fiddler2</p></li> <li><p>As all traffic is routed through the proxy, you need to set Fiddler to apply the accept-encoding:Gzip in the HTTP header. Rules -> Apply GZip Encoding</p></li> <li><p>Visit your site through fiddler. If your site is on localhost, IE7 won't route this through fiddler. Fiddler 2.1.8 has a neat feature that maps localhost (127,0.0.1) to <a href="http://ipv4.fiddler" rel="nofollow noreferrer">http://ipv4.fiddler</a> and <a href="http://ipv6.fiddler" rel="nofollow noreferrer">http://ipv6.fiddler</a></p></li> <li><p>Find the asmx request in the Fiddler sessions.</p></li> </ol> <p>To verify that the request was made with the gzip encoding, look at the Request-Headers in the top panel. You should see <strong>"Client: accept-encoding: gzip,deflate"</strong></p> <p>To verify that the response was sent with gzip encoding, look at the Response-Headers in the bottom panel. You should see <strong>"Transport: Content-Encoding: gzip"</strong></p> <p>I have IIS 7 installed on Vista Business SP1 with no additional configuration, my project is using ASP.NET AJAX with standard web-services.</p> <p>Hope that helps!</p>
<p>You need to check that the .asmx file extension is on the the list of file types to compress, this is where the ajax json comes from. </p>
30,236
<p>I'd like to define a generic type, whose actual type parameter can only be</p> <ol> <li>One of the numeric primitive wrapper classes (<code>Long</code>, <code>Integer</code>, <code>Float</code>, <code>Double</code>)</li> <li><code>String</code></li> </ol> <p>I can meet the first requirement with a definition like this</p> <pre><code>public final class MyClass&lt;T extends Number&gt; { // Implementation omitted } </code></pre> <p>But I can't figure out how to meet both of them. I suspect this is not actually possible, because AFAIK there's no way to specify "or" semantics when defining a formal type parameter, though you can specify "and" semantics using a definition such as</p> <pre><code>public final class MyClass&lt;T extends Runnable &amp; Serializable &gt; { // Implementation omitted } </code></pre> <p>Cheers, Don</p>
<p>Java generics does not support union types (this parameter can be A OR B).</p> <p>On a related note that may be of interest to some, it does support multiple bounds, if you want to enforce multiple restrictions. Here's an example from the JDK mentioned in the Java <a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf" rel="noreferrer">generics tutorial</a>:</p> <pre><code>public static &lt;T extends Object &amp; Comparable&lt;? super T&gt;&gt; T max(Collection&lt;? extends T&gt; coll) </code></pre>
<p>Interesting question, it boggled me a bit. However apparently this is impossible. I tried several different hacks, none really work.</p>
47,081
<p>Is there any performance gain using a CTE over a derived table?</p>
<p>Hah, got it!</p> <pre><code>Object[] ni = (Object[])nDoc.Items; string names_values = ""; for (int x = 0; x &lt; ni.Length; x++) { NotesItem item = (NotesItem)ni[x]; if (!string.IsNullOrEmpty(item.Name)) names_values += x.ToString() + ": " + item.Name + "\t\t" + item.Text + "\r\n"; } </code></pre> <p>This returned a list of indices, names, and values:</p> <pre><code>0: Received from example.com ([192.168.0.1]) by host.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500 1: Received from example.com ([192.168.0.2]) by host2.example.com (Lotus Domino Release 6.5.4 HF182) with ESMTP id 2008111917343129-205078 ; Wed, 19 Nov 2008 17:34:31 -0500 2: X_PGRTRKID 130057945714t 3: X_PGRSRC IE 4: ReplyTo "example" &lt;name@email.example.com&gt; 5: Principal "example" &lt;customerservice@email.example.com&gt; 6: From "IE130057945714t"&lt;service@test.email.example.com&gt; 7: SendTo me@example.com 8: Subject (Message subject redacted) 9: PostedDate 11/19/2008 03:34:15 PM 10: MIME_Version 1.0 11: $Mailer SMTP DirectMail 12: $MIMETrack Itemize by SMTP Server on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:31 PM;Serialize by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;Serialize complete at 11/19/2008 05:34:32 PM;MIME-CD by Router on xxxPT02-CORP/example(Release 6.5.4 HF182|May 31, 2005) at 11/19/2008 05:34:32 PM;MIME-CD complete at 11/19/2008 05:34:32 PM;Itemize by Router on camp-db-05/example(Release 7.0.2 HF76|November 03, 2006) at 11/19/2008 05:34:32 PM;MIME-CD by Notes Client on MyName/Guest/example(Release 6.5.6|March 06, 2007) at 11/20/2008 12:46:25 PM;MIME-CD complete at 11/20/2008 12:46:25 PM 13: Form Memo 14: $UpdatedBy ;CN=xxxPT02-CORP/O=example 15: $ExportHeadersConverted 1 16: $MessageID &lt;redacted@LocalDomain&gt; 17: RouteServers CN=xxxPT02-CORP/O=example;CN=camp-db-05/O=example 18: RouteTimes 11/19/2008 03:34:31 PM-11/19/2008 03:34:32 PM;11/19/2008 03:34:32 PM-11/19/2008 03:34:32 PM 19: $Orig 958F2E4E4B666AB585257506007C02A7 20: Categories 21: $Revisions 22: DeliveredDate 11/19/2008 03:34:32 PM 23: Body []exampleexample </code></pre> <p>Now, who can tell me why the Body keeps getting messed up?</p>
<p>It may not work depending on how your environment is set up, but the easiest way to deal with mail in domino is to leave them as MIME and get at the values via the NotesMIMEEntity and NotesMIMEHeader. This will only work if the mail came in from the web rather than native Notes and the environment has been set up to store mail in MIME format.</p> <p>Otherwise you need to access the body as a NotesRichTextItem. From that item you need to get a NotesRichTextNavigator that will allow you move around the rich text structure if you need to.</p> <p>If you think the struture should be relatively simple try calling NotesRichTextItem.GetFormattedText(). If that still isn't working then you're going to need to work out what is happeing by playing with an example doument and seeing what the structure looks like to the NotesRichTextNavigator.</p>
39,420
<p>I need to be able to load the entire contents of a text file and load it into a variable for further processing. </p> <p>How can I do that?</p> <hr> <p>Here's what I did thanks to Roman Odaisky's answer.</p> <pre><code>SetLocal EnableDelayedExpansion set content= for /F "delims=" %%i in (test.txt) do set content=!content! %%i echo %content% EndLocal </code></pre>
<p>If your <code>set</code> command supports the <code>/p</code> switch, then you can pipe input that way.</p> <pre><code>set /p VAR1=&lt;test.txt set /? |find "/P" </code></pre> <blockquote> <p>The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.</p> </blockquote> <p>This has the added benefit of working for un-registered file types (which the accepted answer does not).</p>
<p>Create a file called "SetFile.bat" that contains the following line with <strong>no carriage return</strong> at the end of it...</p> <pre><code>set FileContents= </code></pre> <p>Then in your batch file do something like this...</p> <pre><code> @echo off copy SetFile.bat + %1 $tmp$.bat &gt; nul call $tmp$.bat del $tmp$.bat </code></pre> <p>%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.</p>
16,220
<p>I have recently written an application(vb.net) that stores and allows searching for old council plans. Now while the application works well, the other day I was having a look at the routine that I use to generate the SQL string to pass the database and frankly, it was bad.<br> I was just posting a question here to see if anyone else has a better way of doing this.</p> <p>What I have is a form with a bunch of controls ranging from text boxes to radio buttons, each of these controls are like database filters and when the user hits search button, a SQL string(I would really like it to be a LINQ query because I have changed to LINQ to SQL) gets generated from the completed controls and run. </p> <p>The problem that I am having is matching each one of these controls to a field in the database and generating a LINQ query efficiently without doing a bunch of "if ...then...else." statements. In the past I have just used the tag property on the control to link to control to a field name in the database.</p> <p>I'm sorry if this is a bit confusing, its a bit hard to describe. Just throwing it out there to see if anyone has any ideas.</p> <p>Thanks Nathan</p>
<p>I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects <em>always always always</em> turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option.</p>
<p>Why not write it in Haxe (<a href="http://haxe.org/" rel="nofollow noreferrer">http://haxe.org/</a>) and convert it to whatever you want it to be?</p>
10,422
<p>In the course of my career I've noticed that developers working on new functionality are, as a rule, more cheerful than these assigned to troubleshooting and fixing bugs.</p> <p>Good tips on keeping business support a happy? Organising business support in the way that team's morale isn’t hurt?</p>
<p>If we start with the assumption that the reason for new function developers being happier is that they get to feel proactive or in control and the troubleshooters are reactive and pushed around by the users one answer comes to mind:</p> <p>Create a model for those doing troubleshooting to fixes to generalise these from point fixes into broad, consistent fixes for a class of problem. This puts them in the situation of creating new code, even if not new functionality, and they get to think a problem through and anticipate and avoid problems rather than playing whack-a-mole.</p> <p>In fast moving environments it may also be possible to rotate people through the job descriptions by have them follow their feature from new development into fix and realease and hopefully into version 2 of the feature.</p>
<p>Following Bell's suggestion, consider letting new or junior developers cut their teeth on fixes. Promote them from maintenance to the feature team based on their performance and ability.</p> <p>Healthy competition is also a good motivator, but it must be managed to remain a positive influence.</p>
25,493
<p>How can I change the title of the command prompt window every time I execute a dos-based program by double clicking it, in c language. Should I use the Windows API?</p>
<p>Try <a href="http://msdn.microsoft.com/en-us/library/ms686050.aspx" rel="nofollow noreferrer">SetConsoleTitle</a>.</p>
<p>you can do </p> <p>%comspec% /c start "testtest" %comspec%</p> <p>at application launcher of Windows+R </p>
6,715
<p>So im working on a game in XNA and i need it to get a server list off our site. </p> <p>so i just need to do a http request to <a href="http://play.feedthezombie.com/?want=servers&amp;enc=xml" rel="nofollow noreferrer">http://play.feedthezombie.com/?want=servers&amp;enc=xml</a> and get the contest as either a string or xml object.</p> <p>any clues?</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/875kz807.aspx" rel="nofollow noreferrer">XmlDocument.Load</a> method. It can load XML from an URL.</p>
<p>You can call any .NET framework classes you like on Windows, including ones that do network access and XML handling. On Xbox you are limited to what XNA provides to you which is a subset of the .NET framework and the only network access is through the Xbox Live APIs.</p>
24,703
<p>How do you get the max value of an enum?</p>
<p>Enum.GetValues() seems to return the values in order, so you can do something like this:</p> <pre><code>// given this enum: public enum Foo { Fizz = 3, Bar = 1, Bang = 2 } // this gets Fizz var lastFoo = Enum.GetValues(typeof(Foo)).Cast&lt;Foo&gt;().Last(); </code></pre> <p><strong>Edit</strong></p> <p>For those not willing to read through the comments: You can also do it this way:</p> <pre><code>var lastFoo = Enum.GetValues(typeof(Foo)).Cast&lt;Foo&gt;().Max(); </code></pre> <p>... which will work when some of your enum values are negative.</p>
<p>In F#, with a helper function to convert the enum to a sequence:</p> <pre><code>type Foo = | Fizz = 3 | Bang = 2 // Helper function to convert enum to a sequence. This is also useful for iterating. // stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c let ToSeq (a : 'A when 'A : enum&lt;'B&gt;) = Enum.GetValues(typeof&lt;'A&gt;).Cast&lt;'B&gt;() // Get the max of Foo let FooMax = ToSeq (Foo()) |&gt; Seq.max </code></pre> <p>Running it...</p> <pre> > type Foo = | Fizz = 3 | Bang = 2 > val ToSeq : 'A -> seq&lt;'B> when 'A : enum&lt;'B> > val FooMax : Foo = Fizz </pre> <p>The <code>when 'A : enum&lt;'B&gt;</code> is not required by the compiler for the definition, but is required for any use of ToSeq, even by a valid enum type.</p>
24,882
<p>You can use command <strong>lsof</strong> to get file descriptors for all running processes, but what I would like to do is to close some of those descriptors without being inside that process. This can be done on Windows, so you can easily unblock some application.</p> <p>Is there any command or function for that?</p>
<p>I don't know why you are trying to do this, but you should be able to attach to the process using gdb and then call close() on the fd. Example:</p> <p>In one shell: cat</p> <p>In another shell:</p> <pre><code>$pidof cat 7213 $gdb -p 7213 ... lots of output ... (gdb) </code></pre> <p>Now you tell gdb to execute close(0):</p> <pre><code>(gdb) p close(0) $1 = 0 (gdb) c Continuing. Program exited with code 01. (gdb) </code></pre> <p>In the first shell I get this output:</p> <pre><code>cat: -: Bad file descriptor cat: closing standard input: Bad file descriptor </code></pre>
<p>I doubt it. File descriptors are process-local, <code>stdout</code> is 1 to all processes, yet they still reference unique streams of course.</p> <p>Perhaps more detail would be useful, about the blocking problem you're trying to solve.</p>
41,820
<p>I've got a grid (dojox.grid v1.2) that I don't want to be sortable. How can I disable that?</p>
<p>Found it:</p> <p><a href="http://dojotoolkit.org/forum/dojox-dojox/dojox-grid-support/disable-sorting-specific-column-0" rel="nofollow noreferrer">http://dojotoolkit.org/forum/dojox-dojox/dojox-grid-support/disable-sorting-specific-column-0</a></p> <p>To save linking:</p> <p>In your onload, or postrender add code like this:</p> <p><code> dojo.byId('myGridId').canSort = function(col){ if(Math.abs(col) == 3) { return false; } else { return true; } }; </code></p> <p>(Note, the columns seem to be indexed from 1 in this setting.)</p>
<p>If you are creating your grid programatically you can do the following:</p> <pre><code>var grid = new dojox.grid.DataGrid({ ..., canSort: function(col) { return col != 3; } }); </code></pre>
49,662
<p>I know there are <a href="https://stackoverflow.com/questions/11737/net-library-to-unzip-zip-and-rar-files">libraries out there for working with ZIP files</a>. And, you can alternatively <a href="https://stackoverflow.com/questions/30211/windows-built-in-zip-compression-script-able">use the functionality built into Windows for working ZIP files</a>.</p> <p>But, I'm wondering if anyone has worked out how to use the tools built into the System.IO.Compression namespace within .NET for reading/writing ZIP files? Or, is it not possible using only this namespace?</p> <p>UPDATED: I've seem someone comment that the System.IO.Packaging namespace might be usefull with this also. Does anyone know exactly how to do it?</p>
<p>MSDN has a complete <a href="http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx" rel="noreferrer">example</a> <a href="http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx</a> using the ZipPackage class. Requires .NET 3.5.</p>
<p>Yes, I've used it in the past. I sub-classed <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx" rel="nofollow noreferrer">DataSet</a> once to support persisting itself out to a file (via the <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx" rel="nofollow noreferrer">ReadXML</a>/<a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.writexml.aspx" rel="nofollow noreferrer">WriteXML</a> method). As an added bonus, I decided to allow it to be, optionally, compressed if desired (this, as you all should already know, is extremely effective with textual data like XML).</p> <p>I used the <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx" rel="nofollow noreferrer">GZipStream</a> class (it was my understanding at the time that the related <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx" rel="nofollow noreferrer">DeflateStream</a> was merely GZip without header information, or some such &mdash; I'm sure someone could correct me on this). It works quite simply by piggy-backing on top of another stream and thus you then use the GZipStream in its place. In my case, it was piggy-backing on a FileStream.</p> <p>Given a <a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx" rel="nofollow noreferrer">MemoryStream</a> to be filled with the output of <code>myDataSet.WriteXML()</code>, I did something like the following:</p> <pre><code>if (CompressData) { // Write to memory mStream = new MemoryStream(); Save(mStream); mStream.Seek(0, SeekOrigin.Begin); // Filter that through a GZipStream and then to file fStream = new FileStream(Path.Combine(CacheFilePath, FileName + ".gz"), FileMode.OpenOrCreate); zipStream = new GZipStream(fStream, CompressionMode.Compress, true); Pump(mStream, zipStream); } else { // Write straight to file fStream = new FileStream(Path.Combine(CacheFilePath, FileName), FileMode.OpenOrCreate); Save(fStream); } </code></pre> <p>Where <code>Save()</code> and <code>Pump()</code> are simple methods like the following:</p> <pre><code>private void Pump(Stream input, Stream output) { int n; byte[] bytes = new byte[4096]; // 4KiB at a time while ((n = input.Read(bytes, 0, bytes.Length)) != 0) { output.Write(bytes, 0, n); } } public void Save(Stream stream) { AcceptChanges(); WriteXml(stream, XmlWriteMode.WriteSchema); } </code></pre>
22,287
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: </p> <blockquote> <p>Python Fatal Error: GC Object already tracked</p> </blockquote> <p>which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
<p>Yes, you can do this kind of thing:</p> <pre><code>(gdb) print PyRun_SimpleString("import traceback; traceback.print_stack()") File "&lt;string&gt;", line 1, in &lt;module&gt; File "/var/tmp/foo.py", line 2, in &lt;module&gt; i**2 File "&lt;string&gt;", line 1, in &lt;module&gt; $1 = 0 </code></pre> <p>It should also be possible to use the <code>pystack</code> command defined in the python <a href="http://svn.python.org/view/python/trunk/Misc/gdbinit?view=auto" rel="noreferrer">gdbinit</a> file, but it's not working for me. It's discussed <a href="http://wiki.python.org/moin/DebuggingWithGdb" rel="noreferrer">here</a> if you want to look into it.</p> <p>Also, if you suspect memory issues, it's worth noting that you can use <a href="http://valgrind.org/" rel="noreferrer"><code>valgrind</code></a> with python, if you're prepared to recompile it. The procedure is described <a href="http://svn.python.org/projects/python/trunk/Misc/README.valgrind" rel="noreferrer">here.</a></p>
<p>If you're using CDLL to wrap a C library in python, and this is 64-bit linux, there's a good chance that you're CDLL wrapper is misconfigured. CDLL defaults to int return types on all platforms (should be a long long on 64-bit systems) and just expects you to pass the right arguments in. You may need to verify the CDLL wrapper in this case...</p>
34,386
<p>I have a repeater control with a check box, if I check the box then my delete functionality will delete an item in the underlying table.</p> <p>When I test the delete functionality on an aspx page with a code behind page, everything works fine. Hooray!</p> <p>However, when I take the repeater and put it into a User Control, the delete functionality thinks that my repeater control has no items.</p> <p>Code as below, I've tried to strip out the unnecessary code. I asked this question on the asp.net forums but no-one responded!</p> <p>asxc:</p> <pre><code>&lt;%@ Control AutoEventWireup="true" Inherits="Moto.Web.UI.UserControls.Messages.MessageListForm" Language="C#" %&gt; &lt;asp:button id="btnDelete" runat="server" text="Delete" OnClick="btnDelete_Click" &gt;&lt;/asp:button&gt; &lt;asp:Repeater ID="RepeaterMessageList" runat="server" EnableViewState="true" &gt; &lt;ItemTemplate &gt; &lt;div class="messageContainer item" &gt; &lt;div class="messageListLeft"&gt; &lt;div class="messageList"&gt; &lt;asp:Image ID="imgUser" runat="server" CssClass="" /&gt; &lt;asp:CheckBox ID="chkDeleteMe" runat="server" Text="test" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>Code file:</p> <pre><code>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections; using System.Collections.Generic; using System.IO; namespace Moto.Web.UI.UserControls.Messages { public class MessageListForm : Moto.Web.UI.UserControls.UserControl//System.Web.UI.UserControl { private string userGUID; private MembershipUser MembershipUser; private Moto.Business.UserComponent userComponent; private Moto.Business.User user; private Button cmdPrev; private Button cmdNext; private Button cmdNewest; private Button cmdOldest; private Label lblCurrentPage; private Label lblMessage; private HyperLink hypPageRedirect; private Repeater RepeaterMessageList; private MessageView DisplayMessages = MessageView.Inbox;//default setting private Button btnDelete; private Label lblConfirmDelete; protected Button btnConfirmDelete; protected Button btnCancelDelete; enum MessageView { Inbox, //0 Sent //1 } protected override void OnInit(EventArgs e) { base.OnInit(e); this.InitializePage(); } protected void InitializePage() { this.cmdNext = (Button)FindControl("cmdNext"); this.cmdPrev = (Button)FindControl("cmdPrev"); this.cmdOldest = (Button)FindControl("cmdOldest"); this.cmdNewest = (Button)FindControl("cmdNewest"); this.lblCurrentPage = (Label)FindControl("lblCurrentPage"); // this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList"); this.RepeaterMessageList = (Repeater)FindControlRecursive(this, "RepeaterMessageList"); this.hypPageRedirect = (HyperLink)FindControl("hypPageRedirect"); this.lblMessage = (Label)FindControl("lblMessage"); //delete functionality this.btnDelete = (Button)FindControl("btnDelete"); this.lblConfirmDelete = (Label)FindControl("lblConfirmDelete"); this.btnConfirmDelete = (Button)FindControl("btnConfirmDelete"); this.btnCancelDelete = (Button)FindControl("btnCancelDelete"); //where are we coming from - are we the Logged in user or just a voyeur? if (Page.User.Identity.IsAuthenticated) { this.userComponent = new Moto.Business.UserComponent(); this.MembershipUser = Membership.GetUser();//user logged in this.userGUID = this.MembershipUser.ProviderUserKey.ToString();//signed in user this.user = this.userComponent.GetByUserGUID(this.userGUID); } else { Response.Redirect("~/default.aspx"); } if (null != this.Page.Request.QueryString["viewing"]) { //reset the enum value DisplayMessages = this.Page.Request.QueryString["viewing"].ToLower() == "sent" ? MessageView.Sent : MessageView.Inbox; CurrentPage = 0;//if it's a redirect then reset the Current Page } } void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ItemsGet();//on post back we'll call it elsewhere } switch (DisplayMessages) { case MessageView.Sent: this.hypPageRedirect.Text += "Inbox"; this.hypPageRedirect.NavigateUrl += "?viewing=Inbox"; break; case MessageView.Inbox: this.hypPageRedirect.Text += "Sent Items"; this.hypPageRedirect.NavigateUrl += "?viewing=Sent"; break; } } protected void cmdPrev_Click(object sender, EventArgs e) { // Set viewstate variable to the previous page CurrentPage -= 1; // Reload control ItemsGet(); } protected void cmdNext_Click(object sender, EventArgs e) { // Set viewstate variable to the next page CurrentPage += 1; // Reload control ItemsGet(); } protected void cmdNewest_Click(object sender, EventArgs e) { // Set viewstate variable to the previous page CurrentPage = 0; // Reload control ItemsGet(); } protected void cmdOldest_Click(object sender, EventArgs e) { } public void RepeaterMessageList_ItemDataBound(object sender, RepeaterItemEventArgs e) { // Execute the following logic for Items and Alternating Items. if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { //Are we vieing the Inbox or Sent items? if (DisplayMessages == MessageView.Inbox) { .........Do stuff } else { .........Do stuff } } } private void ItemsGet() { // this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList"); this.RepeaterMessageList.ItemDataBound += new RepeaterItemEventHandler(RepeaterMessageList_ItemDataBound); // Populate the repeater control with the Items DataSet PagedDataSource objPds = new PagedDataSource(); if (DisplayMessages == MessageView.Inbox)//which table are we getting data from? { List&lt;Moto.Business.MessageReceived&gt; messages; Moto.Business.MessageReceivedComponent messageComponent = new Moto.Business.MessageReceivedComponent(); messages = messageComponent.GetByReceiverGUID(this.user.UserGUID); objPds.DataSource = messages; } else { List&lt;Moto.Business.MessageSent&gt; messages; Moto.Business.MessageSentComponent messageComponent = new Moto.Business.MessageSentComponent(); messages = messageComponent.GetBySenderGUID(this.user.UserGUID); objPds.DataSource = messages; //Items.Tables[0].DefaultView; } // Indicate that the data should be paged objPds.AllowPaging = true; // Set the number of items you wish to display per page objPds.PageSize = 25; // Set the PagedDataSource's current page objPds.CurrentPageIndex = CurrentPage; this.lblCurrentPage.Text = "Page " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString(); // Disable Prev or Next buttons if necessary this.cmdPrev.Enabled = !objPds.IsFirstPage; this.cmdNext.Enabled = !objPds.IsLastPage; this.cmdOldest.Enabled = !objPds.IsLastPage; this.cmdNewest.Enabled = !objPds.IsFirstPage; this.RepeaterMessageList.DataSource = objPds; this.RepeaterMessageList.DataBind(); } public int CurrentPage { get { // look for current page in ViewState object o = this.ViewState["_messagesCurrentPage"]; if (o == null) return 0; // default page index of 0 else return (int)o; } set { this.ViewState["_messagesCurrentPage"] = value; } } protected void btnDelete_Click(object sender, EventArgs e) { foreach (RepeaterItem item in this.RepeaterMessageList.Items) { CheckBox chkDeleteMe = item.FindControl("chkDeleteMe") as CheckBox; TextBox test = item.FindControl("test") as TextBox; if (chkDeleteMe.Checked) { if (DisplayMessages == MessageView.Inbox)//which table are we getting data from? { .........Do stuff } else { .........Do stuff } } } // Reload control ItemsGet(); } protected Control FindControlRecursive(Control root, string id) { if (root.ID == id) { return root; } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } } </code></pre> <p>Any help greatly appreciated!</p>
<p>I think the problem is that when the delete button is clicked the Page_Load is fired again and since its a postback it does not execute the ItemsGet method and hence the repeater does not have the data.</p> <p>Try putting the ItemsGet method call in the OnPreRender event instead of Page_Load.</p> <p>Jomit</p>
<p>So it binds to the repeater and displays all the items correctly but when repeating through the list of items on postback nothing is found?</p> <p>Is the delete event definately being fired? What is visible after you have hit the delete button? (e.g. is the table empty or does it still display all the items)</p> <p>Update:</p> <p>Comment out the GetItems method and see if the table is empty or not on postback. It sounds like your repeaters viewstate isn't populating the control again or something.</p>
49,875
<p>I'm looking for the specific density of the GEL-LAY and LAYWOO 3D materials by manufacturer CC Products.</p> <p>It isn't noted on their website or on the spool or the box the spools came in. I've looked for hours on Google and various websites, from resellers to people who tested it, without being able to find it.</p>
<p>I can't provide the end answer, but if you already have the material, you should be able to measure this yourself quite simply.</p> <p>Measure and cut a sample of filament, and weigh it. For example, a 10 meter length with a 1.75 mm diameter will have a volume of:</p> <blockquote> <p>v = pi * r<sup>2</sup> * l</p> <p>v = pi * (0.175 cm/2)<sup>2</sup> * 1000 cm</p> <p>v = 24.05 cm<sup>3</sup></p> </blockquote> <p>Density is mass divided by volume. If your sample weighs 18 g, this would be</p> <blockquote> <p>d = m / v</p> <p>d = 18.0 g / 24.05 cm<sup>3</sup></p> <p>d = 0.748 g/cm<sup>3</sup></p> </blockquote> <p>Note that the accuracy of this measurement will depend on the accuracy and precision of your measurements. A household kitchen scale might not be good enough for such small weights. In order to get a good weight measurement, you may need to use a much longer (and heavier) sample of filament.</p>
<p>Indeed, the properties of this filament are kept rather secret, so to find out what the density is, you need to either contact the filament supplier or the manufacturer for accessing the data sheet or calculate this yourself. The answer below expands on the "<em>calculate it yourself</em>".</p> <p>Density is defined as <span class="math-container">$\rho = \frac{m}{V}=\frac{[kg]}{[m^3]}$</span>. The use of this formula has been show in <a href="https://3dprinting.stackexchange.com/a/7546/5740">this answer</a>. The drawback of that answer is that it is an approximation that relies on a uniform piece of filament that requires cutting off expensive filament and relies on assumptions rather than actual calculations. Furthermore, the weighing of a small piece of filament is much less accurate of a small piece than for a larger piece or the whole spool (for the same scale, so a decent kitchen scale might be usable when more weight is concerned). You could improve the density calculation by measuring the diameter at various sections and make a better approximation based on the average diameter, but still that would need you to unroll the spool and carefully measure a piece of filament (and cut it). The advantage of that answer is that it is far easier than my proposition.</p> <p>The method that is proposed here relies on a well known method to calculate the density of materials that is called hydrostatic weighing. Hydrostatic weighing uses the displacement of a fluid due to a submerged object to determine the density of the object. Any submerged object will displace the fluid surrounding it by it's own volume, as such you would need to measure the rise of the volume level to read the volume of the submerged product. This can be done accurately by using methods that include containers of known dimensions, known fluids and even an overflow method and weighing.</p> <p>If the filament comes on a spool, you would require an identical spool to prevent removing it from the spool. But, I read that it is sold in bundles, not on spools. Without a spool would make it even easier to calculate the density as you do not have to subtract the spool weight and volume, the answer continues as if you have it on a spool. This is purely necessary so that you would not need to cut off filament or unroll the whole spool. The suggestion below let's you measure the whole spool, so weight is measured more easily as there is a lot more. </p> <p>Theoretically, you could put the filament in a fluid which is known to not affect the filament properties (so not water for GEL-LAY!) in a bath of known dimensions. Once the spool and filament are completely submerged, you could measure the volume rise. If you do the same for the empty spool, you also know the volume of the spool alone. If you also are able to weigh the empty spool and the full spool (before you plunged them in the "bathtub"/container), you now know the volume and the weight of the filament, dividing the weight (full spool weight minus empty spool weight) by the volume (full spool submerged volume minus empty spool submerged volume) will give you the density.</p> <p><span class="math-container">$$\rho_{filament} = \frac{(m_{full\ spool}-m_{empty\ spool})}{(V_{full\ spool}-V_{empty\ spool})}$$</span></p> <p><br> <em>Now let your filament dry for a long, long time! :)</em></p>
1,094
<p>Now that it's clear <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
<p>A callable is anything that can be called. </p> <p>The <a href="http://svn.python.org/projects/python/trunk/Objects/object.c" rel="noreferrer">built-in <em>callable</em> (PyCallable_Check in objects.c)</a> checks if the argument is either:</p> <ul> <li>an instance of a class with a <code>__call__</code> method or</li> <li>is of a type that has a non null <em>tp_call</em> (c struct) member which indicates callability otherwise (such as in functions, methods etc.)</li> </ul> <p>The method named <code>__call__</code> is (<a href="https://docs.python.org/3/reference/datamodel.html#object.__call__" rel="noreferrer">according to the documentation</a>)</p> <blockquote> <p>Called when the instance is ''called'' as a function</p> </blockquote> <h2>Example</h2> <pre><code>class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method </code></pre>
<p>Callable is a type or class of &quot;Build-in function or Method&quot; with a method <strong>call</strong></p> <pre><code>&gt;&gt;&gt; type(callable) &lt;class 'builtin_function_or_method'&gt; &gt;&gt;&gt; </code></pre> <p>Example: <strong>print</strong> is a callable object. With a build-in function <strong><strong>call</strong></strong> When you invoke the <strong>print</strong> function, Python creates an <strong>object of type print</strong> and invokes its method <strong><strong>call</strong></strong> passing the parameters if any.</p> <pre><code>&gt;&gt;&gt; type(print) &lt;class 'builtin_function_or_method'&gt; &gt;&gt;&gt; print.__call__(10) 10 &gt;&gt;&gt; print(10) 10 &gt;&gt;&gt; </code></pre>
13,637
<p>So I am trying to get the XSD-Schema from this object. When I open the File I just get something like this code (snippet):</p> <pre><code>¸†2¡Q·2ºyƒeCã2ï…w ïÀ|¼ðAøä[0Ÿ |&gt;‚|ó‘å2²ºFƒ¼Æò1ùàåcj@Þ`ùиÌ{áÈ;0/|¾ ùÌ'Ÿ„ Á|d½¬¬¯Õ ¯±|l¾…­Œo@Þ`ùиÌ{áÈ;0/|¾ùÌ'Ÿ„ Á|d½œ¬¯Ó ¯±|h\æ­Œo@Þ`ù¸| ßBs¦5–Œ~ôè»­£(™c´“Ç£[yp1:æ'Éc4Jó Uâ˜ÍÇ&lt;h—8^'Ð¯É </code></pre> <p>What is this? How can I convert it back? I need to edit the structure manually. <br>Thank you in advance.</p>
<p>Three likely culprit:</p> <ul> <li><strong>The file is compressed but your machine can't detect it</strong>. So for example the 3MF model has been zipped, and what you are trying to do is opening the zip archive in the text editor, rather than the file that is in the zip archive. Solution: try to see if common decompress utilities like zip, gzip, 7z can open the file.</li> <li><strong>The file is a 3MF model but the <a href="https://en.wikipedia.org/wiki/Character_encoding" rel="nofollow noreferrer">character encoding</a> in the file being different than the one your editor is expecting</strong> (typically <code>Unicode/UTF-8</code>, these days). Solution: read on the rest of this answer.</li> <li><strong>The file is a binary one that is totally unrelated to 3MF</strong>. So in essence: an error, you are trying to open maybe an MP3 or a JPG file believing it to be a 3MF instead.</li> </ul> <p>As for the "wrong encoding" option... Oversimplifying a bit, the story goes like this:</p> <ul> <li>computers write data to files in bytes,</li> <li>a byte can only be set to one of its 256 possible values,</li> <li>in the early days of computing, when computers were just glorified calculators, it was enough to have a 1:1 ratio between the byte possible values and the symbols one wanted to use, so <a href="http://www.asciitable.com/" rel="nofollow noreferrer">ASCII</a> was born (actually ASCII only "mapped" the first 127 values of the byte, but that is a detail). So: value #49 would represent a <code>1</code>, value #90 a <code>Z</code> and so on...</li> <li>shortly afterwards, computers became powerful enough that people wanted to use them to process human languages, so the need for more characters (like accented ones <code>åáä</code> or the ones from non-latin alphabets like Cyrillic <code>язы́к</code> or arabic <code>عَرَبِيّ‎</code>, or...) came to be and engineers speaking different languages had the "brilliant" idea to each use the other 127 "free slots" in a byte for their favourite languages, thus a plethora of <a href="https://en.wikipedia.org/wiki/Extended_ASCII" rel="nofollow noreferrer">extended ASCII</a> encodings was born, <strong>each using the same byte value, but each mapping to a different symbol</strong>.</li> <li>later on, people began to realise the need to combine the use of say Gaelic, English, Japanese and Farsi with mathematical symbols, and thus they came up to way to map symbols to values expressed as the product of more bytes (so for example: 2 bytes encoding could map 256x256=65536 symbols). Again: each system using the same values but different symbols.</li> <li>finally after decades of frustrated users and expensive bugs, engineers around the world settled for a multi-byte <strong>standard that has 1,114,112 possible values that could contain all characters one can possibly need</strong>, and <a href="https://en.wikipedia.org/wiki/Unicode" rel="nofollow noreferrer">Unicode</a> was born.</li> </ul> <p>Back to your question: despite unicode having been around for a few decades now, legacy software and sloppy programming are a thing, and there are still systems that do not use unicode internally but some legacy "special purpose" encoding.</p> <p>Unfortunately, it is <a href="https://softwareengineering.stackexchange.com/a/187174/29074">impossible to say with certainty how a file was encoded</a>, so <strong>occasionally you may find yourself opening a file and starting decoding it according to a "conversion table" that is not the one used by the author of the file itself</strong>. This is what it looks like is happening to you.</p> <p>Onward to what you can try to do to fix this...</p> <p>First of all: as attentive readers may have already inferred, <strong>you will need the actual file</strong> for this. In fact if you cut-and-paste its "content" from an editor what you are really doing is cutting-and-pasting the <em>decoding</em> your computer did of the byte values, and not the byte values themselves.</p> <p>Then your best bets are:</p> <ul> <li><strong>Try one of the online detectors</strong> like <a href="https://nlp.fi.muni.cz/projects/chared/" rel="nofollow noreferrer">this one</a>, using "English" as a language. These detectors work by trying all the decoders they know of until the decoded file will have English (or another language of your choice) words in it. This may not work for you as a 3MF file is mostly numbers, not text, but it is worth a shot.</li> <li><strong>Guesstimate what encoder may have been used</strong>. For example: if you got the file from an old windowsXP machine from Eastern Europe, chances are it may have been encoded with "windows-1251". Use an <a href="http://www.motobit.com/util/charset-codepage-conversion.asp" rel="nofollow noreferrer">online converter</a> to see if you were right about it.</li> <li><strong>Use brute force</strong>. For this you will require to write a simple programme or ask somebody to do it for you, but the key idea here is to have a script taking your original file and decoding it using all encoders in that programming language knows of. Then it will be up to you to open each decoded file individually and verify if it worked or not.</li> </ul>
<p>Seems to be your are trying to edit a file with the wrong file editor.</p> <p>If you have Microsoft® Windows® 8.1, you can print directly using the 3MF format included. Simply set the print options in the 3D Print PropertyManager and print to the 3D printer. A preview of the print bed and the model's location within the print bed lets you modify settings before committing to a 3D print job.</p> <p>To access the 3D print dialog box and specify print options, click File > 3DPrint. The print dialog box that is available depends on your installed 3D print driver.</p> <p>If you need to get the STL you may need to use a file conversion, <a href="https://www.youtube.com/watch?v=6MVeFiCN7bA" rel="nofollow noreferrer">here</a> is a youtube tutorial to makeprintable</p>
794
<p>From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). </p> <p>I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.</p>
<p>There is no "callback" in C - not more than any other generic programming concept.</p> <p>They're implemented using function pointers. Here's an example:</p> <pre><code>void populate_array(int *array, size_t arraySize, int (*getNextValue)(void)) { for (size_t i=0; i&lt;arraySize; i++) array[i] = getNextValue(); } int getNextRandomValue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getNextRandomValue); ... } </code></pre> <p>Here, the <code>populate_array</code> function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback <code>getNextRandomValue</code>, which returns a random-ish value, and passed a pointer to it to <code>populate_array</code>. <code>populate_array</code> will call our callback function 10 times and assign the returned values to the elements in the given array.</p>
<p>Usually this can be done by using a function pointer, that is a special variable that points to the memory location of a function. You can then use this to call the function with specific arguments. So there will probably be a function that sets the callback function. This will accept a function pointer and then store that address somewhere where it can be used. After that when the specified event is triggered, it will call that function.</p>
17,253
<p>I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:</p> <pre><code>try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } </code></pre> <p>Now, I have two problems:</p> <ul> <li><p>I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?</p></li> <li><p>This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.</p></li> </ul> <p>Any help with either would be great.</p>
<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (<a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">linky</a>) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.</p>
<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (<a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">linky</a>) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.</p>
7,162
<p>I am building a medium-sized printer which needs to produce super-precise parts at a moderately fast print time. I frankly don't want to deal with belts or their tension issues but on the other hand, having ball screws on each axis will increase inertia...right?. I'm using Rexroth rails and will use (depending on what I decide) name brand belts or name brand ball screws.</p>
<p>The size of the nozzle usually isn't the main factor for how close you can put nozzles together. To keep the filament drive gear system from being the limiting factor, you would need Bowden extruders. &quot;Then, the heat sinks and fans would be your limiting factor. Have you considered a single nozzle with three extruders? Otherwise, you need custom angled heat sinks similar to the three heat sinks on a single nozzle, and still a way to orient the nozzles at the same Z-height. That would be difficult if all the nozzles are on the same heater block. It still seems that nozzle size is the least of the issues of putting nozzles close together.</p> <p>If you search for smaller nozzle sizes, you will get nozzles with smaller openings, not smaller overall size. The threads on the nozzles are a standard size. Thus, the smaller opening size can't be put closer together than the larger opening size. Otherwise, you have only small variations between different types of nozzles and need room to screw them in to the heater block if you put all of them into one block. You can get a nozzle using a 6 mm hex wrench that is smaller than one using a 7 mm hex (E3D).</p>
<p>One of the thinnest hotends I've seen are those from a Chinese factory Mellow Store, the heatsink is smaller than the top flange to mount the hotend. I don't know the quality of these hotends, the image below shows the basic layouts of available options:</p> <p><a href="https://i.stack.imgur.com/MsvUL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MsvUL.jpg" alt="Mellow Store custom hotend" /></a></p> <p>Ultimaker uses high quality hotends which are pretty small 2.85  mm hotends they call &quot;cores&quot;, they house 2 next to each other and use a lifting mechanism:</p> <p><a href="https://i.stack.imgur.com/pl0mt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pl0mt.png" alt="Ultimaker 0.8 mm core" /></a></p>
1,703
<p>I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.</p> <p>Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.</p> <p>I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?</p> <p>EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.</p> <p>Here is my code (Rev 2.0, now with optional callbacks):</p> <pre><code>function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } </code></pre> <p>and in the method with a dependency:</p> <pre><code>var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else calbackMethod(); </code></pre> <p>Any suggestions?</p>
<p>If you're using a higher level framework such as JQuery, you could check out the <code>$.getScript(url, callback)</code> function.</p>
<p>Checkout the YUI Loader utility. It's super handy, unobtrusive javascript for loading scripts on-demand.</p> <p>Here's a link to an example using non-YUI scripts:</p> <p><a href="http://developer.yahoo.com/yui/examples/yuiloader/yl-addmodule.html" rel="nofollow noreferrer">http://developer.yahoo.com/yui/examples/yuiloader/yl-addmodule.html</a></p>
24,844
<p>I am using NetBeans for PHP 6.5.</p> <p>In my code I frequently use the following type of command:</p> <pre><code>if (($row = $db-&gt;get_row($sql))) { return $row-&gt;folder; } else { return FALSE; } </code></pre> <p>Netbeans tells me that I should not be using assignments in the IF statement.</p> <p>Why ?</p>
<p>They are not bad, but they can lead to dangerous mistakes.</p> <p>In c like languages, where an assignment is an expression, (to support for example a=b=c=1;) a common error is:</p> <pre><code>if (a = 1) { .. } </code></pre> <p>But you wanted to have </p> <pre><code>if (a == 1) { .. } </code></pre> <p>Some developers have learned to type</p> <pre><code>if (1 == a) { .. } </code></pre> <p>To create an error if one '=' is forgotten. But I think that it does not improve the readability.</p> <p>However modern compilers, give a warning if you write</p> <pre><code>if (a = 1) { .. } </code></pre> <p>which I think is a better solution. In that case you are forced to check if it was what you really meant.</p>
<p>I use them all the time, with loops (not sure why that would make a difference), like:</p> <pre><code>$counter = 0; while( $getWhateverDataObj = mysql_fetch_object( $sqlResult )) { $getWhateverObj-&gt;firstName[$counter] = $getWhateverDataObj-&gt;firstName; $getWhateverObj-&gt;lastName[$counter] = $getWhateverDataObj-&gt;lastName; $counter++; } </code></pre> <p>And it works fine.</p>
40,976
<p>Let's say I'm modeling a simple box with a lid. Just as an example, we'll say the <strong>outer</strong> edge along the top of the box is 50 mm x 50 mm. With 3D modeling software, it's easy to build a lid for this box to surround the top with an <strong>inner</strong> edge size of also exactly 50 mm x 50 mm ...but this seems like a bad idea. Surely I'll want some kind of of gap, to ensure an easy on/off. An <em>exact</em> fit seems like it's asking for trouble.</p> <ul> <li>How much gap do we leave for this kind of thing?</li> <li>Is it related to nozzle size?</li> <li>I suppose it also matters how tightly you want to fit, though I expect in cases where a tight fit matters some kind of snap or clip would be used.</li> <li>Are draft prints with larger layer sizes useful for figuring this, or do the rough layers make things seem tighter than they'll be in a final print?</li> </ul>
<p>I use my clearance values according to my rule of thumb: 0.1 mm - to fit with some force, 0.2 mm - just fit edge to edge without force.</p> <p>Examples:</p> <ol> <li><p>3 mm metal cylinder to be pressed into plastic part needs <span class="math-container">$3\ mm+0.1\ mm*2=3.2\ mm$</span> diameter printed hole (clearance from two sides)</p> </li> <li><p>3 mm screw to fit into plastic part needs a hole bigger than <span class="math-container">$3\ mm+0.2\ mm*2=3.4\ mm$</span> that is 3.5 mm will be already good.</p> </li> </ol> <p>This is fully experimental but always worked for me on three different printers and both on PLA and ABS.</p>
<p>Since you said nozzle, I expect you mean FDM 3d printing. Typically you would use one (1) outline of gap between the parts. An outline is usually equal to the size of the nozzle. The corners of a 3d printed square object are rounded. The radius of that rounding would be half your nozzle diameter (i.e. the nozzle's radius). Also if there was any over extrusion occurring on the outline it the two parts would not fit within each other. This is of course assuming that they are being designed to easily come apart. Otherwise you can make them an exact fit if you intend to friction fit them together.</p>
990
<p>I am looking for troubleshooting help on my printer. Recently the hot end just can muster the courage to go past about 70 °C.</p> <p>The hardware - Ender 3V2 with a E3D V6 hot end. 24 volts</p> <p>I changed the thermistor to a new one. Before heating, it registers an appropriate 10 °C in line with the bed temp sensor.</p> <p>With the thermistor checked good, I looked at the heater element. It is reading 22 Ω. The documentation from E3D is not clear in what wattage heater I bought, but if it is a 30 W 24 V heater, it's on the high end of acceptable.</p> <ul> <li>A 24 V 30 W heater cartridge will read between 16.7 - 22.6 Ω.</li> <li>A 24 V 40 W heater cartridge will read between 12.3 - 15.1 Ω.</li> </ul> <p>If anyone is able to confirm how to know what my heater wattage is supposed to be, LMK. Options are shown for blue wires, red wires, and yellow. I have yellow.</p> <p>If the resistance is in spec, I checked if the voltage being supplied to the heater is correct. It is reading 23.6 V which seems good.</p> <p>I have attempted to PID autotune in Pronterface which I had also done several times previously before the issue. If I try to target anything over 70 °C, the attempt to tune fails because it can't get hot enough. I can tune if I set the temp to 65 °C by comparison.</p> <p>The temperature trace in Pronterface shows the temp rising quickly through the 30s, 40s, then plateauing and maxing out in the high 60s.</p> <p>I am looking for advice on where to look next for trouble shooting. Seems odd to suddenly have such a low temperature limit capability that I can't root cause.</p>
<h2>TL;DR:</h2> <p>Print more PLA on top of them, and pull it off together.</p> <h2>Preparation</h2> <p>First, of course, clean it well with IPA. This will both ensure there's no oil or other material on top of the PLA that will prevent it from bonding well with new PLA, and start to work underneath it to get it loose.</p> <h2>Printing</h2> <p>Then, print! Do a 2- or 3-layer square covering the whole buildplate if you need to, or just smaller ones in the affected areas. They should bond to whatever is there and pull it up when you peel them off.</p> <h2>Prevention</h2> <p>To avoid this happening in the future, <strong>fix your bed leveling</strong>. The type of tracks that are nearly impossible to remove by themselves normally come from printing with the nozzle so low that the material is forced entirely between the texture irregularities of the build surface, with no significant layer on top, and this means your bed is at least a whole layer-height too high relative to the nozzle.</p>
<p>If you can feel it with your finger, then you can scrape it off. Just be careful. Keep the scraper closer to horizontal and don't dig in. It doesn't really need much effort.</p> <p>If you can't feel it with your finger then it doesn't matter. Just clean as normal and carry on printing over it.</p>
2,117
<p>I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?</p>
<p>EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.</p> <p>To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">serialize the two arrays to JSON</a> and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to <em>each</em> of the objects within the arrays as well to see which ones were different.</p> <p>Another option is to use a library which has some nice facilities for comparing objects - I use and recommend <a href="http://www.mochikit.com/" rel="noreferrer"><strong>MochiKit</strong></a>.</p> <hr> <p><strong>EDIT:</strong> <a href="https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932">The answer kamens gave</a> deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).</p> <p>Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:</p> <pre><code>function objectsAreSame(x, y) { var objectsAreSame = true; for(var propertyName in x) { if(x[propertyName] !== y[propertyName]) { objectsAreSame = false; break; } } return objectsAreSame; } </code></pre> <p>The assumption is that both objects have the same exact list of properties.</p> <p>Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)</p>
<p>comparing with json is pretty bad. try this package to compare nested arrays and get the difference.</p> <blockquote> <p><a href="https://www.npmjs.com/package/deep-object-diff" rel="nofollow noreferrer">https://www.npmjs.com/package/deep-object-diff</a></p> </blockquote>
4,667
<p>I'm porting an existing .NET 3.5 application into a plug-in for Eclipse.</p> <p>I want to have my custom UserControl, written in C#, embedded within Eclipse; I've exported it successfully as a COM Control, and it works well in Eclipse Europa.</p> <p>In Ganymede, it seems the OLE load code has changed, and what originally worked in Europa, fails.</p> <p>The specific error is when Ganymede loads my control, it queries for IOleObject, receives the proper interface, and then calls SetClientSite on it, which causes my object to lose both its references, and become de-allocated (Ganymede will then crash). The exact same control works flawlessly in both Visual C++ designer and in Europa.</p> <p>Apart from the obvious .NET attributes and UserControl, is there any specific class I need to inherit from? Specific interfaces I need to implement, or specific behavior change between Europa/VC and Ganymede?</p> <p>Thanks!</p>
<p>If anyone is still having this problem, then please report it on <a href="http://connect.microsoft.com/visualstudio/" rel="nofollow noreferrer">Connect</a>. When done reporting, please post the URL of the bug report here, so people who read this post can vote on it.</p> <p>If this is still a bug, it would be nice to get it fixed by RTM of .NET 4.0, or at least SP1.</p>
<p>I've come across similar problems with hosting .NET controls in non .NET environments. There have been problems with how some of my user controls have exposed to COM. </p> <p>Following the example on this site solved my problem, perhaps it will help you too!</p> <p><a href="http://blogs.msdn.com/calvin_hsia/archive/2006/07/14/665830.aspx" rel="nofollow noreferrer">Link</a></p>
21,407
<p>Since I've started using NetBeans, I've learned of some <a href="http://www.netbeans.org/kb/60/java/gui-db.html" rel="nofollow noreferrer">powerful ways</a> to abstract away the process of creating Java database applications with automatically generated UI, beans bindings, and a bunch of other stuff I only vaguely understand the workings of at the moment (I hate being a newb). Problem is, <em>how do I do the basic stuff I actually want to do</em>? The tutorials I've read make a big deal about being able to connect to and mess around with a database from within the IDE, or how to create and bind some UI sliders and checkboxes to table columns, etc. But where can I learn about how to make my own code do that stuff? Abstraction is nice and all, but it's quite useless to me at the moment for what I need done.</p> <p>Can anyone refer me to some good resources or tutorials to learn this? The few I've found aren't proving as useful as I'd hoped to get my project underway...</p>
<p>The <a href="http://java.sun.com/docs/books/tutorial/jdbc/index.html" rel="nofollow noreferrer">JDBC Tutorial</a> is a good starting point</p> <p>A snippet from the intro</p> <pre> The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write java applications that manage these three programming activities: 1. Connect to a data source, like a database 2. Send queries and update statements to the database 3. Retrieve and process the results received from the database in answer to your query The following simple code fragment gives a simple example of these three steps: </pre> <pre><code> Connection con = DriverManager.getConnection ( "jdbc:myDriver:wombat", "myLogin","myPassword"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } </code></pre> <pre> This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple. </pre> <p>There is also a book preview on Google Books <a href="http://tinyurl.com/5sgag8" rel="nofollow noreferrer">here</a>.</p>
<p>After reading jdbc tutorials take some attention to the base concepts: - connection - statement - query - resultset</p> <p>Db authorisation belongs to conntection, query is the description of "what to do" - fetch data or update, resultset could be updatable(!) in some cases.</p>
37,319
<p>The following code illustrates an object literal being assigned, but with no semicolon afterwards:</p> <pre><code>var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); </code></pre> <p>This appears to be legal, and doesn't issue a warning (at least in Firefox&nbsp;3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?</p> <p>I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.</p>
<p>Not technically, JavaScript has semicolons as optional in many situations. </p> <p>But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.</p> <p>Automatic semicolon insertion is performed by the interpreter, so you <em>can</em> leave them out if you so choose. In the comments, someone claimed that </p> <blockquote> <p>Semicolons are not optional with statements like break/continue/throw</p> </blockquote> <p>but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. </p> <p>Here is the rest of the standard on semicolon insertion:</p> <blockquote> <p>For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.</p> </blockquote>
<p>This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from</p> <pre><code>var foo = "bar"; </code></pre> <p>The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.</p> <p>If you want to be writing correct JavaScript code, write the semicolon :-)</p> <p>According to the ECMAscript spec, <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow noreferrer">http://www.ecma-international.org/publications/standards/Ecma-262.htm</a>, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.</p>
6,368
<p>I've inherited someone else's monster of a BASH script. The script was written in such a way that it uses a ridiculous amount of memory (around 1GB). I can run it from a shell with out issue, but if I run it from cron I crashes with a sig fault. </p> <p>Apart from digging into the poorly commented behemoth, is there a way to run it from cron with out running into the sig fault? </p> <p>Cheers,</p> <p>Steve</p>
<p>When you run something using cron you'll encounter issues with the environment variables being different or simply not set as compared to your own variables when you manually execute. Often things like the PATH aren't set properly when cron executes something, so it's important to supply full paths to executables within the script, even for things such as perl or common commands that you thing <em>should</em> be found in the default PATH. Without more info it's hard to speculate on what precisely the problem is.</p>
<p>try making sure stdout and stderr have somewhere to go</p> <pre><code>/path/to/bigscript.sh &amp;&gt; /dev/null </code></pre> <p>[Edit] you may want to use a file other than /dev/null, especially if your running it in debug mode ;)</p> <p>Being so huge, I'm not if running in debug would help but you can try. In bash, it's the '-x' option, which you can just put in the shebang.</p> <p>And as said in other answers, there's a good chance that it may be an environment variable.</p>
33,355
<p>I'm trying to have an XSLT that copies most of the tags but removes empty "<code>&lt;b/&gt;</code>" tags. That is, it should copy as-is "<code>&lt;b&gt; &lt;/b&gt;</code>" or "<code>&lt;b&gt;toto&lt;/b&gt;</code>" but completely remove "<code>&lt;b/&gt;</code>".</p> <p>I think the template would look like :</p> <pre><code>&lt;xsl:template match="b"&gt; &lt;xsl:if test=".hasChildren()"&gt; &lt;xsl:element name="b"&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:element&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre> <p>But of course, the "<code>hasChildren()</code>" part doesn't exist ... Any idea ?</p>
<p>I wonder if this will work?</p> <pre><code>&lt;xsl:template match="b"&gt; &lt;xsl:if test="b/text()"&gt; ... </code></pre>
<p>If you have access to update the original XML, you could try using use <strong>xml:space=preserve</strong> on the root element</p> <pre><code>&lt;html xml:space="preserve"&gt; ... &lt;/html&gt; </code></pre> <p>This way, the space in the empty &lt;b&gt; &lt;/b&gt; tag is preserved, and so can be distinguished from &lt;b /&gt; in the XSLT.</p> <pre><code>&lt;xsl:template match="b"&gt; &lt;xsl:if test="text() != ''"&gt; .... &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre>
38,288
<p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p> <pre><code>Socket mySocket = new Socket(host,port); </code></pre> <p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p> <pre><code>tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT </code></pre> <p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p> <p>I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.</p> <p>Any advice please?</p> <p>Thanks all</p>
<p>Set a short timeout?</p> <p>Does <code>isOutputShutdown()</code> not get you what you want?</p> <p>You could always build a <code>SocketWatcher</code> class that spins up in its own <code>Thread</code> and repeatedly tries to write empty strings to the <code>Socket</code> until that raises a <code>SocketClosedException</code>.</p>
<p>Set a different thread to reading from the socket. It will block until the socket is closed, and then an exception will be thrown. Catch that exception to detect the close immediately.</p>
4,276