instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I am currently trying to print a gear with the possibility to connect it to the shaft of a DC motor. The following picture best describes what the shaft of the motor looks like by showing the hole printed in the gear:</p> <p><a href="https://i.stack.imgur.com/UNHn5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UNHn5.png" alt="enter image description here" /></a></p> <p>So far this works well for a short amount of time, however since the gear is connected to another gear that is from time to time exerting quite some resistance already after a few revolutions the shaft starts to wear out the material that is holding it and it turns without powering the gear, i.e. the printed part is not strong enough to withstand the torque of the motor.</p> <p>I am wondering what the best way forward would be here. I see multiple options:</p> <ul> <li>Design a different connection to the shaft, however I don't know of any</li> <li>Switch to a different material, I am currently using PLA, but I could also go for ABS or PETG if any of them would provide advantages. For PLA vs ABS I found some conflicting information which one is &quot;harder&quot;</li> <li>Play with the parameters of the print. At the moment I am only using 3 wall layers, I wonder if increasing the number of wall layers would improve rigidity.</li> </ul> <p>Are there other ideas? What could you recommend me to improve this connection?</p>
<blockquote> <p>Design a different connection to the shaft, however I don't know of any</p> </blockquote> <p>Use a shaft/flange coupler to be fastened to your shaft and to your printed part.</p> <hr /> <p>Without knowing the length of the shaft, you could connect a flange/coupler to design this into your gear. This is a good solution if you have to transmit larger torques. See e.g. <a href="https://www.thingiverse.com/thing:3296969" rel="noreferrer">this pulley</a> that incorporates that concept.</p> <p>Shaft flange couplers can be connected to your printed part and to the flat part of the shaft.</p> <p>Metal flange couplers are available in many sizes:</p> <p><a href="https://i.stack.imgur.com/TPne9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TPne9.jpg" alt="enter image description here" /></a></p> <p>A recess in the printed part houses the flange:</p> <p><a href="https://i.stack.imgur.com/pka5O.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pka5O.jpg" alt="enter image description here" /></a></p> <p>When assembled you can mount the pulley/gear onto the shaft, provided you have enough length on the shaft.</p> <p><a href="https://i.stack.imgur.com/PNt6V.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/PNt6V.jpg" alt="enter image description here" /></a></p>
<p>A good option would be to use a (set-)screw to press against the flat of the motor shaft, similar to how pulleys are mounted on stepper motors.</p>
1,733
<p>Using Microsoft Visual Studio 98, Microsoft Visual C++ 6.0 SP6</p> <p>When running under the debugger, there's only one problem. If I pause the program and resume, everything's fine.</p> <p>The problem? When I hit a breakpoint, my program stops. But not in a good way; execution halts, I'm thrown out of debug mode into edit mode. All's fine until a breakpoint is hit. And I know it's hitting the breakpoint - I see a flash of the little yellow arrow pointing at the right line of code, local variables in the inspect window and the call stack in that window. And then I'm staring at the editor.</p> <p>This happens in all projects.</p> <p>I've uninstalled and re-installed MSVC6. It didn't help.</p> <p>I'm about to start over on a new PC; before I go that far, anyone know what I've done to this one?</p> <hr> <p>Note: MSVC6 is not my choice, but there are reasons. It's the tool I work with. And, we get to target NT4, so given 2008 can't target NT4 and 2005 has issues with MFC and NT4, MSVC6 it is.</p>
<p>Stop beating on VC6. It's old. The STL was updated in 1996 from HP code written in 1994. C++ was ratified in 1998.</p> <p>What is the code doing when you are breaking? Can you reduce the situation into a simple test. When I try that I usually find the cause. If you can do that so it still happens then I'll take a look at it for you. I too am unfortunate enough to use VC6 for my day to day work.</p> <p>Visual C++ Express 2008 can't be used in certain situations.</p>
<p>I haven't used MSVC6 in years, but I remember the debugger basically being a flaky piece of crap. Things like this would regularly happen for no apparent reason because it just didn't like your code that day.</p> <p>In addition to the debugger being a flaky piece of crap, the rest of it was too.</p> <p>It's STL implementation isn't threadsafe, it doesn't support very much of the C++ standard, and the IDE is sorely lacking in niceties. </p> <p>I'm pretty sure you also just simply can't use any versions of the Platform SDK from the last 5 years because it's too old to grok them. Not a good thing.</p> <p>You'd be mad to keep using it when there is <a href="http://www.microsoft.com/express/vc/" rel="nofollow noreferrer">Visual C++ Express 2008</a> which you can download for free.</p>
2,986
<p>I am building a toolchanger CoreXY 3D printer. I am in big trouble to find mic-6 aluminium toolplate in my country. Can you suggest me an alternative to mic-6? In my country, I can find easily 5083, 6082, 7005, etc. I don't think, that theese aluminium plates are suitable as heated bed. The design of the bed is the same as the <a href="https://jubilee3d.com/index.php?title=Main_Page" rel="nofollow noreferrer">jubilee 3D printer</a>, so it will be best to have minimum warpage.</p>
<p>This is probably caused by too few top layers in combination with a too low infill percentage. Increase skin layers and increase infill percentage.</p> <p>If you have multiple layers already (at least about 4 for 0.2 mm layer height, for smaller layer heights even more), you might be printing at a too high temperature and or too few part cooling percentage and a too low infill percentage.</p>
<p>To combat the bad top layers, I usually use usually 5 top layers for any model of layer height 0.1 to 0.3 mm. I generally don't print with less than 9 % infill for PLA, which I have found sufficient to support even complex geometry on top.</p> <p>Also, I generally use a mixed setup of layers: the outermost layers I demand as concentric because this is the most beautiful setup, while the lower levels are Zig-Zag patterned, as this gives the best layer-to-wall connection.</p>
1,815
<p>From what I understand, it takes a really long time for the heated bed to heat up using an MK2a heated bed. I've heard some people suggest that using <a href="http://forums.reprap.org/read.php?4,584582" rel="nofollow">Polyisocyanurate (PIR) foam</a> (insulation that takes quite a bit of heat to catch on fire) can be used under the headed bed to make it heat up faster. </p> <p>Now of course there are other methods for doing this too, for instance using a larger power supply, but at this point I'd rather just use the parts that I have without re-soldering many of the components on the RAMPS board. </p> <p>I was wondering what a proper way to attach this to the bed would be for instance, should the springs go on the bottom or on the top of the bed? Do I need some extra parts? Are there any other considerations for doing this?</p>
<p>An alternative solution that is used with some <a href="https://www.think3dprint3d.com/3D-Printer-Kits/complete-3D-printer-kits/Kossel-Mini-3dPrinter-Kit" rel="nofollow">Kossel Mini</a> models, is a simple <a href="https://lh4.googleusercontent.com/RNWfKpkiA_cg16D6gPqcQ4e1uCFmW4-lIV-KVZYnFJyn3EtbCrsH_sXHKXZxkrlPjnHD1giczw676mjnJbq4SwFeJRHEGvfZqdh_j_QoX1kYxGITuiuJ9xQZ023sgMSyCEolIuo" rel="nofollow">cardboard covered with aluminum tape</a> (<a href="https://docs.google.com/document/d/1k2J78MIDsD2FBHLDnZ06bMdprNjH6nYhkiLUsjemnUc/pub" rel="nofollow">docs</a>).</p> <p>This solution has the added benefit of actually improving heat-up time, since the reflective surface of the aluminum tape <em>reflects the heat back into the bed</em>, instead of getting absorbed. </p> <p>It is also a very simple solution, without costly materials. I guess mounting it properly could be an issue depending on your printer, but this is a fine solution for the Kossel models, at least.</p>
<p>If you use a seperate powersupply for your bed (or if your controller has a built in voltage regulator so it doesn't damage at higher voltages) you can sometimes find an small potentiometer near the connection terminals of your powersupply, turning this potentiometer up can raise the outputvoltage of your powersupply by a few volts max. In my case the potentiometer was orange and allowed me to turn up the voltage by almost 2Volts!</p> <p>If your printcontroller is running from the same powersupply and is critical about input DON'T do this since it will damage the electronics. Better option then is to find a higher voltage powersupply and power the bed Seperately. </p> <p>A buddy of mine runs his MARK2a bed on 19V and it heats up very fast. (he uses an obscure 15V powersupply that was able to be cranked up to 19V). And he doesn't use insulation at all!</p>
185
<p>I'm trying to write a RegEx for a code generator (in C#) to determine a proper class or package name of an AS3 class.</p> <p>I know that class names</p> <ul> <li>must start with a letter (capital or otherwise)</li> <li>any other digit can be alphanumeric</li> <li>cannot have spaces</li> </ul> <p>Is there anything else?</p>
<p>Although you can start class names with lower case letters and include underscores and dollar signs, the "naming <strong>convention</strong>" is to start the class name and each separate word with a capital letter (e.g. UsefulThing), and not include underscores. When I see classes like <code>useful_thing</code>, it looks wrong, because it's not the naming <strong>convention</strong>. Maybe your question should have said what are the <strong>valid</strong> names for an AS3 class?</p> <p>Other than that I think you + maclema have it.</p>
<p>Here are some more valid classes. </p> <p>Actionscript 3 classes (and packages) must start with a letter, "_", or "$". They may also contain (but not start with) a number.</p> <pre><code>public class $Test {} public class _Test {} public class test {} </code></pre>
4,182
<ol> <li>Specifically getting on Windows the "..\Documents &amp; Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. <strong>(Now I need the answer to this)</strong></li> <li>the current users My Documents dirctory <strong>(okay this has been answered)</strong> and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.</li> </ol>
<p>My docs would probably best be handled by accessing:</p> <pre><code>System.getProperty("user.home"); </code></pre> <p>Look up the docs on <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html" rel="noreferrer">System.getProperty</a>.</p>
<blockquote> <p>Specifically getting on Windows the "..\Documents &amp; Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)</p> </blockquote> <p>The folders below the All Users dir are variable directories in windows. Details can be found in the document about <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457%28v=vs.85%29.aspx" rel="nofollow">KNOWNFOLDERIDs</a> (<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx" rel="nofollow">CSIDL</a> in older versions). Because this values are system dependent Java does not provide a way to access the values.</p> <p>I think there is in general no equivalent on other operating systems to this windows specific folder. In addition the folder Documents &amp; Settings\All Users is only present in latest windows versions and things are handled differently for e.g Windows 2000 or XP I think.</p> <p>If you really need this information you should read the microsoft docs and impement a native library or some script invoked by Runtime.exec to provide the information to your java application.</p>
5,788
<p>I'm new to NHibernate (my 1st big project with it).<br> I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. </p> <p>This doesn't work in a situation where lazy-loading is required, however.<br> For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception.<br> Anyone using a different method?</p>
<p>Session management:</p> <p><a href="http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs" rel="nofollow noreferrer">http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs</a></p> <p>Session per request:</p> <p><a href="http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs" rel="nofollow noreferrer">http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs</a></p>
<p>Since you are developing a Web App (presumably with ASP.NET), check out <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">NHibernate Best Practices with ASP.NET</a> at CodeProject.</p>
5,257
<p>I think that java executables (jar files) are trivial to decompile and get the source code.</p> <p>What about other languages? .net and all?</p> <p>Which all languages can compile only to a decompile-able code?</p>
<p>In general, languages like Java, C#, and VB.NET are relatively easy to decompile because they are compiled to an intermediary language, not pure machine language. In their IL form, they retain more metadata than C code does when compiled to machine language. </p> <p>Technically you aren't getting the original source code out, but a variation on the source code that, when compiled, will give you the compiled code back. It isn't identical to the source code, as things like comments, annotations, and compiler directives usually aren't carried forward into the compiled code.</p>
<p>Most languages can be decompiled but some are easier to decompile than others. .Net and Java put more information about the original program in the executables (method names, variable names etc.) so you get more of your original information back. </p> <p>C++ for example will translate variables and functions etc. to memory adresses (yeah I know this is a gross simplification) so the decompiler won't know what stuff was called. But you can still get some of the structure of the program back though.</p>
6,526
<p>Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder.</p> <p>Thanks</p>
<p>Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.</p> <p>Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.</p> <p>If the exception appears when calling a method on objects instantiated by classes <em>you</em> made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.</p>
<p>If your file name is different than the class name which contain main method then it may be the possibility that this error may cause.</p>
5,563
<p>I know you should, like an infant, never leave your printer without surveillance.</p> <p>But sometimes we all do, trusting our double thermistors and heat runaway configurations. But electronics fry and who says there is no danger even after the print job has finished and it's cooling down, still hooked up?</p> <p>I have searched but smoke/fire detectors come in a wide range of varieties: </p> <p>They can be battery powered or hardwired, they detect different things: carbon monoxide, heat, smoke..., they thus also have different detectors like photoelectric sensors, ionization sensors or both. We also print with different materials...</p> <p>So what's the best safeguard for my 2 year old (CoreXY ^^)?</p>
<p>Disclaimer: I am not affiliated with any linked brand or company, I just link to them for reference of the suggested print settings.</p> <h1>What is PLA?</h1> <p>PLA is, by its definition PolyLacticAcid, a polymer of entwined lactic acids. It is commonly made from fermenting starch - not via Type I (alcohol) but Type II (lactic acid) fermentation<sup><a href="https://3dprinting.stackexchange.com/users/12857/user77232">user77232</a>, <a href="https://en.wikipedia.org/wiki/Lactic_acid_fermentation" rel="noreferrer">Wikipedia</a></sup>. Chemically it looks like this:</p> <p><a href="https://i.stack.imgur.com/JFAww.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JFAww.png" alt="Structural formula of PLA" /></a></p> <p>It's relevant physical data for the pure material are a density of 1.210–1.430 g·cm<sup>−3</sup> and a melting point of 150 to 160 °C.<sup><a href="https://en.wikipedia.org/wiki/Polylactic_acid" rel="noreferrer">Wikipedia</a></sup>.</p> <p>Usually, PLA sold under just the name PLA contains, besides PLA, additives to change the color from transparent to whatever color one is printing at. This can change the standard printing temperature depending on the amount, size and shape of the pigments embedded (see below).</p> <p>Common Printing temperatures are listed by the manufacturers in the range of 185 to 210 °C. The color can have an influence on the printing temperature, especially for the difference between transparent and opaque filaments. While a heated bed is not strictly necessary, the bed temperature is usually quoted with 60 °C.</p> <p>I myself print most PLA filaments at 200 °C and 60 °C bed, but for noncolored transparent filament, I had better results using 190 °C.</p> <p>Note that not all PLA is just PLA! It is very likely that some PLA brands contain fillers and additives from the house without claiming to be a +-filament, indeed, additives precede the idea of PLA+, as the case with Tiertime PP3DP filaments will show.</p> <h3>The special Tiertime mixture</h3> <p>Since back in 2012 or earlier, ABS made by Tiertime includes some unknown compound (possibly PC) that alters the best-result print temperature from the &quot;normal&quot; 220 - 240 °C to the much higher but narrower 260 - 270 °C band. Why this is done is a mystery among 3d-printing enthusiasts, but it might be either to get rid of any color-dependency of the print results or to make it harder to use generic ABS. Fact is, that this temperature was matching what was set as the (then unchangeable) standard temperature in the <em>Up 1.1.7</em> software of that time.<sup><a href="https://www.tiertime.com/forum/viewtopic.php?t=8233" rel="noreferrer">Angus aka MakersMuse</a> &amp; <a href="https://www.tiertime.com/forum/viewtopic.php?t=8233" rel="noreferrer">Tiertime Forums</a></sup>. The higher temperature hasn't changed over the years<sup><a href="https://www.genie-online.de/product/3D-printer-ABS-filament-1x700g-1.75mm-Color-black/239" rel="noreferrer">Tiertime ABS</a></sup>. Indeed, the Tiertime PLA introduced in March 2014<sup><a href="https://www.tiertime.com/tiertime-now-offers-pla-for-up-series-printers/" rel="noreferrer">Tiertime</a></sup> is also quoted to print at higher temperatures than generic PLA, and had similarly a higher default temperature in the then updated UP-spftware<sup><a href="https://www.tiertime.com/dami/viewtopic.php?t=54665" rel="noreferrer">Tiertime Forums</a></sup>, though I found listings from 200<sup><a href="https://3dprintersuperstore.com.au/products/black-up-pla" rel="noreferrer">here</a> &amp; <a href="https://www.reprap-3d-printer.com/product/1234568364-pla-tiertime-official-natural" rel="noreferrer">here</a></sup> to 215 °C<sup><a href="https://www.3dmensionals.de/tiertime-pp3dp-up-pla-filament-1000g?number=PSUPP0030V" rel="noreferrer">here</a> under Technische Daten</sup>.</p> <p><strong>The modern <em>UP-Studio</em> software allows setting the temperature freely</strong><sup><a href="https://youtu.be/uCnNxc_U9cE?t=437" rel="noreferrer">Angus aka MakersMuse</a></sup>.</p> <h1>What is PLA+?</h1> <p>Now, what differs PLA from PLA+? Well, PLA+ is a <em>modified</em> PLA, which means that it has additives in it to alter its properties. What exactly is added depends extremely on the manufacturer, and no two PLA+ are the same.<sup><a href="https://all3dp.com/2/pla-vs-pla-3d-printer-filament-compared/" rel="noreferrer">all3dp</a></sup>.</p> <h1>What is the difference?</h1> <p>PLA+ has - but for a few degrees - the same printing temperature as standard PLA. In fact, the printing temperature difference between standard PLA from different brands is often larger than the difference between PLA and PLA+.</p> <p><a href="https://all3dp.com/2/pla-vs-pla-3d-printer-filament-compared/" rel="noreferrer">All3dp</a> claims, that most PLA+ would have a better surface finish than the PLA from the same brand. Because of the additives, they also usually print best at elevated temperature compared to PLA. Among various manufacturers, I saw 210–240 °C<sup><a href="https://rads.stackoverflow.com/amzn/click/com/B079VYGNRG" rel="noreferrer" rel="nofollow noreferrer">Kodak PLA+</a></sup>, 190-220 °C<sup><a href="https://www.amazon.de/SUNLU-Filament-Printing-Dimensional-Accuracy/dp/B073P9LZWB" rel="noreferrer">SUNLU PLA+</a></sup> and 190-210 °C<sup><a href="https://www.amazon.de/eSun-Filament-Universal-Thing-matic/dp/B01KM6MDFG" rel="noreferrer">eSun PLA+</a></sup>.</p> <p>However, there is no uniformity in other effects on the filament. Some filaments would have less moisture absorption, a different stiffness or compressibility while others might have a higher tensile strength and feature an extremely glossy surface.</p> <p>Most commonly, the claimed benefits lie in the fields of the filament's strength, surface texture and glossiness, the printability of overhangs.</p> <h1>Conclusion</h1> <p>PLA+ is <strong>not one product</strong> per se but <strong>a family of modified PLA</strong>. While you can print PLA+ with the same settings as normal PLA, the resulting benefits between different brands are much more diverse than with normal PLA.</p> <ul> <li>Changing between different brands of <em>similar quality</em> normal PLA has usually little to no effect on the print's general properties.</li> <li>Changing between different brands of <em>similar quality</em> PLA+ can alter the print's properties immensely</li> </ul> <p>Because of the fact that no two brands of PLA+ are the same (and the manufacturers are silent on what additives they use to change the properties), one should not rely on the same effects when switching between brands.</p>
<p>Adding this as a new answer since it doesn't seem to be covered in existing ones:</p> <p>Despite &quot;PLA+&quot; being a marketing term without a specific definition, I've found that many (most?) filament vendors don't seem to be doing their own secret-sauce blending to make it, and most premium filament vendors who <em>do document</em> the source polymers they use are using roughly the same thing - most often one of the <a href="https://www.natureworksllc.com/Products/3D-series-for-3D-printing" rel="nofollow noreferrer">Natureworks Ingeo 3D series of polymers</a>, obtained in pellet source form, often 3D850 or 3D870. As such, if you can verify that this is what you filament marketed as &quot;PLA+&quot; is made from (or just search out one that's well-documented) you can use the data sheets for the polymer to find out more about how it's formulated.</p>
747
<p>In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?</p> <pre><code>if (@x = 1) begin select 1 as Text into #Temptable end else begin select 2 as Text into #Temptable end </code></pre>
<p>It's created when it's executed and dropped when the session ends.</p>
<p>Whilst it may be automatically dropped at the end of a session, it is good practice to drop the table yourself when you're done with it.</p>
6,553
<p>The compiler usually chokes when an event doesn't appear beside a <code>+=</code> or a <code>-=</code>, so I'm not sure if this is possible.</p> <p>I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:</p> <pre><code>using(var foo = new EventWatcher(target, x =&gt; x.MyEventToWatch) { // act here } // throws on Dispose() if MyEventToWatch hasn't fired </code></pre> <p>My questions are twofold:</p> <ol> <li>Will the compiler choke? And if so, any suggestions on how to prevent this?</li> <li>How can I parse the Expression object from the constructor in order to attach to the <code>MyEventToWatch</code> event of <code>target</code>?</li> </ol>
<p><strong>Edit:</strong> As <a href="https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255">Curt</a> has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "<code>x =&gt; x.MyEvent</code>" returning the event, it was returning the backing field, which is only accessble by the class.</p> <p>Since expressions cannot contain assignment statements, a modified expression like "<code>( x, h ) =&gt; x.MyEvent += h</code>" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the <code>EventInfo</code> for the event (which, unfortunatley, will not be strongly typed).</p> <p>Otherwise, the only updates that need to be made are to store the reflected <code>EventInfo</code>, and use the <code>AddEventHandler</code>/<code>RemoveEventHandler</code> methods to register the listener (instead of the manual <code>Delegate</code> <code>Combine</code>/<code>Remove</code> calls and field sets). The rest of the implementation should not need to be changed. Good luck :)</p> <hr> <p><strong>Note:</strong> This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)</p> <pre><code>public sealed class EventWatcher : IDisposable { private readonly object target_; private readonly string eventName_; private readonly FieldInfo eventField_; private readonly Delegate listener_; private bool eventWasRaised_; public static EventWatcher Create&lt;T&gt;( T target, Expression&lt;Func&lt;T,Delegate&gt;&gt; accessor ) { return new EventWatcher( target, accessor ); } private EventWatcher( object target, LambdaExpression accessor ) { this.target_ = target; // Retrieve event definition from expression. var eventAccessor = accessor.Body as MemberExpression; this.eventField_ = eventAccessor.Member as FieldInfo; this.eventName_ = this.eventField_.Name; // Create our event listener and add it to the declaring object's event field. this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType ); var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Combine( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList ); } public void SetEventWasRaised( ) { this.eventWasRaised_ = true; } private Delegate CreateEventListenerDelegate( Type eventType ) { // Create the event listener's body, setting the 'eventWasRaised_' field. var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" ); var body = Expression.Call( Expression.Constant( this ), setMethod ); // Get the event delegate's parameters from its 'Invoke' method. var invokeMethod = eventType.GetMethod( "Invoke" ); var parameters = invokeMethod.GetParameters( ) .Select( ( p ) =&gt; Expression.Parameter( p.ParameterType, p.Name ) ); // Create the listener. var listener = Expression.Lambda( eventType, body, parameters ); return listener.Compile( ); } void IDisposable.Dispose( ) { // Remove the event listener. var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Remove( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList ); // Ensure event was raised. if( !this.eventWasRaised_ ) throw new InvalidOperationException( "Event was not raised: " + this.eventName_ ); } } </code></pre> <p>Usage is slightly different from that suggested, in order to take advantage of type inference:</p> <pre><code>try { using( EventWatcher.Create( o, x =&gt; x.MyEvent ) ) { //o.RaiseEvent( ); // Uncomment for test to succeed. } Console.WriteLine( "Event raised successfully" ); } catch( InvalidOperationException ex ) { Console.WriteLine( ex.Message ); } </code></pre>
<p>While Emperor XLII already gave the answer for this, I thought it was worth while to share my rewrite of this. Sadly, no ability to get the Event via Expression Tree, I'm using the name of the Event.</p> <pre><code>public sealed class EventWatcher : IDisposable { private readonly object _target; private readonly EventInfo _eventInfo; private readonly Delegate _listener; private bool _eventWasRaised; public static EventWatcher Create&lt;T&gt;(T target, string eventName) { EventInfo eventInfo = typeof(T).GetEvent(eventName); if (eventInfo == null) throw new ArgumentException("Event was not found.", eventName); return new EventWatcher(target, eventInfo); } private EventWatcher(object target, EventInfo eventInfo) { _target = target; _eventInfo = event; _listener = CreateEventDelegateForType(_eventInfo.EventHandlerType); _eventInfo.AddEventHandler(_target, _listener); } // SetEventWasRaised() // CreateEventDelegateForType void IDisposable.Dispose() { _eventInfo.RemoveEventHandler(_target, _listener); if (!_eventWasRaised) throw new InvalidOperationException("event was not raised."); } } </code></pre> <p>And usage is:</p> <pre><code>using(EventWatcher.Create(o, "MyEvent")) { o.RaiseEvent(); } </code></pre>
5,565
<p><strong><em>Note</strong>: Before any negative flagging, we asked permission on Meta prior to posting &amp; got a YES: <strong><a href="https://3dprinting.meta.stackexchange.com/questions/281/could-this-printing-material-recommendation-question-be-or-shaped-to-be-valid-on/283#283">Could this Printing Material Recommendation Question be or shaped to be valid on 3D SE?</a></em></strong></p> <hr> <p>Which common 3D printing materials/methods will suitably replicate (with durability) this injection molded Polypropylene item? </p> <p><strong>Item to replicate via 3D Printing:</strong><br> <a href="https://imgur.com/a/oJX5Q5A" rel="nofollow noreferrer">Club Handle</a> - 5/6 image album (a few images are attached below as well) </p> <p><strong>Physics, Mechanics &amp; Forces in play on object:</strong><br> Usage Intent is not to create an Impact or Hit but to <strong>Flow in Circular motion</strong> like this: <a href="https://www.youtube.com/watch?v=fIEOWh87ahY" rel="nofollow noreferrer">YouTube - 10 Best Indian Club Exercises</a> </p> <ul> <li>Item with <strong>PCO 28 PET Threading</strong></li> <li>20 cm Length - Avg. 28 mm Diameter</li> </ul> <p>Instead of me trying to figure out materials, I seek advice from experienced experts here. </p> <p>Please advise and suggest on materials:</p> <ul> <li>Ideal top 3 materials recommended/ most suitable for this item?</li> <li>Other top 3 materials that are easier to get through "Entities" on 3dHubs? </li> <li><strong>Add Thought:</strong> <em>Is "negative" printing is the way to go (Sculpting, lathe, threading, CNC types)?</em> </li> </ul> <p><strong>Note:</strong> The immediate answer people gave was to use <strong>PP printing</strong>, however I am looking for alternatives because PP printing is <strong>not common or easy to find nearby</strong> and <strong>expensive</strong>. </p> <hr> <p><strong>Self Homework:</strong></p> <p>So I looked through these <strong>material guides</strong> which show <strong>different attributes</strong> and <strong>ratings</strong> for various <strong>parameters</strong>:</p> <ul> <li>Print-ability</li> <li>Strength</li> <li>Stiffness</li> <li>Durability</li> <li>Price</li> </ul> <p>For example, Polypropylene - <a href="https://www.simplify3d.com/support/materials-guide/polypropylene/" rel="nofollow noreferrer">Simplify3D - Polypropylene</a></p> <p><em>Polypropylene is great for high-cycle, low strength applications due to its fatigue resistance, semi-flexible, and lightweight characteristics.</em></p> <p><strong>Entire Material Lists looked at:</strong></p> <ul> <li><a href="https://www.simplify3d.com/support/materials-guide/" rel="nofollow noreferrer">Simplify3D - Ultimate 3D Printing Materials Guide</a></li> <li><a href="https://blog.tinkercad.com/materialsguide/" rel="nofollow noreferrer">Tinkercad - 3D Printing Materials Guide</a></li> <li><a href="https://all3dp.com/1/3d-printing-materials-guide-3d-printer-material/" rel="nofollow noreferrer">All3DP - 2018 3D Printing Materials Guide</a></li> <li><a href="https://3dprinting.com/materials/" rel="nofollow noreferrer">3DPrinting.com - 3D Printer Materials Guide</a></li> <li><a href="https://www.shapeways.com/materials" rel="nofollow noreferrer">Shapeways - Materials for every stage of any project</a> </li> </ul> <hr> <p><a href="https://i.imgur.com/upOyMCN.jpg" rel="nofollow noreferrer" title="Injection molded Polypropylene item - image 1"><img src="https://i.imgur.com/upOyMCN.jpg" alt="Injection molded Polypropylene item - image 1" title="Injection molded Polypropylene item - image 1"></a> <a href="https://i.imgur.com/TcL9718.jpg" rel="nofollow noreferrer" title="Injection molded Polypropylene item - image 2"><img src="https://i.imgur.com/TcL9718.jpg" alt="Injection molded Polypropylene item - image 2" title="Injection molded Polypropylene item - image 2"></a></p>
<h2>No FDM print at all.</h2> <p>The problem of your design will not be the materials, but a basic property of FDM printing: FDM Printers do create a structure by placing a long string of filament next to itself and ontop of itself, creating tons of boudaries.</p> <p>These boundaries between the layers are the weak points for this application: Even if the material like ABS could withstand the blow handled with such a club, the print will break at its weakest point - which in this case is any layer boundary. This is amplyfied by the basic design we have here: The elongated shape will serve as a lever on each of the weak boundries, until one gives way and results in catastrophic failure and a flying clubhead.</p> <h1>Non-FDM for the rescue.</h1> <p>To counteract this, you need to use a different method than FDM printing to get a more homogenous material than the bound deposited filament. Such methods could be for example SLA (Stereolithography) or SLS (Selective Laser Sintering). Both could easily offer even tiny details.</p> <p>SLS uses Nylon or metal powders, sometimes even ceramics - Tungstencarbide for example.</p> <h3>SLA/Resin</h3> <p>Using a Resin printer using the SLA methods results in an object almost as homogenous as an injecion molded object. Proper aftercare and curing is required to get the best results. Also, Resin prints usually age under UV light, which can negatively impact lifetime. SLA printers are expensive (for home printers), print shops that offer them relatively rare and costly (in comparison to FDM) but usually offer superb resolution and almost perfect smoothness. A lot of the exact material properties is resin and aftercare dependant.</p> <p>A way around the aging could be that the results of an SLA print could be used to create green-sand molds countless times, which can be used for casting metal or even some thermoplastics. Remember though, that cooling metal shrinks.</p> <h3>SLS Nylon</h3> <p>Nylon would be a medium rigid, light solution, but it ages and has a quite rough surface. It does offer some flex, almost perfect for this application. While most SLS machines for nylon are commercial to industrial, print technology of this kind is widespread enough to make them somewhat affordable (for an industrial printer) and printshops for these relatively common, prints are not cheap but well priced.</p> <h3>DMLS / SLM</h3> <p>Direct Metal Laser Sintering and Selective Laser Melting - an evolution of SLS - allows to create structures from various metals by sintering/melting powders of metal at the right spot to gain shape. The benefit would be, that you get a part that could withstand much more destructive testing than your bottle used as a clubhead - you get a workpiece of solid metal (Steel, aluminium, Titanium and a lot others are available) after all that has the same properties as a cast item. The big downside is, that only few companies currently delve into DMLS, among them the former patent holder of many of the FDM printing patents, <a href="https://www.stratasysdirect.com/technologies/direct-metal-laser-sintering" rel="nofollow noreferrer">Stratasys</a>. This means, that a machine for this is industrial rated and priced, and that print suppliers charge accordingly.</p>
<h2>No FDM print at all.</h2> <p>The problem of your design will not be the materials, but a basic property of FDM printing: FDM Printers do create a structure by placing a long string of filament next to itself and ontop of itself, creating tons of boudaries.</p> <p>These boundaries between the layers are the weak points for this application: Even if the material like ABS could withstand the blow handled with such a club, the print will break at its weakest point - which in this case is any layer boundary. This is amplyfied by the basic design we have here: The elongated shape will serve as a lever on each of the weak boundries, until one gives way and results in catastrophic failure and a flying clubhead.</p> <h1>Non-FDM for the rescue.</h1> <p>To counteract this, you need to use a different method than FDM printing to get a more homogenous material than the bound deposited filament. Such methods could be for example SLA (Stereolithography) or SLS (Selective Laser Sintering). Both could easily offer even tiny details.</p> <p>SLS uses Nylon or metal powders, sometimes even ceramics - Tungstencarbide for example.</p> <h3>SLA/Resin</h3> <p>Using a Resin printer using the SLA methods results in an object almost as homogenous as an injecion molded object. Proper aftercare and curing is required to get the best results. Also, Resin prints usually age under UV light, which can negatively impact lifetime. SLA printers are expensive (for home printers), print shops that offer them relatively rare and costly (in comparison to FDM) but usually offer superb resolution and almost perfect smoothness. A lot of the exact material properties is resin and aftercare dependant.</p> <p>A way around the aging could be that the results of an SLA print could be used to create green-sand molds countless times, which can be used for casting metal or even some thermoplastics. Remember though, that cooling metal shrinks.</p> <h3>SLS Nylon</h3> <p>Nylon would be a medium rigid, light solution, but it ages and has a quite rough surface. It does offer some flex, almost perfect for this application. While most SLS machines for nylon are commercial to industrial, print technology of this kind is widespread enough to make them somewhat affordable (for an industrial printer) and printshops for these relatively common, prints are not cheap but well priced.</p> <h3>DMLS / SLM</h3> <p>Direct Metal Laser Sintering and Selective Laser Melting - an evolution of SLS - allows to create structures from various metals by sintering/melting powders of metal at the right spot to gain shape. The benefit would be, that you get a part that could withstand much more destructive testing than your bottle used as a clubhead - you get a workpiece of solid metal (Steel, aluminium, Titanium and a lot others are available) after all that has the same properties as a cast item. The big downside is, that only few companies currently delve into DMLS, among them the former patent holder of many of the FDM printing patents, <a href="https://www.stratasysdirect.com/technologies/direct-metal-laser-sintering" rel="nofollow noreferrer">Stratasys</a>. This means, that a machine for this is industrial rated and priced, and that print suppliers charge accordingly.</p>
941
<p>I'm trying to subtract a polyhedron from a cube, but it is not working (the cube remains solid). However, I can see the cut-out poly in preview mode (but not after a full render).</p> <p><strong>Preview</strong> -- poly cutout shows on the top (and bottom).</p> <p><a href="https://i.stack.imgur.com/Zk1Z5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zk1Z5.png" alt="preview" /></a></p> <p><strong>Rendered</strong> -- poly cutout not visible.</p> <p><a href="https://i.stack.imgur.com/cofDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cofDh.png" alt="rendered" /></a></p> <p><strong>Poly Exploded</strong> -- pulled the poly to the right to show its shape.</p> <p><a href="https://i.stack.imgur.com/VILrM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VILrM.png" alt="poly exploded" /></a></p> <p><strong>Code</strong></p> <pre><code>size = 30; wall = 3; wall_x2 = wall * 2; nubGap = .125; nubHeight = 8; nubOffset = wall + nubGap; xCutoutSize = size - wall_x2; yCutoutSize = size - wall_x2; cutoutLowerY = nubHeight + nubGap; cutoutUpperOffset = nubOffset + wall; difference() { cube([size, size, size]); translate([wall, wall, 0]) { polyhedron( points = [ [0, 0, -10], [xCutoutSize, 0, -10], [xCutoutSize, yCutoutSize, -10], [0, yCutoutSize, -10], [0, 0, cutoutLowerY], [xCutoutSize, 0, cutoutLowerY], [xCutoutSize, yCutoutSize, cutoutLowerY], [0, yCutoutSize, cutoutLowerY], [cutoutUpperOffset, cutoutUpperOffset, size], [xCutoutSize - cutoutUpperOffset, cutoutUpperOffset, size], [xCutoutSize - cutoutUpperOffset, yCutoutSize - cutoutUpperOffset, size], [cutoutUpperOffset, yCutoutSize - cutoutUpperOffset, size] ], faces = [ [0, 1, 2], [2, 3, 0], // bottom [0, 1, 4], [1, 4, 5], // side A [1, 2, 5], [2, 5, 6], // side B [2, 3, 6], [3, 6, 7], // side C [3, 0, 7], [0, 7, 4], // side D [4, 5, 8], [5, 8, 9], // slope A [5, 6, 9], [6, 9, 10], // slope B [6, 7, 10], [7, 10, 11], // slope C [7, 4, 11], [4, 11, 8], // slope D [8, 9, 10], [10, 11, 8] // top ] ); }; }; </code></pre>
<p>Usually when there's an overlap in two objects during a difference action, F6 render will resolve the problem. There's something more than that involved here, as reducing the height of the cube creates a non-manifold object from the difference. user R..'s answer has merit but is not going to solve the problem.</p> <p>Isolating the cube from the code and exporting the result as an STL allows me to determine that the faces are generated in a manner preventing a proper difference action:</p> <p><a href="https://i.stack.imgur.com/QEtXM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QEtXM.png" alt="meshmixer image" /></a></p> <p>This image from meshmixer shows the faces have inverted normals. The order of the points are critical when describing a polyhedron. From the wiki page for <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language#polyhedron" rel="nofollow noreferrer">OpenSCAD</a>:</p> <blockquote> <p>It is arbitrary which point you start with, but all faces must have points ordered in the same direction . OpenSCAD prefers clockwise when looking at each face from outside inward. The back is viewed from the back, the bottom from the bottom, etc. Another way to remember this ordering requirement is to use the right-hand rule. Using your right-hand, stick your thumb up and curl your fingers as if giving the thumbs-up sign, point your thumb into the face, and order the points in the direction your fingers curl.</p> </blockquote> <p>EDIT: I reversed some of the points, haphazardly and luckily picked the correct ones:</p> <pre><code> faces = [ [0, 1, 2], [2, 3, 0], // bottom [4, 1, 0], [1, 4, 5], // side A [5, 2, 1], [2, 5, 6], // side B [6, 3, 2], [3, 6, 7], // side C [7, 0, 3], [0, 7, 4], // side D [8, 5, 4], [5, 8, 9], // slope A [9, 6, 5], [6, 9, 10], // slope B [10, 7, 6], [7, 10, 11], // slope C [11, 4, 7], [4, 11, 8], // slope D [10, 9, 8], [8, 11, 10] // top </code></pre> <p><a href="https://i.stack.imgur.com/GWBMo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GWBMo.png" alt="rendered code" /></a></p>
<p>If the polyhedron surface and top surface of the cube are exactly coplanar, which they seem to be, it won't work; OpenSCAD operates numerically rather than analytically and which is &quot;inside&quot; or &quot;outside&quot; the other is subject to numerical instability. Whenever using differences you need to make the object being subtracted extend by at least some small epsilon outside the surfact of the object you're subtracting from.</p>
1,784
<p>To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.</p> <p>ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P</p> <p>ETA2: I've now selected a “best answer”; see <a href="https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833">this post</a> for rationale. Thanks to everyone who contributed! :-)</p>
<p>All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all:</p> <pre><code>1 </code></pre> <p>Not kidding. Try it yourself: <a href="http://www.quirkster.com/iano/js/befunge.html" rel="nofollow noreferrer">http://www.quirkster.com/iano/js/befunge.html</a></p> <p>EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language. </p> <p>Using the interpreter provided, you will eventually--and I mean <i>eventually</i>--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster.</p>
<p>Ruby:</p> <pre><code>def i()i()end;i() </code></pre> <p>(17 chars)</p>
8,755
<p>New version of Management Studio (i.e. the one that ships with SQL Server 2008) finally has a Transact-SQL IntelliSense feature. However, out-of-the-box it only works with SQL Server 2008 instances.</p> <p>Is there some workaround for this?</p>
<p>There's no known trick 'in the wild' for getting around this, other than using CTP-6 of SQL Server 2008 (in favour of the RTM).</p> <p>the reasons for removing backward compatability (and a lot more discussion besides) are provided at the <a href="https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=341872" rel="noreferrer">relevant feedback in microsoft connect</a>.</p> <p>edit: sorry i don't know where this ctp is available, if at all</p>
<p>Has anyone tried either patching SSMS not to check the version (perhaps try looking at the binary differences between CTP 6 and RTM?), or patching SS 2005 to pretend to be 2008?</p> <p>Unclean, I know, but I don't see any other way.</p>
2,649
<p>I'm working on getting an Introduction to <a href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29" rel="nofollow noreferrer">Groovy</a> presentation ready for my local Java User's Group and I've pretty much got it together. What I'd like to see is what you all think I just have to cover. </p> <p>Remember, this is an introductory presentation. Most of the people are experienced Java developers, but I'm pretty sure they have little to no Groovy knowledge. I won't poison the well by mentioning what I've already got down to cover as I want to see what the community has to offer.</p> <p>What are the best things I can cover (in a 1 hour time frame) that will help me effectively communicate to these Java developers how useful Groovy could be to them?</p> <p>p.s. I'll share my presentation here later for anyone interested.</p> <p>as promised now that my presentation has been presented <a href="http://docs.google.com/Presentation?id=dhd8kj8d_17cx6gwfch" rel="nofollow noreferrer">here it is</a></p>
<p>I don't know anything about groovy so in a sense I've qualified to answer this...</p> <p>I would want you to:</p> <ul> <li>Tell me why I would want to use Scripting (in general) as opposed to Java-- what does it let me do quicker (as in development time), what does it make more readable. Give tantalising examples of ways I can use chunks of scripting in my mostly Java app. You want to make this relevant to Java devs moreso than tech-junkies.</li> <li>With that out of the way, why Groovy? Why not Ruby, Python or whatever (which are all runnable on the JVM).</li> <li>Don't show me syntax that Java can already do (if statements, loops etc) or if you do make it quick. It's as boring as hell to watch someone walk through language syntax 101 for 20min. <ul> <li>For syntax that has a comparible feature in Java maybe show them side by side quickly.</li> <li>For syntax that is not in Java (closures etc) you can talk to them in a bit more detail.</li> </ul></li> <li>Remember those examples from the first point. Show me one, fully working (or at least looking like it is).</li> <li>At the end have question time. That is <strong>crazy</strong> important, and with that comes a burden on you to be a psuedo-guru :P.</li> </ul> <p>I'm not sure about how the Java6 scripting support works but I'm fairly sure it can be made secure. I remember something about defining the API the script can use before it's run.</p> <p>If this is the case then an example you could show would be some thick-client application (e.g. a music player) where users can write their own scripts with an API you provide them in Groovy which allows them to script their app in interesting and secure ways (e.g. creating custom columns in the playlist)</p>
<p>You should definitely show them how to create a quick Grails application. Two domain classes that are related. Build a basic CRUD app. Explain that tables are being created behind the scenes using GORM(Hibernate). Then explain that you can create a war file and deploy it as you would any other Java war file. You can also add Grails/Groovy to an existing Java/JSP project so it doesn't require a huge commitment or paradigm change. </p> <p>Groovy/Grails is simply Ruby/Rails for Java people. I'd cover the plugins for Netbeans/Eclipse too. Groovy/Grails are just now getting full support in the major IDE's.</p> <p>Finally, if you can find a good diagram that shows how Grails is built on top of Spring, Hibernate, Quartz, Sitemesh and Groovy, I think people will understand that there is a treasure chest waiting to be unlocked.</p>
4,911
<p>We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?</p>
<p>No, it isn't true, you can encode XML to any Writer in Java using something similar to:</p> <pre><code>char[] ch; AttributesImpl atts = new AttributesImpl(); Writer writer = new StringWriter(); StreamResult streamResult = new StreamResult(writer); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); // SAX2.0 ContentHandler TransformerHandler transformerHandler = tf.newTransformerHandler(); Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); transformerHandler.setResult(streamResult); transformerHandler.startDocument(); atts.clear(); // atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes"); // atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance"); // atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd"); transformerHandler.startElement("", "", "node_list", atts); // displayName element if (displayName != null) { transformerHandler.startElement("", "", "display_name", null); ch = displayName.toCharArray(); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "display_name"); } // nodes element transformerHandler.startElement("", "", "nodes", null); atts.clear(); atts.addAttribute("", "", "node_type", "CDATA", "sometype"); transformerHandler.startElement("", "", "node", atts); ch = node.getValue().toCharArray(); transformerHandler.startElement("", "", "value", null); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "value"); transformerHandler.endElement("", "", "node"); transformerHandler.endElement("", "", "nodes"); transformerHandler.endElement("", "", "node_list"); transformerHandler.endDocument(); String xml = writer.toString(); </code></pre>
<p>The SAX handler interfaces were designed to be easy to implement. It's easy to write a class with similar (perhaps wrapping a SAX interface) to make it easy to call - chaining, remembering which element to close, easier attributes, etc.</p>
9,915
<p>I am currently creating a master ddl for our database. Historically we have used backup/restore to version our database, and not maintained any ddl scripts. The schema is quite large.</p> <p>My current thinking:</p> <ul> <li><p>Break script into parts (possibly in separate scripts):</p> <ol> <li>table creation</li> <li>add indexes</li> <li>add triggers</li> <li>add constraints</li> </ol></li> <li><p>Each script would get called by the master script.</p></li> <li>I might need a script to drop constraints temporarily for testing</li> <li>There may be orphaned tables in the schema, I plan to identify suspect tables.</li> </ul> <p>Any other advice?</p> <p>Edit: Also if anyone knows good tools to automate part of the process, we're using MS SQL 2000 (old, I know).</p>
<p>I think the basic idea is good. </p> <p>The nice thing about building all the tables first and then building all the constraints, is that the tables can be created in any order. When I've done this I had one file per table, which I put in a directory called "Tables" and then a script which executed all the files in that directory. Likewise I had a folder for constraint scripts (which did foreign key and indexes too), which were executed when after the tables were built.</p> <p>I would separate the build of the triggers and stored procedures, and run these last. The point about these is they can be run and re-run on the database without affecting the data. This means you can treat them just like ordinary code. You should include "if exists...drop" statements at the beginning of each trigger and procedure script, to make them re-runnable.</p> <p>So the order would be</p> <ol> <li>table creation</li> <li>add indexes</li> <li>add constraints</li> </ol> <p>Then</p> <ol start="4"> <li>add triggers</li> <li>add stored procedures</li> </ol> <p>On my current project we are using MSBuild to run the scripts. There are some <a href="http://www.codeplex.com/sdctasks" rel="noreferrer">extension targets</a> that you can get for it which allow you to call sql scripts. In the past I have used perl which was fine too (and batch files...which I would not recommend - the're too limited).</p>
<p>I previously organised my DDL code organised by one file per entity and made a tool that combined this into a single DDL script.</p> <p>My former employer used a scheme where all table DDL was in one file (stored in oracle syntax), indicies in another, constraints in a third and static data in a fourth. A change script was kept in paralell with this (again in Oracle). The conversion to SQL was manual. It was a mess. I actually wrote a handy tool that will convert Oracle DDL to SQL Server (it worked 99.9% of the time).</p> <p>I have recently switched to using <a href="http://msdn.microsoft.com/en-us/vsts2008/db/default.aspx" rel="nofollow noreferrer">Visual Studio Team System for Database professionals</a>. So far it works fine, but there are some glitches if you use CLR functions within the database.</p>
2,697
<p>I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google &amp; two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for <strong>de</strong>-optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?</p>
<p>You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school.</p> <p>Common FORTRAN-isms I deal with, that hurt readability are:</p> <ul> <li>Common blocks</li> <li>Implicit variables</li> <li>Two or three DO loops with shared CONTINUE statements</li> <li>GOTO's in place of DO loops</li> <li>Arithmetic IF statements</li> <li>Computed GOTO's</li> <li>Equivalence REAL/INTEGER/other in some common block</li> </ul> <p>Strategies for solving these involve:</p> <ol> <li>Get <a href="http://www.polyhedron.com/spag0html" rel="noreferrer">Spag / plusFORT</a>, worth the money, it solves a lot of them automatically and Bug Free(tm)</li> <li>Move to Fortran 90 if at all possible, if not move to free-format Fortran 77</li> <li>Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it)</li> <li>Moving all COMMON blocks to MODULEs, low hanging fruit, worth it</li> <li>Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks</li> <li>Convert computed GOTOs to SELECT CASE blocks</li> <li><p>Convert all DO loops to the newer F90 syntax</p> <pre><code>myloop: do ii = 1, nloops ! do something enddo myloop </code></pre></li> <li><p>Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL</p></li> </ol> <p>If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.</p>
<p>Here's another one that has bit me from time to time. When you are working on FORTRAN code make sure you skip all six initial columns. Every once and a while, I'll only get the code indented five spaces and nothing works. At first glance everything seems okay and then I finally realize that all the lines are starting in column 6 instead of column 7.</p> <p>For anyone not familiar with FORTRAN, the first 5 columns are for line numbers (=labels), the 6th column is for a continuation character in case you have a line longer than 80 characters (just put something here and the compiler knows that this line is actually part of the one before it) and code always starts in column 7.</p>
5,160
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p> <blockquote> <p>1) Is it actually worth taking such things into account?</p> <p>2) Assuming it is worth taking it into account, how do I do this?</p> </blockquote> <p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
<p>If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes. </p> <p>Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.</p> <p>Like this:</p> <pre><code>$ time script.php HI! real 0m3.218s user 0m0.080s sys 0m0.064s </code></pre> <p>It will give you clock time, user time (php interpreter) and sys time (OS time)</p> <p>If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well</p>
<ol> <li><p>It's worth taking speed into account if you're optimizing code. You should generally know why you're optimizing code (as in: a specific task in your existing codebase is taking too long, not "I heard PHP is slower than Python"). It's <em>not</em> worth taking speed into account if you don't actually plan on switching languages. Just because one tiny module does something slightly faster doesn't mean rewriting your app in another language is a good idea. There are many other factors to choosing a language besides speed.</p></li> <li><p>You benchmark, of course. Run the two codebases multiple times and compare the timing. You can use the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?time" rel="nofollow noreferrer">time</a> command if both scripts are executable from the shell, or use respective benchmarking functionality from each language; the latter case depends heavily on the actual language, naturally.</p></li> </ol>
8,743
<p>In analogy to: <a href="https://3dprinting.stackexchange.com/q/6723/4762">What glues for bonding printed PLA to injection-molded plastic?</a>, what are the best glues to use for PETG?</p> <p>I mostly print in PETG and have occasional failed prints which I usually reprint. But what if I'd like to repair a print e.g. a split between layers or a part broken off?</p> <p>Knowing that PETG is more &quot;greasy&quot; than PLA, what typical glues can you use to create a good bond; this question excludes using heat to (re-)bond.</p>
<p>From <a href="https://forum.simplify3d.com/viewtopic.php?t=9281" rel="nofollow noreferrer">forum</a></p> <blockquote> <p>Bison plastic - works great for me, only it's not "quick dry" but it's very strong, not brittle, holds PETG and PLA very strongly. Buy paint stripper that is/contains methylene chloride (dichloromethane). It will solvent weld both PLA and PETG.</p> </blockquote> <p>Or see <a href="https://all3dp.com/2/best-glue-for-plastic-pla-abs-petg-nylon/" rel="nofollow noreferrer">other forum</a> which recommends Eastman-910 (original brand of cyanoacrylate) or any equivalent, polyurethane glue, or even epoxy.</p>
<p>If Carl's answer that cyanoacrylate glue works is accurate, I would suggest Loctite 420 or equivalent. It's diluted with solvents sufficiently to behave as a liquid rather than a gel, and in my experience on PLA it not only bonds the joint, but wicks between the extrusions and bonds walls/layers together much more strongly and waterproofs the part. As long as it bonds to PETG it should do the same for PETG.</p>
1,578
<p>How can I determine if a string is an IP address? Either <em>IPv4</em> or <em>IPv6</em>?</p> <p>What is the least and most number of characters?</p> <p>I assume this would be a <strong>regex</strong> answer.</p>
<p>In .NET there's an IPAddress type which has a handy method <a href="http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx" rel="noreferrer">TryParse</a>.</p> <p>Example: </p> <pre><code>if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){ //validatedIPAddress is good } // or more simply: bool IsValidIPAddress(string possibleIP){ return System.Net.IPAddress.TryParse(PossibleIPAddress, null) } </code></pre>
<p>IPv4 becomes: <code>/\d\d?\d?.\d\d?\d?.\d\d?\d?.\d\d?\d?/</code></p> <p>I'm not sure about the IPv6 rules.</p>
6,379
<p>Are there any free tools that implement evidence-based scheduling like <a href="http://www.joelonsoftware.com/items/2007/10/26.html" rel="nofollow noreferrer">Joel talks about</a>? There is FogBugz, of course, but I am looking for a simple and free tool that can apply EBS on some tasks that I give estimates (and actual times which are complete) for.</p>
<p>FogBugz is free for up to 2 users by the way. As far I know this is the only tool that does EBS.</p> <p>See here <a href="http://www.workhappy.net/2008/06/get-fogbugz-for.html" rel="noreferrer">http://www.workhappy.net/2008/06/get-fogbugz-for.html</a></p>
<p><a href="http://en.wikipedia.org/wiki/Evidence_Based_Scheduling" rel="nofollow noreferrer">According to Wikipedia</a>, Fogbugz is the only product currently offering EBS.</p>
3,035
<p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>
<p>Lambda comes from the <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="noreferrer">Lambda Calculus</a> and refers to anonymous functions in programming.</p> <p>Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.</p> <p><strong>Python</strong></p> <pre class="lang-py prettyprint-override"><code>def adder(x): return lambda y: x + y add5 = adder(5) add5(1) 6 </code></pre> <p>As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.</p> <p><strong>Examples in other languages</strong></p> <p><strong>Perl 5</strong></p> <pre class="lang-pl prettyprint-override"><code>sub adder { my ($x) = @_; return sub { my ($y) = @_; $x + $y } } my $add5 = adder(5); print &amp;$add5(1) == 6 ? "ok\n" : "not ok\n"; </code></pre> <p><strong>JavaScript</strong></p> <pre class="lang-js prettyprint-override"><code>var adder = function (x) { return function (y) { return x + y; }; }; add5 = adder(5); add5(1) == 6 </code></pre> <p><strong>JavaScript (ES6)</strong></p> <pre class="lang-js prettyprint-override"><code>const adder = x =&gt; y =&gt; x + y; add5 = adder(5); add5(1) == 6 </code></pre> <p><strong>Scheme</strong></p> <pre class="lang-scheme prettyprint-override"><code>(define adder (lambda (x) (lambda (y) (+ x y)))) (define add5 (adder 5)) (add5 1) 6 </code></pre> <p><strong><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx" rel="noreferrer">C# 3.5 or higher</a></strong></p> <pre class="lang-cs prettyprint-override"><code>Func&lt;int, Func&lt;int, int&gt;&gt; adder = (int x) =&gt; (int y) =&gt; x + y; // `int` declarations optional Func&lt;int, int&gt; add5 = adder(5); var add6 = adder(6); // Using implicit typing Debug.Assert(add5(1) == 6); Debug.Assert(add6(-1) == 5); // Closure example int yEnclosed = 1; Func&lt;int, int&gt; addWithClosure = (x) =&gt; x + yEnclosed; Debug.Assert(addWithClosure(2) == 3); </code></pre> <p><strong>Swift</strong></p> <pre class="lang-swift prettyprint-override"><code>func adder(x: Int) -&gt; (Int) -&gt; Int{ return { y in x + y } } let add5 = adder(5) add5(1) 6 </code></pre> <p><strong>PHP</strong></p> <pre class="lang-php prettyprint-override"><code>$a = 1; $b = 2; $lambda = fn () =&gt; $a + $b; echo $lambda(); </code></pre> <p><strong>Haskell</strong></p> <pre><code>(\x y -&gt; x + y) </code></pre> <p><strong>Java</strong> see <a href="https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545">this post</a></p> <pre class="lang-java prettyprint-override"><code>// The following is an example of Predicate : // a functional interface that takes an argument // and returns a boolean primitive type. Predicate&lt;Integer&gt; pred = x -&gt; x % 2 == 0; // Tests if the parameter is even. boolean result = pred.test(4); // true </code></pre> <p><strong>Lua</strong></p> <pre class="lang-lua prettyprint-override"><code>adder = function(x) return function(y) return x + y end end add5 = adder(5) add5(1) == 6 -- true </code></pre> <p><strong>Kotlin</strong></p> <pre class="lang-kotlin prettyprint-override"><code>val pred = { x: Int -&gt; x % 2 == 0 } val result = pred(4) // true </code></pre> <p><strong>Ruby</strong></p> <p>Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.</p> <pre class="lang-ruby prettyprint-override"><code>def adder(x) lambda { |y| x + y } end add5 = adder(5) add5[1] == 6 </code></pre> <p>Ruby being Ruby, there is a shorthand for lambdas, so you can define <code>adder</code> this way:</p> <pre><code>def adder(x) -&gt; y { x + y } end </code></pre> <p><strong>R</strong></p> <pre class="lang-r prettyprint-override"><code>adder &lt;- function(x) { function(y) x + y } add5 &lt;- adder(5) add5(1) #&gt; [1] 6 </code></pre>
<p>A lambda function can take any number of arguments, but they contain only a single expression. ... Lambda functions can be used to return function objects. Syntactically, lambda functions are restricted to only a single expression.</p>
3,724
<p>I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. </p> <p>This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. </p> <p>Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)</p> <p>Here is a code snippet:</p> <pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open); long byteNum = fs.Length; byte[] pdfBytes = new byte[byteNum]; fs.Read(pdfBytes, 0, (int)byteNum); Response.AppendHeader("Content-disposition", "filename=Testme.doc"); Response.CacheControl = "no-cache"; Response.ContentType = "application/msword; charset=utf-8"; Response.Expires = -1; Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length); Response.Flush(); Response.Close(); fs.Close(); </code></pre> <p>Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 &amp; IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. </p> <p>IE does provide an advanced setting "Do not save encrypted pages to disk". </p> <p>I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.</p> <p>Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).</p> <p>Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?</p>
<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.</p> <pre><code> Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc"); </code></pre> <p>failing that i've included my code below as I know that works over https://</p> <pre> <code> private void ReadFile(string URL) { try { string uristring = URL; WebRequest myReq = WebRequest.Create(uristring); NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString()); myReq.Credentials = netCredential; StringBuilder strSource = new StringBuilder(""); //get the stream of data string contentType = ""; MemoryStream ms; // Send a request to download the pdf document and then get the response using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse()) { contentType = response.ContentType; // Get the stream from the server using (Stream stream = response.GetResponseStream()) { // Use the ReadFully method from the link above: byte[] data = ReadFully(stream, response.ContentLength); // Return the memory stream. ms = new MemoryStream(data); } } Response.Clear(); Response.ContentType = contentType; Response.AddHeader("Content-Disposition", "attachment;"); // Write the memory stream containing the pdf file directly to the Response object that gets sent to the client ms.WriteTo(Response.OutputStream); } catch (Exception ex) { throw new Exception("Error in ReadFile", ex); } } </code> </pre>
<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.</p> <pre><code> Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc"); </code></pre> <p>failing that i've included my code below as I know that works over https://</p> <pre> <code> private void ReadFile(string URL) { try { string uristring = URL; WebRequest myReq = WebRequest.Create(uristring); NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString()); myReq.Credentials = netCredential; StringBuilder strSource = new StringBuilder(""); //get the stream of data string contentType = ""; MemoryStream ms; // Send a request to download the pdf document and then get the response using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse()) { contentType = response.ContentType; // Get the stream from the server using (Stream stream = response.GetResponseStream()) { // Use the ReadFully method from the link above: byte[] data = ReadFully(stream, response.ContentLength); // Return the memory stream. ms = new MemoryStream(data); } } Response.Clear(); Response.ContentType = contentType; Response.AddHeader("Content-Disposition", "attachment;"); // Write the memory stream containing the pdf file directly to the Response object that gets sent to the client ms.WriteTo(Response.OutputStream); } catch (Exception ex) { throw new Exception("Error in ReadFile", ex); } } </code> </pre>
7,596
<p>Debugging in visual studio seems to have been broken with sp1. Single stepping randomly does not work and just starts to run. Sometimes breakpoints are ignored. It is unpredictable and unusable. It will generally hit the first break point but after that it is totally unpredictable. </p> <p>Any idea what needs to be done to correct this behavior ? </p>
<p>Make sure you are debuging using the debug configuration, not the release one. Also make sure optimizations are disabled in debug configuration.</p> <p>Optimizations must be off when you debug else it can lead to very erratic behaviours like these.</p> <hr> <p>For C# projects, which I am assuming the question is about looking at the tags, the optimization option would be located in the "Build" tab of "Project > Properties..." Last option of "General" it's called "Optimize Code".</p>
<p>We are using c# as a language.</p> <p>The problem has been identified by microsoft.</p> <p>quote from forums:</p> <blockquote> <p>We have identified the root cause of this issue and are currently working on a solution. We apologize for the inconvenience that this is causing you. We will let you know as soon as we have a solution. In the mean time, if we discover any workrounds, we will post them here.</p> </blockquote>
4,305
<p>I'm having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with <code>::</code> or leading zeros omitted from each byte pair). </p> <p>Can someone suggest a regular expression that would fulfill the requirement?</p> <p>I'm considering expanding each byte pair and matching the result with a simpler regex.</p>
<p>I was unable to get @Factor Mystic's answer to work with POSIX regular expressions, so I wrote one that works with POSIX regular expressions and PERL regular expressions.</p> <p>It should match:</p> <ul> <li>IPv6 addresses</li> <li>zero compressed IPv6 addresses (<a href="https://www.rfc-editor.org/rfc/rfc5952#section-2.2" rel="noreferrer">section 2.2 of rfc5952</a>)</li> <li>link-local IPv6 addresses with zone index (<a href="https://www.rfc-editor.org/rfc/rfc4007#section-11" rel="noreferrer">section 11 of rfc4007</a>)</li> <li>IPv4-Embedded IPv6 Address (<a href="https://www.rfc-editor.org/rfc/rfc6052#section-2" rel="noreferrer">section 2 of rfc6052</a>)</li> <li>IPv4-mapped IPv6 addresses (<a href="https://www.rfc-editor.org/rfc/rfc2765#section-2.1" rel="noreferrer">section 2.1 of rfc2765</a>)</li> <li>IPv4-translated addresses (<a href="https://www.rfc-editor.org/rfc/rfc2765#section-2.1" rel="noreferrer">section 2.1 of rfc2765</a>)</li> </ul> <p>IPv6 Regular Expression:</p> <pre><code>(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])) </code></pre> <p>For ease of reading, the following is the above regular expression split at major OR points into separate lines:</p> <pre><code># IPv6 RegEx ( ([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8 ([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7:: ([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8 ([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8 ([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8 ([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8 ([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8 [0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8 :((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index) ::(ffff(:0{1,4}){0,1}:){0,1} ((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3} (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses) ([0-9a-fA-F]{1,4}:){1,4}: ((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3} (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address) ) # IPv4 RegEx ((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) </code></pre> <p>To make the above easier to understand, the following &quot;pseudo&quot; code replicates the above:</p> <pre><code>IPV4SEG = (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) IPV4ADDR = (IPV4SEG\.){3,3}IPV4SEG IPV6SEG = [0-9a-fA-F]{1,4} IPV6ADDR = ( (IPV6SEG:){7,7}IPV6SEG| # 1:2:3:4:5:6:7:8 (IPV6SEG:){1,7}:| # 1:: 1:2:3:4:5:6:7:: (IPV6SEG:){1,6}:IPV6SEG| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8 (IPV6SEG:){1,5}(:IPV6SEG){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8 (IPV6SEG:){1,4}(:IPV6SEG){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8 (IPV6SEG:){1,3}(:IPV6SEG){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8 (IPV6SEG:){1,2}(:IPV6SEG){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8 IPV6SEG:((:IPV6SEG){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8 :((:IPV6SEG){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: fe80:(:IPV6SEG){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index) ::(ffff(:0{1,4}){0,1}:){0,1}IPV4ADDR| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses) (IPV6SEG:){1,4}:IPV4ADDR # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address) ) </code></pre> <p>I posted a script on GitHub which tests the regular expression: <a href="https://gist.github.com/syzdek/6086792" rel="noreferrer">https://gist.github.com/syzdek/6086792</a></p>
<p>The regex allows the use of leading zeros in the IPv4 parts.</p> <p>Some Unix and Mac distros convert those segments into octals.</p> <p>I suggest using <code>25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d</code> as an IPv4 segment.</p>
7,698
<p>I am looking for a <strong>3rd party solution to integrate a <a href="http://en.wikipedia.org/wiki/QR_Code" rel="nofollow noreferrer">QR code</a> reader</strong> in Windows Mobile Applications (.NET Compact Framework). The component should <strong>integrate Reader (camera) and Decoder (algorithm)</strong>.</p> <p>I tried out the <a href="http://www.quickmark.com.tw/En/basic/index.asp" rel="nofollow noreferrer">QuickMark</a> reader, which can be called outside the application and communicates using Windows Messages. It works quiet well, but doesn't give me every option I need (e.g. it has to be installed etc.).</p> <p>Are there other good solutions which I may have missed? Anything Open Source? Tested on different devices?</p>
<p><a href="http://www.codeproject.com/KB/cs/qrcode.aspx" rel="nofollow noreferrer">Here</a> is an open source C# port of the Java QR Code <a href="http://qrcode.sourceforge.jp/" rel="nofollow noreferrer">library</a>.</p>
<p>Did you try this one: <a href="http://webscripts.softpedia.com/script/E-Commerce/QRCode-NET-Compact-Framework-Package--30802.html" rel="nofollow noreferrer">QRCode .NET Compact Framework Package</a> ?</p>
8,754
<p>As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function.<br> I want a way to track allocations like in <a href="http://msdn.microsoft.com/en-us/library/cy8c7wz5.aspx" rel="nofollow noreferrer">_CrtSetAllocHook</a>, but for <code>C#/.NET</code>.<br> The only visibility to the garbage collector/allocation appears to be <a href="http://msdn.microsoft.com/en-us/library/system.gc.collectioncount(VS.80).aspx" rel="nofollow noreferrer">GC.CollectionCount</a>.<br> Anyone have any other .NET memory mojo?</p>
<p>The CLR has a 'profiling API' that hooks into pretty much everything - it is what the commercial .NET memory profiling products use, I believe. Here is an MSDN link to the top level of the documentation: <a href="http://msdn.microsoft.com/en-us/library/bb384547.aspx" rel="noreferrer">.NET Framework General Reference: About the Profiling API</a></p> <p>See this MSDN magazine article for an introduction to the memory piece: <a href="http://msdn.microsoft.com/en-us/magazine/cc188781.aspx" rel="noreferrer">Inspect and Optimize Your Program's Memory Usage with the .NET Profiler API</a></p>
<p>I would just use Red Gate's ANTS Profiler. It will tell you a lot about what's going on in memory without you having to learn the profiling API yourself.</p>
7,318
<p>I have a class to parse a matrix that keeps the result in an array member:</p> <pre><code>class Parser { ... double matrix_[4][4]; }; </code></pre> <p>The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:</p> <pre><code>void api_func(const double matrix[4][4]); </code></pre> <p>The only way I have come up with for the caller to pass the array result to the function is by making the member public:</p> <pre><code>void myfunc() { Parser parser; ... api_func(parser.matrix_); } </code></pre> <p>Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought <code>matrix_</code> would essentially be the same as a <code>double**</code> and I could cast (safely) between the two. As it turns out, I can't even find an <em>unsafe</em> way to cast between the things. Say I add an accessor to the <code>Parser</code> class:</p> <pre><code>void* Parser::getMatrix() { return (void*)matrix_; } </code></pre> <p>This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type:</p> <pre><code> // A smorgasbord of syntax errors... api_func((double[][])parser.getMatrix()); api_func((double[4][4])parser.getMatrix()); api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type </code></pre> <p>The error is:</p> <blockquote> <p>error C2440: 'type cast' : cannot convert from 'void *' to 'const double [4][4]'</p> </blockquote> <p>...with an intriguing addendum:</p> <blockquote> <p>There are no conversions to array types, although there are conversions to references or pointers to arrays</p> </blockquote> <p>I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here.</p> <p>To be sure, at this point the matter is purely academic, as the <code>void*</code> casts are hardly cleaner than a single class member left public!</p>
<p>Here's a nice, clean way:</p> <pre><code>class Parser { public: typedef double matrix[4][4]; // ... const matrix&amp; getMatrix() const { return matrix_; } // ... private: matrix matrix_; }; </code></pre> <p>Now you're working with a descriptive type name rather than an array, but since it's a <code>typedef</code> the compiler will still allow passing it to the unchangeable API function that takes the base type.</p>
<p>I've used a union like this to pass around matrices in the past:</p> <pre><code>union matrix { double dflat[16]; double dmatr[4][4]; }; </code></pre> <p>Then pass a pointer in to your setter and copy the data into the matrix in your class.</p> <p>There are ways of handling this otherwise (that are more generic), but this solution tends to be the cleanest in the end, in my experience.</p>
7,880
<p>Many websites, including this one, add what are apparently called <em>slugs</em> - descriptive but as far as I can tell useless bits of text - to the end of URLs.</p> <p>For example, the URL the site gives for this question is:</p> <p><a href="https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls"><code>https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls</code></a></p> <p>But the following URL works just as well:</p> <p><a href="https://stackoverflow.com/questions/47427/"><code>https://stackoverflow.com/questions/47427/</code></a></p> <p>Is the point of this text just to somehow make the URL more user friendly or are there some other benefits? </p>
<p>The slugs make the URL more user-friendly and you know what to expect when you click a link. Search engines such as Google, rank the pages higher if the searchword is in the URL.</p>
<p>Ideally, the "slug" should be the only identifier needed. In practice, on dynamic sites such as this, you either have to have a unique numerical identifier or start appending/incrementing numbers to the "slug" like Digg does.</p>
6,966
<p>I want to get started on HMM's, but don't know how to go about it. Can people here, give me some basic pointers, where to look?</p> <p>More than just the theory, I like to do a lot of hands-on. So, would prefer resources, where I can write small code snippets to check my learning, rather than just dry text.</p>
<p>Have you tried: Russel and Norvig's Artificial Intelligence: A Modern Approach. </p> <p>I realise that this is heavy on theory, but it also contains useful code samples that can be used to help your learning.</p> <p>You can also check out: <a href="http://www.kanungo.com/software/software.html" rel="nofollow noreferrer">http://www.kanungo.com/software/software.html</a> for a c-implementation of a HMM</p>
<p>Great videos as of Stanford Online AI course are available: See unit 11.</p> <p><a href="https://www.ai-class.com/course/video/videolecture/138" rel="nofollow">https://www.ai-class.com/course/video/videolecture/138</a></p>
9,537
<p>I have to choose an online WYSIWYG editor. I'm pending between <a href="http://tinymce.moxiecode.com/" rel="nofollow noreferrer">TinyMCE</a> and <a href="http://trac.xinha.org/" rel="nofollow noreferrer">Xinha</a>. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons? </p>
<p>Haven't tried Xihna myself, but I have experience with TinyMCE and FCKeditor. In my company we switched to TinyMce (from FCKeditor) due to the superior support for pasting from word documents and the (relatively easy to work with) plugin architecture which we used to add some custom modules (links browser, simple file browser). TinyMCE also converts the text to xhtml code which is usually better. </p>
<p>I've never used Xinha, but I can vouch for TinyMCE. It's fast, scales well, and is infinitely customizable. I particularly like the dynamic loading of functionality, which means you only take the performance hit for the stuff you use.</p> <p>It also includes language-specific <a href="http://wiki.moxiecode.com/index.php/TinyMCE:Compressor" rel="nofollow noreferrer">compressors</a> to further increase performance (C# is supported, along with PHP, Java and ColdFusion) by GZipping components.</p>
7,124
<p>I'm looking at adding scripting functionality to an existing codebase and am weighing up the pros/cons of various packages. Lua is probably the most obvious choice, but I was wondering if people have any other suggestions based on their experience.</p> <p>Scripts will be triggered upon certain events and may stay resident for a period of time. For example upon startup a script may define several options which the program presents to the user as a number of buttons. Upon selecting one of these buttons the program will notify the script where further events may occur.</p> <p>These are the only real requirements;</p> <ol> <li>Must be a cross-platform library that is compilable from source</li> <li>Scripts must be able to call registered code-side functions</li> <li>Code must be able to call script-side functions</li> <li>Be used within a C/C++ codebase.</li> </ol>
<p>Based on my own experience:</p> <ul> <li>Python. IMHO this is a good choice. We have a pretty big code base with a lot of users and they like it a lot.</li> <li>Ruby. There are some really nice apps such as Google Sketchup that use this. I wrote a Sketchup plugin and thought it was pretty nice.</li> <li>Tcl. This is the old-school embeddable scripting language of choice, but it doesn't have a lot of momentum these days. It's high quality though, they use it on the Hubble Space Telescope!</li> <li>Lua. I've only done baby stuff with it but IIRC it only has a floating point numeric type, so make sure that's not a problem for the data you will be working with.</li> </ul> <p>We're lucky to be living in the golden age of scripting, so it's hard to make a bad choice if you choose from any of the popular ones.</p>
<p>There were some excellent suggestions already, but I just wanted to mention that Perl can also be called / can call to C/C++.</p>
3,616
<p>Let's say we have a simple function defined in a pseudo language.</p> <pre><code>List&lt;Numbers&gt; SortNumbers(List&lt;Numbers&gt; unsorted, bool ascending); </code></pre> <p>We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.</p> <p>In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?</p> <p>We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous.</p>
<p>Don't waste too much time trying to think of <em>every</em> boundry condition. Your tests won't be able to catch <em>every</em> bug first time around. The idea is to have tests that are <em>pretty good</em>, and then each time a bug <em>does</em> surface, write a new test specifically for that bug so that you never hear from it again.</p> <p>Another note I want to make about code coverage tools. In a language like C# or Java where your have many get/set and similar methods, you should <strong>not</strong> be shooting for 100% coverage. That means you are wasting too much time writing tests for trivial code. You <em>only</em> want 100% coverage on your complex business logic. If your full codebase is closer to 70-80% coverage, you are doing a good job. If your code coverage tool allows multiple coverage metrics, the best one is 'block coverage' which measures coverage of 'basic blocks'. Other types are class and method coverage (which don't give you as much information) and line coverage (which is too fine grain).</p>
<p>A good code coverage tool really helps.</p> <p>100% coverage doesn't mean that it definitely is adequately tested, but it's a good indicator.</p> <p>For .Net NCover's quite good, but is no longer open source.</p> <hr> <p>@Mike Stone - Yeah, perhaps that should have been "high coverage" - we aim for 80% minimum, past about 95% it's usually diminishing returns, especially if you have belt 'n' braces code.</p>
3,359
<p>Right now, I'm particularly interested in reading the data from MP3 files (ID3 tags?), but the more it can do (eg EXIF from images?) the better without compromising the ID3 tag reading abilities.</p> <p>I'm interested in making a script that goes through my media (right now, my music files) and makes sure the file name and directory path correspond to the file's metadata and then create a log of mismatched files so I can check to see which is accurate and make the proper changes. I'm thinking Ruby or Python (see <a href="https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python">a related question specifically for Python</a>) would be best for this, but I'm open to using any language really (and would actually probably prefer an application language like C, C++, Java, C# in case this project goes off).</p>
<p>There is a great post on using PowerShell and TagLibSharp on Joel "Jaykul" Bennet's <a href="http://huddledmasses.org/editing-media-tags-from-powershell/" rel="nofollow noreferrer">site</a>. You could use TagLibSharp to read the metatdata with any .NET based language, but PowerShell is quite appropriate for what you are trying to do.</p>
<p>@Thomas Owens PowerShell is now part of the Common Engineering Criteria (as of Microsoft's 2009 Product Line) and starting with Serve 2008 is included as a feature. It stands as much of a chance to be installed as Python or Ruby. You also mentioned that you were willing to go to C#, which could use TagLibSharp. Or you could use IronPython...</p>
4,828
<p>The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.</p> <p>Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.</p> <pre><code>using System; using Microsoft.Win32; namespace HowTo { class WebClickSound { /// &lt;summary&gt; /// Enables or disables the web browser navigating click sound. /// &lt;/summary&gt; public static bool Enabled { get { RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current"); string keyValue = (string)key.GetValue(null); return String.IsNullOrEmpty(keyValue) == false &amp;&amp; keyValue != "\"\""; } set { string keyValue; if (value) { keyValue = "%SystemRoot%\\Media\\"; if (Environment.OSVersion.Version.Major == 5 &amp;&amp; Environment.OSVersion.Version.Minor &gt; 0) { // XP keyValue += "Windows XP Start.wav"; } else if (Environment.OSVersion.Version.Major == 6) { // Vista keyValue += "Windows Navigation Start.wav"; } else { // Don't know the file name so I won't be able to re-enable it return; } } else { keyValue = "\"\""; } // Open and set the key that points to the file RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, keyValue, RegistryValueKind.ExpandString); isEnabled = value; } } } } </code></pre> <p>Then in the main form we use the above code in these 3 events: </p> <ul> <li>Activated </li> <li>Deactivated </li> <li><p>FormClosing</p> <pre><code>private void Form1_Activated(object sender, EventArgs e) { // Disable the sound when the program has focus WebClickSound.Enabled = false; } private void Form1_Deactivate(object sender, EventArgs e) { // Enable the sound when the program is out of focus WebClickSound.Enabled = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Enable the sound on app exit WebClickSound.Enabled = true; } </code></pre></li> </ul> <p>The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.</p> <p>What do you guys think? Is this a good solution? What improvements can be made?</p>
<p>I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.</p> <p>So instead of this:</p> <pre><code>webBrowser1.DocumentText = "&lt;h1&gt;Hello, world!&lt;/h1&gt;"; </code></pre> <p>try this:</p> <pre><code>webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write("&lt;h1&gt;Hello, world!&lt;/h1&gt;"); </code></pre>
<p>Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet.</p> <p>Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead. (Can you tell that I was dealing with this problem back in the days before the term "AJAX" was coined?)</p>
3,163
<p>I need to build something that starts serving a H.264 encoded video to a flash player halfway through the file (to support skipping to a point in the video that has not been buffered yet). </p> <p>Currently, the videos are in the FLV container format, but transcoding is an option. I managed to re-write the file header and metadata information for a given byte offset. This works for older videos, but not for H.264 encoded files. I suspect this is because the video tags inside the file also have to be altered, which is not feasible (it would take too much processing power).</p> <p>What is the "proper" way to do it?</p>
<p>The flash player can only start playing H.264 video once it's downloaded the MOOV atom. Existing pseudo-streaming providers just give you an FLV header - either the first 13 bytes of the file or a hardcoded one - and then serve the file from the given offset. If you want to make an H.264 pseudo-streamer, you'll need to have it output the FLV header, then a MOOV atom, and then serve the rest of the file from the given offset. If you don't use an FLV container, you won't need the FLV header, but you'll still need the MOOV atom.</p> <p>Unfortunatley, I don't think you'll be able to use the MOOV atom from the file on disk; the information it contains won't be right for the file fragment that you serve. So you'd have to parse the existing atom and generate one of your own which was appropriate to the served part of the file. </p> <p>If there are complicated structures within the H.264 file it could be even more complicated to pseudo-stream. If parsing the file isn't feasible, I'm afraid you may not be able to pseudo-stream your media.</p>
<p>two things you can do:</p> <p>1) use lighttpd and it's mp4 streaming plug-in that'll generate the required streaming container on the fly</p> <p>2) create a keyframed FLV and use a psuedo-streaming script (like XMOOV) to stream your file.</p> <p>if you need mp4/aac you can just put them inside the FLV container, much to adobe's chagrin, but it works.</p>
8,740
<p>In relation to this question on <a href="https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows">Using OpenGL extensions</a>, what's the purpose of these extension functions? Why would I want to use them? Further, are there any tradeoffs or gotchas associated with using them?</p>
<p>The OpenGL standard allows individual vendors to provide additional functionality through extensions as new technology is created. Extensions may introduce new functions and new constants, and may relax or remove restrictions on existing OpenGL functions. </p> <p>Each vendor has an alphabetic abbreviation that is used in naming their new functions and constants. For example, NVIDIA's abbreviation (NV) is used in defining their proprietary function glCombinerParameterfvNV() and their constant GL_NORMAL_MAP_NV.</p> <p>It may happen that more than one vendor agrees to implement the same extended functionality. In that case, the abbreviation EXT is used. It may further happen that the Architecture Review Board "blesses" the extension. It then becomes known as a standard extension, and the abbreviation ARB is used. The first ARB extension was GL_ARB_multitexture, introduced in version 1.2.1. Following the official extension promotion path, multitexturing is no longer an optionally implemented ARB extension, but has been a part of the OpenGL core API since version 1.3.</p> <p>Before using an extension a program must first determine its availability, and then obtain pointers to any new functions the extension defines. The mechanism for doing this is platform-specific and libraries such as GLEW and GLEE exist to simplify the process.</p>
<p><strong>OpenGL Extensions</strong> are new features added to the <strong>OpenGL specification</strong>, they are added by the OpenGL standards body and by the various graphics card vendors. These are exposed to the programmer as new function calls or variables. Every new version of the OpenGL specification ships with newer functionality and (typically) includes all the previous functionality and extensions.</p> <p>The real problem with OpenGL extensions exists only on Windows. Microsoft hasn't supported any extensions that have been released after <em>OpenGL v1.1</em>. The graphics card vendors overcome this by shipping their own version of this functionality through header files and libraries. However, using this can be a bit painful as the question you linked to shows. But this problem has mostly gone away with the popularity of <strong>GLEW</strong>, which takes care of wrapping all this into a easy-to-use package.</p> <p>If you do use a very recent OpenGL extension, be aware that it may not be supported on older graphics hardware. Other than this, there's no other disadvantage to using these extensions. Most of the extensions which become standard are pretty darn <em>useful</em> and there's very little logic to not use them.</p>
3,801
<p>What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.</p> <p>I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.</p> <p>What can I be doing better in my PHP development?</p>
<p>You don't need a "system" to do templating. You can do it on your own by keeping presentation &amp; logic separate. This way the designer can screw up the display, but not the logic behind it.</p> <p>Here's a simple example:</p> <pre><code>&lt;?php $people = array('derek','joel','jeff'); $people[0] = 'martin'; // all your logic goes here include 'templates/people.php'; ?&gt; </code></pre> <p>Now here's the people.php file (which you give your designer):</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;?php foreach($people as $name):?&gt; &lt;b&gt;Person:&lt;/b&gt; &lt;?=$name?&gt; &lt;br /&gt; &lt;?php endforeach;?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>There's a lot that can be said on this topic but a very basic starting point would be to move as much code as possible out into separate files and then use include statements.</p>
5,703
<p>How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> and C#.</p> <p>I'd like to be able to support any <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation.</p> <p>By <em>"changes to a table"</em> I mean changes to table data, not changes to table structure.</p> <p>Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval.</p> <hr> <p>The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the <code>BINARY_CHECKSUM</code> function in <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a>. The way I plan to implement is this:</p> <p>Every X seconds run the following query:</p> <pre><code>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); </code></pre> <p>And compare that against the stored value. If the value has changed, go through the table row by row using the query:</p> <pre><code>SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); </code></pre> <p>And compare the returned checksums against stored values.</p>
<p>Take a look at the CHECKSUM command:</p> <pre><code>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); </code></pre> <p>That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa258245(SQL.80).aspx" rel="noreferrer">CHECKSUM</a></p> <p>Here's how I used it to rebuild cache dependencies when tables changed:<br> <a href="http://weblogs.asp.net/jgalloway/archive/2005/05/07/406056.aspx" rel="noreferrer">ASP.NET 1.1 database cache dependency (without triggers)</a></p>
<p>Check the last commit date. Every database has a history of when each commit is made. I believe its a standard of ACID compliance.</p>
2,242
<p>I have a very large cascading menu system with over 300 items in it. <em>(I know it's large but it's a requirement.)</em><br> Currently, it's written in javascript so the external file is cached by browsers. </p> <p>To improve search engine results I need to convert this to a css menu system.<br> I realize the browsers will also cache external stylesheets but, </p> <ul> <li>is there a way to cache the menu content (<code>&lt;ul&gt;</code> and <code>&lt;li&gt;</code> tags)? </li> </ul> <p>If I use javascript (<code>document.write</code>) to write the content I could have this in an external javascript file, which would be cached locally, but,</p> <ul> <li>would this be search engine friendly? </li> </ul> <p>What is the best solution?</p>
<p>The best way to accomplish what you want to do is using <a href="https://www.google.com/webmasters/tools/docs/en/protocol.html" rel="nofollow noreferrer">SiteMaps</a> to inform Google about the urls for your web site. Basically you will want to translate your hierarchial data for the menus into a SiteMap.</p>
<p>You could generate the menus beforehand into static html / javascript files, and have all the pages pull the site from the same URL on your site. That way, the client side browser will do the caching. You'll just have to have a step in your deployment that generates the html files for the menu.</p> <p>Try to have it generate as much plain HTML (+JS +CSS) as possible, then whatever has to be dynamic can be adjusted with javascript.</p>
7,958
<p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p> <p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p> <p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p> <p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>
<p>You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow. </p> <pre><code> using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class ExampleEventArgs : EventArgs { public int IntArg {get; set;} } class EventRaiser { public event EventHandler SomethingHappened; public event EventHandler&lt;ExampleEventArgs&gt; SomethingHappenedWithArg; public void RaiseEvents() { if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty); if (SomethingHappenedWithArg!=null) { SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5}); } } } class Handler { public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");} public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg); } } static class EventProxy { //void delegates with no parameters static public Delegate Create(EventInfo evt, Action d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, EventArgs x1) =&gt; d() var parameters = eventParams.Select(p=&gt;Expression.Parameter(p.ParameterType,"x")); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke")); var lambda = Expression.Lambda(body,parameters.ToArray()); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //void delegate with one parameter static public Delegate Create&lt;T&gt;(EventInfo evt, Action&lt;T&gt; d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, ExampleEventArgs x1) =&gt; d(x1.IntArg) var parameters = eventParams.Select(p=&gt;Expression.Parameter(p.ParameterType,"x")).ToArray(); var arg = getArgExpression(parameters[1], typeof(T)); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg); var lambda = Expression.Lambda(body,parameters); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //returns an expression that represents an argument to be passed to the delegate static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType) { if (eventArgs.Type==typeof(ExampleEventArgs) &amp;&amp; handlerArgType==typeof(int)) { //"x1.IntArg" var memberInfo = eventArgs.Type.GetMember("IntArg")[0]; return Expression.MakeMemberAccess(eventArgs,memberInfo); } throw new NotSupportedException(eventArgs+"-&gt;"+handlerArgType); } } static class Test { public static void Main() { var raiser = new EventRaiser(); var handler = new Handler(); //void delegate with no parameters string eventName = "SomethingHappened"; var eventinfo = raiser.GetType().GetEvent(eventName); eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent)); //void delegate with one parameter string eventName2 = "SomethingHappenedWithArg"; var eventInfo2 = raiser.GetType().GetEvent(eventName2); eventInfo2.AddEventHandler(raiser,EventProxy.Create&lt;int&gt;(eventInfo2,handler.HandleEventWithArg)); //or even just: eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=&gt;Console.WriteLine("!"))); eventInfo2.AddEventHandler(raiser,EventProxy.Create&lt;int&gt;(eventInfo2,i=&gt;Console.WriteLine(i+"!"))); raiser.RaiseEvents(); } } </code></pre>
<p>Do you mean something like:</p> <pre><code>//reflect out the method to fire as a delegate EventHandler eventDelegate = ( EventHandler ) Delegate.CreateDelegate( typeof( EventHandler ), //type of event delegate objectWithEventSubscriber, //instance of the object with the matching method eventSubscriberMethodName, //the name of the method true ); </code></pre> <p>This doesn't do the subscription, but will give to the method to call.</p> <p>Edit: </p> <p>Post was clarified after this answer, my example won't help if you don't know the type. </p> <p>However all events in .Net should follow the default event pattern, so as long as you've followed it this will work with the basic EventHandler.</p>
6,777
<p>That's my first 3d printer. I'm using Repetier Host as the brand recomends, and set all the configuration as the recommended one. I decided to print one STL file but the result is not the best one. That's what I was trying to print: <a href="https://i.stack.imgur.com/f1V22.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f1V22.jpg" alt="handle"></a> and that's what I've got. <a href="https://i.stack.imgur.com/iPEfT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iPEfT.jpg" alt="cr*p print"></a> Here you have a video of the impression. <a href="https://www.youtube.com/watch?v=HDdBQL44R3M" rel="nofollow noreferrer">it is a G2S pro rostock mini</a></p>
<p>From the video it is very clear there is <strong>a major problem with bed adhesion</strong>.</p> <p>It also looks like you are printing on bare metal (aluminium?) which I never saw anybody doing. I must admit I don't know it is impossible or simply very rare, but the first thing I would try in your case is <strong><a href="https://youtu.be/G2wAsP1biFc" rel="nofollow noreferrer">covering the bed in painter's tape</a> and wipe it with some alcohol</strong>. This is a surefire method to get good adhesion with PLA, which - from the temperatures shown in the video I assume is what you are using.</p> <p>If you haven't tried this before, you should know that:</p> <ul> <li>some brands of tape work well even without being wiped with alcohol</li> <li>you may need to readjust your nozzle height after having applied the tape</li> </ul> <p>Unless you have already done this, I would also suggest to print some <a href="https://www.thingiverse.com/thing:1278865" rel="nofollow noreferrer">test cubes</a> and possibly some <a href="http://www.3dbenchy.com/" rel="nofollow noreferrer">stress tests</a> as your first prints, in order to check that the basics (extrusion rate, dimensional accuracy...) are working correctly, as well as getting familiar with the limitats of your printer.</p>
<p>I would suggest buying Buildtak, which is a high-quality adhesion surface. This surface is almost guaranteed to make your prints stick to your bed. If Buildtak is outside of your budget, I would suggest using a relatively high grade painters tape combined with either purple gluestick or hairspray applied to your bed before each print.</p>
818
<p>What tools are people using for testing SQL Server databases?</p> <p>By this I mean all parts of the database:</p> <ul> <li>configuration</li> <li>tables</li> <li>column type</li> <li>stored procedures</li> <li>constraints</li> </ul> <p>Most likely, there is not one tool to do it all.</p>
<p>How do you mean "Test the database"? </p> <p>If you are testing foreign keys, a simply script to insert invalid data is all you should need.</p> <p>Testing a database could imply a great number of issues. Does it have all the tables? Are the tables correct? Are the indexes in place? Did the latest updates get applied? Has the data been migrated? Is the even valid? Are the foreign keys correct?</p> <p>There is a lot to test in a database so you are unlikely to find a simple way to test it. I find that a combination of test stored procedures and some Nunit unit tests do most of the vetting of my databases.</p>
<p>I personally use NHibernate with SqlCe, this provides a "throw-away" database that doesn't need any specialized tear down after the tests are run.</p> <p>It also provides a good way to test your nhibernate mappings if applicable.</p> <p>Here is a link to an article I wrote awhile ago on how to accomplish this: <a href="http://www.codeproject.com/KB/database/TDD_and_SqlCE.aspx?display=Print" rel="nofollow noreferrer">http://www.codeproject.com/KB/database/TDD_and_SqlCE.aspx?display=Print</a></p>
4,758
<p>What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0 </p>
<p>If you're using .Net 2 then the XmlReader and XmlDocument are about it.</p> <p>If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement.</p>
<p>I haven't benched-marked it myself, but when I've asked about it in the past I've been told that XmlDocument is supposed to be faster. I have my doubts, though, since XmlDocument would need to create a DOM while XmlReader does not.</p>
6,340
<p>I want something that looks like a file handle but is really backed by an in-memory buffer to use for I/O redirects. How can I do this?</p>
<p>I just wrote a library which provides this, called "knob" [<a href="http://hackage.haskell.org/package/knob">hackage</a>]. You can use it to create <code>Handle</code>s which reference/modify a <code>ByteString</code>:</p> <pre><code>import Data.ByteString (pack) import Data.Knob import System.IO main = do knob &lt;- newKnob (pack []) h &lt;- newFileHandle knob "test.txt" WriteMode hPutStrLn h "Hello world!" hClose h bytes &lt;- Data.Knob.getContents knob putStrLn ("Wrote bytes: " ++ show bytes) </code></pre>
<p>It's not possible without modifying the compiler. This is because Handle is an abstract data type, not a typeclass.</p>
8,547
<p>What kind of execution rate do you aim for with your unit tests (# test per second)? How long is too long for an individual unit test? </p> <p>I'd be interested in knowing if people have any specific thresholds for determining whether their tests are too slow, or is it just when the friction of a long running test suite gets the better of you? </p> <p>Finally, when you do decide the tests need to run faster, what techniques do you use to speed up your tests?</p> <p><em>Note: integration tests are obviously a different matter again. We are strictly talking unit tests that need to be run as frequently as possible.</em></p> <hr> <p><strong>Response roundup:</strong> Thanks for the great responses so far. Most advice seems to be don't worry about the speed -- concentrate on quality and just selectively run them if they are too slow. Answers with specific numbers have included aiming for &lt;10ms up to 0.5 and 1 second per test, or just keeping the entire suite of commonly run tests under 10 seconds. </p> <p>Not sure whether it's right to mark one as an "accepted answer" when they're all helpful :)</p>
<p>All unit tests should run in under a second (that is all unit tests combined should run in 1 second). Now I'm sure this has practical limits, but I've had a project with a 1000 tests that run this fast on a laptop. You'll really want this speed so your developers don't dread refactoring some core part of the model (i.e., Lemme go get some coffee while I run these tests...10 minutes later he comes back). </p> <p>This requirement also forces you to design your application correctly. It means that your domain model is pure and contains zero references to any type of persistance (File I/O, Database, etc). Unit tests are all about testing those business relatonships.</p> <p>Now that doesn't mean you ignore testing your database or persistence. But these issues are now isolated behind repositories that can be separately tested with integration tests that is located in a separate project. You run your unit tests constantly when writing domain code and then run your integration tests once on check in.</p>
<p>I judge my unit tests on a per test basis, not by by # of tests per second. The rate I aim for is 500ms or less. If it is above that, I will look into the test to find out why it is taking so long.</p> <p>When I think a test is to slow, it usually means that it is doing too much. Therefore, just refactoring the test by splitting it up into more tests usually does the trick. The other times that I have noticed my tests running slow is when the test shows a bottleneck in my code, then a refactoring of the code is in order.</p>
3,168
<p>When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine <code>(file:///)</code> then where should the <code>css</code> file be for the browser to find it?</p> <pre><code>&lt;link href="/temp/test.css" rel="stylesheet" type="text/css" /&gt; </code></pre>
<p>You <i>can</i>, but probably don't want to, set the document root on a per-file basis in the head of your file:</p> <pre> &lt;base href="my-root"&gt; </pre>
<p>Eric, the document root is the folder in which your file is, wherever it may be.</p>
3,943
<p>One of the things that has been talked about a few times on the podcast is whether menu items should always be enabled to prevent "WHY ISN'T THIS AVAILABLE!" frustration for the end user.</p> <p>This strikes me as a good idea, but then there's the issue of communicating the lack of availability (and the reason why) to the user. Is there anything better than just popping up a message box with a blurb of text?</p> <p>As I'm about to start on a fairly sizeable cross-platform Windows / Mac app I thought I'd throw this out to hear the wisdom of the SO crowd.</p>
<p>One thing I've seen a printer manufacturer do with their printer properties dialog is to have a little help baloon icon beside disabled items that display a tooltip when hovered over.</p> <p>Another thing you can do with disabled items is to add in parenthesis why it's disabled or what the user would have to do to enable it. E.g., "Save (already saved)" or "Copy (select something to copy)".</p> <p>I don't like keeping it enabled because then it will instill hesitation in users to select <em>any</em> menu item in fear that they'll just get an error message making them feel stupid for not realizing that they couldn't <em>possibly</em> perform that operation at the time. </p> <p>Menu items that spring dialogs have elipsis (...) after them to let users know it's not just click and carry on. Required form fields have an asterisk or bold label to spare the user from being scolded with a validation error message.</p>
<p>Joel has a post on that <a href="http://www.joelonsoftware.com/items/2008/07/01.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/items/2008/07/01.html</a> which might be a good place to start thinking about this.</p>
3,959
<p>I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security?</p> <p>If it matters to you, I'm using MySQL 5.x.</p>
<p>You could use this as a rough "ruleset":</p> <p><strong>YES</strong>, use persistent connections, if:</p> <ul> <li>There are only few applications/users accessing the database, i.e. you will not result in 200 open (but probably idle) connections, because there are 200 different users shared on the same host.</li> <li>The database is running on another server that you are accessing over the network</li> <li>An (one) application accesses the database very often</li> </ul> <p><strong>NO</strong>, don't use persistent connections, if:</p> <ul> <li>Your application only needs to access the database 100 times an hour. </li> <li>You have many webservers accessing one database server</li> <li>You're using Apache in prefork mode. It uses one connection for each child process, which can ramp up fairly quickly. (via @Powerlord in the comments)</li> </ul> <p>Using persistent connections is considerable faster, especially if you are accessing the database over a network. It doesn't make so much difference if the database is running on the same machine, but it is still a little bit faster. However - as the name says - the connection is persistent, i.e. it stays open, even if it is not used.</p> <p>The problem with that is, that in "default configuration", MySQL only allows 1000 parallel "open channels". After that, new connections are refused (You can tweak this setting). So if you have - say - 20 Webservers with each 100 Clients on them, and every one of them has just one page access per hour, simple math will show you that you'll need 2000 parallel connections to the database. That won't work. </p> <p>Ergo: Only use it for applications with lots of requests.</p>
<p>I was going to ask this same question but rather than ask the same question again I'll just add some information that I've found.</p> <ul> <li><a href="http://www.mysqlperformanceblog.com/2006/11/12/are-php-persistent-connections-evil/" rel="nofollow noreferrer">Are PHP persistent connections evil ?</a></li> <li><a href="http://us2.php.net/manual/en/features.persistent-connections.php" rel="nofollow noreferrer">Persistent Database Connections</a></li> </ul> <p>It is also worth noting that the newer mysqli extension does not even include the option to use persistent database connections.</p> <p>I'm still using persitent connections at the moment but plan to switch to non-persistent in the near future.</p>
7,301
<p>Currently I have two Linux servers running MySQL, one sitting on a rack right next to me under a 10 Mbit/s upload pipe (main server) and another some couple of miles away on a 3 Mbit/s upload pipe (mirror).</p> <p>I want to be able to replicate data on both servers continuously, but have run into several roadblocks. One of them being, under MySQL master/slave configurations, every now and then, some statements drop (!), meaning; some people logging on to the mirror URL don't see data that I know is on the main server and vice versa. Let's say this happens on a meaningful block of data once every month, so I can live with it and assume it's a "lost packet" issue (i.e., god knows, but we'll compensate).</p> <p>The other most important (and annoying) recurring issue is that, when for some reason we do a major upload or update (or reboot) on one end and have to <a href="http://en.wiktionary.org/wiki/sever" rel="noreferrer">sever</a> the link, then LOAD DATA FROM MASTER doesn't work and I have to manually dump on one end and upload on the other, quite a task nowadays moving some .5 TB worth of data.</p> <p>Is there software for this? I know MySQL (the "corporation") offers this as a VERY expensive service (full database replication). What do people out there do? The way it's structured, we run an automatic failover where if one server is not up, then the main URL just resolves to the other server. </p>
<p>We at Percona offer free tools to detect discrepancies between master and server, and to get them back in sync by re-applying minimal changes.</p> <ul> <li><a href="http://www.percona.com/doc/percona-toolkit/pt-table-checksum.html" rel="nofollow">pt-table-checksum</a></li> <li><a href="http://www.percona.com/doc/percona-toolkit/pt-table-sync.html" rel="nofollow">pt-table-sync</a></li> </ul>
<p><a href="http://www.goldengate.com/" rel="nofollow noreferrer">GoldenGate</a> is a very good solution, but probably as expensive as the MySQL replicator.</p> <p>It basically tails the journal, and applies changes based on what's committed. They support bi-directional replication (a hard task), and replication between heterogenous systems.</p> <p>Since they work by processing the journal file, they can do large-scale distributed replication without affecting performance on the source machine(s).</p>
2,583
<p>I have a repeater that is bound to some data.</p> <p>I bind to the <strong>ItemDataBound</strong> event, and I am attempting to <strong>programmatically</strong> create a <strong>UserControl</strong>:</p> <p>In a nutshell:</p> <pre><code>void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e) { CCTask task = (CCTask)e.Item.DataItem; if (task is ExecTask) { ExecTaskControl foo = new ExecTaskControl(); e.Item.Controls.Add(foo); } } </code></pre> <p>The problem is that while the binding works, the user control is not rendered to the main page.</p>
<p>Eh, figured out one way to do it:</p> <pre><code>ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\ExecTaskControl.ascx"); </code></pre> <p>It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.</p>
<p>I think that @Craig is on the right track depending on the details of the problem you are solving. Add it to the repeater and remove it or set Visible="false" to hide it where needed. Viewstate gets tricky with dynamically created controls/user controls, so google that or check <a href="http://www.aspnet4you.com/articles.aspx?articleid=5032" rel="nofollow noreferrer">here</a> if you must add dynamically. The article referenced also shows an alternative way to load dynamically:</p> <blockquote> <p>Control ctrl=this.LoadControl(Request.ApplicationPath +"/Controls/" +ControlName);</p> </blockquote>
4,874
<p>How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.<p> I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range. <p>For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:</p> <pre><code>select sum(n) from numbers where n between 100 and 200 </code></pre> <p>Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.</p> <p>[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. <a href="https://stackoverflow.com/questions/58429/sql-set-based-range#59657">See below.</a></p>
<p>I think the very short answer to your question is to use WITH clauses to generate your own.</p> <p>Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a <strong>huge</strong> failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.</p> <p>So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.</p> <p>Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them "common table expressions", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like...</p> <p>In Oracle SQL:</p> <pre><code>WITH digits AS -- Limit recursion by just using it for digits. (SELECT LEVEL - 1 AS num FROM DUAL WHERE LEVEL &lt; 10 CONNECT BY num = (PRIOR num) + 1), numrange AS (SELECT ones.num + (tens.num * 10) + (hundreds.num * 100) AS num FROM digits ones CROSS JOIN digits tens CROSS JOIN digits hundreds WHERE hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed. SELECT -- Some columns and operations FROM numrange -- Join to other data if needed </code></pre> <p>This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.</p> <p>I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know.</p> <p>At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data.</p> <p><strong>UPDATE:</strong> I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven <a href="http://en.wikipedia.org/wiki/Declarative_programming_language" rel="nofollow noreferrer">declarative language</a>. Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.</p>
<p>If using SQL Server 2000 or greater, you could use the <strong>table datatype</strong> to avoid creating a normal or temporary table. Then use the normal table operations on it.</p> <p>With this solution you have essentially a table structure in memory that you can use almost like a real table, but much more performant.</p> <p>I found a good discussion here: <a href="http://www.odetocode.com/articles/365.aspx" rel="nofollow noreferrer">Temporary tables vs the table data type</a></p>
8,277
<p>Which way do you prefer to create your forms in MVC?</p> <pre><code>&lt;% Html.Form() { %&gt; &lt;% } %&gt; </code></pre> <p>Or</p> <pre><code>&lt;form action="&lt;%= Url.Action("ManageImage", "UserAccount") %&gt;" method="post"&gt; &lt;/form&gt; </code></pre> <p>I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. </p> <p>What is your take?</p>
<p>The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.</p>
<p>The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code. </p> <p>For example, I <a href="http://andrewpeters.net/2008/08/21/nhaml-block-methods-and-restful-helpers/" rel="nofollow noreferrer">blogged</a> about some RESTful NHaml helpers that can build urls based on a model.</p>
6,372
<p>(This is a followup to my <a href="https://stackoverflow.com/questions/42468/how-do-i-measure-bytes-inout-of-an-ip-port-used-for-net-remoting">previous question</a> about measuring .NET remoting traffic.)</p> <p>When I am testing our Windows service / service controller GUI combination, it is often most convenient to run both pieces on my development box. With this setup, the remoting traffic between the two is via loopback, not through the Ethernet card.</p> <p>Are there any software packet sniffers that can capture loopback traffic on a WinXP machine? <a href="http://www.wireshark.org/" rel="nofollow noreferrer">Wireshark</a> is a great package, but it can only capture external traffic on a Windows machine, not loopback.</p>
<p>What you should do is to run RawCap, which is a sniffer that can capture traffic to/from the loopback interface in Windows. Just start it with "RawCap.exe 127.0.0.1 loopback.pcap".</p> <p>You can then open up loopback.pcap in Wireshark or <a href="http://www.netresec.com/?page=NetworkMiner" rel="noreferrer">NetworkMiner</a> to look at the network traffic.</p> <p>You can find RawCap here: <a href="http://www.netresec.com/?page=RawCap" rel="noreferrer">http://www.netresec.com/?page=RawCap</a></p> <p>Good Luck!</p>
<p>You should definitely try Npcap, it works perfectly with Wireshark to capture loopback traffic in Windows, see here: <a href="https://wiki.wireshark.org/CaptureSetup/Loopback" rel="nofollow">https://wiki.wireshark.org/CaptureSetup/Loopback</a></p>
6,848
<p>I'd like to buy a 3D printer and use it as a &quot;platform&quot; for an <strong>external</strong> optical sensor. The idea is to mount an optical sensor on the Z-axis and to put a workpiece on the X-Y table. Now, I'd like to move the sensor across the workpiece and trigger the measurement of the optical sensor. Hence, the 3D printer is not actually printing, but only used as a motion and trigger device for the optical sensors.</p> <p>I have never used a 3D printer, but I'm afraid that I'll run into several problems:</p> <ol> <li>The standard G-code of &quot;wait one second&quot; is <code>G04 X1</code> on many CNC machines. Does this code exist on 3D printers as well?</li> <li>Is it possible to extract a trigger signal (e.g. 5 V) from the 3D printer? Are printers available which provide a G-code for an external trigger? Could anybody suggest a model? I'm happy to pay some extra dollars if I don't have to solder by myself. Of course, a second option would be to use the voltage, which is used to heat the filament.</li> </ol>
<p>A flexible material, such as PETG or ABS, is probably the best. PLA is brittle, especially after absorbing moisture, and probably would crack under continued use.</p> <p>Nylon is good, but not easy to use. With PETG in an enclosure, I end up running fans to avoid heat creep; so PETG may actually do better without an enclosure.</p> <p>If you're printing to flex your print, keep in mind the the x and y axes are stronger than the z-axis, which depends on how well the layers stick together. PETG tends to stick to the print surface too well; so I use an Elmer's glue stick for it to pull up the glue layer instead of damaging my print surface.</p>
<p>PETG, ABS and NYLON would work great for press-fit or snap-fit connections. If you really can't build a (cardboard) enclosure I would go for PETG as it has good repeatable mechanical properties and does not require an enclosure.</p>
1,905
<p>For more information - <a href="http://en.wikipedia.org/wiki/Personal_Software_Process" rel="noreferrer">Personal Software Process on Wikipedia</a> and <a href="http://en.wikipedia.org/wiki/Team_Software_Process" rel="noreferrer">Team Software Process on Wikipedia</a>.</p> <p>I have two questions:</p> <ol> <li>What benefits have you seen from these processes?</li> <li>What tools and/or methods do you use to follow these processes?</li> </ol>
<p>I went through the training and then my company paid for me to go to Carnegie Mellon and go through the PSP instructor training course to get certified as an instructor. I think the goal was to use this as part of our company's CMM/CMMI effort. I met Watts Humphrey and found him to be a kind, gentle soul with some deeply held ideas about process. I read several of his books as well.</p> <p>Here's my take on it in a nutshell - it is too structured for most people to follow, assuming you follow things to the letter. The idea of estimation based on historic info is OK, particularly in the classroom setting, but in the real world where estimates are undone in a day due to the changing tide of requirements and direction, it is far less useful. I've also done Wide Band Delphi estimation and that was OK but honestly wasn't necessarily any better than the 'best guess' I'd make.</p> <p>My team was less than enthusiastic about PSP and that is part of the problem - developer buy-in. My company was doing it for the wrong reason - simply to say "hey, look we use PSP and have some certified instructors!". </p> <p>In the end, I've found using a 'agile' approach to be better. I have a backlog of work to do and can generally estimate it pretty well. I've been doing it long enough that I can make pretty good rough estimates on time and frankly don't think that the time tracking really improves things much. Perhaps in some environments it would work well, but at my place, we'll keep pumping out quality software without all the process hoops that yield questionable benefits.</p> <p>Just my two cents.</p>
<p>I used it during university but at work we really don't have a process at all. Only recently have we started using version control.</p> <p>My experience with it was that it seemed far too tedious to be useful. If it's not automated, then it can go away.</p>
4,784
<p>I have a 3D printer and I have printed some models with castable resin. When I burn one of these models in the oven and then do the metal casting, the surface of the metal piece is not smooth.</p> <p>I did a test with a pan. I put a model of wax and a model of castable resin to heat in a pan, and the wax model melts, but the resin model don't.</p> <p>The resin I have is the following:</p> <p><a href="https://i.stack.imgur.com/o07nG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o07nG.jpg" alt="enter image description here"></a></p> <p>What is the correct process to make a correct resin casting?</p> <p>Thanks for your help.</p>
<p>Factually, the correct process is to heat up the mold hot enough to evaporate the positive. </p> <p>In <a href="https://en.wikipedia.org/wiki/Investment_casting" rel="nofollow noreferrer">investment casting</a> the process to remove the wax or plastic positive is called the <code>"Dewax"</code> and <code>"Burnout preheating"</code>.</p> <p>The answer to your question depends on the material you use to generate a negative mold of the positive product. E.g. many silicate based materials require up to about 1100&nbsp;&deg;C to fully burnout all residue before pouring in the liquid metal.</p>
<h2>Traditional lost molds.</h2> <p>The reason many jewelers use wax for making the molds for lost mold casting is, that it has (compared to plastic molding materials) a very low melting and boiling point, allowing to create molds with much lower temperature equipment.</p> <p>A variant of green sand casting is done with materials that very quickly decompose in contact with the molten metal or that burn out after setting fire to them. Very common in this context is foamed styrene. Styrene melts and burns easily so it is easy to use in this way.</p> <p>PLA has been used in some experiments as a positive and then molten out in a baking oven. It and other printing filaments are usually thermoplastics, so melting them out is similar to wax.</p> <h2>Resin is not soft wax or a thermoplastic.</h2> <p>No, in fact, most resins are a duroplastic, meaning that they don't melt.</p> <p>If you print a positive from resin and then make a mold from that for lost mold casting, you go the traditional way. But most resins don't melt out the way wax does, and on contact with molten metal don'T evaporate the way wax residue does. You got to properly <em>burn</em> out the remains of the cured resin at a higher temperature and for a longer time than the wax as the melting point is much higher - use a proper burning oven. A proper burning oven in this relation reaches something like an email oven (1100 °C) or a clay burning oven (up to 1800 °C)</p> <p>Putting the molds with the opening down into one of these ovens at high temperature should help a lot. Make sure to put a spacer and a tray below to allow better airflow and get the resin out.</p> <h2>Chemical Club.</h2> <p>Besides heat to destroy the resin, most resins could be solved by very highly aggressive chemicals. Which chemical works highly depends on what the resin actually is - if it is <a href="https://www.microtonano.com/TIN-Removing-Cured-Epoxy.php" rel="nofollow noreferrer">epoxy resin</a> it would be the highly toxic CH<sub>2</sub>Cl<sub>2</sub> while <a href="https://www.epoxy.com/Epoxy_Chemical_Resistant_Chart.aspx" rel="nofollow noreferrer">polyester resin</a> is soluble in isopropanol and sulphuric acid.</p> <h2>Cold alternative?</h2> <p>If your product is to be made of a two-component resin or a ceramic that can be shaped cold and that sustains form, then you might also look at silicone molding. This is not an alternative for most metal castings. Among the very few exceptions is pewter, as PunishedPropsAcademy and Evan&amp;Katelyn <a href="https://www.youtube.com/watch?v=umtYcUdOv3U" rel="nofollow noreferrer">showed in their video</a> and there are high temp silicones around that could be used repeatedly for pewter.</p>
1,264
<p>ASP.NET 2.0 web application, how to implement shortcut key combination of <kbd>CTRL + Letter</kbd>, preferably through JavaScript, to make web application ergonomically better? How to capture multiple-key keyboard events through JavaScript?</p>
<p>Your event listener function, gets passed an Event object. That has a lot of useful information on it, including the properties "altKey", "ctrlKey", "shiftKey" and "metaKey". If any of the modifier keys are being held down when that event fires, the corresponding property is set to true.</p> <p>This applies to keyboard as well as mouse events (onclick, etc). Note that if you have a onkeydown event listener, the modifier key itself will fire the event.</p> <pre><code>window.onkeyup = function(e) { if (e.altKey) alert("Alt pressed"); if (e.shiftKey) alert("Shift pressed"); } </code></pre> <p>This tested on Firefox 3, Windows XP.</p>
<p>I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application!</p> <p>Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that "one-key shortcut" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser.</p> <p>Moreover, if your visitors use a higly customisable browser, such as Firefox or Opera, There is a high risk that they have either configure their own shortcuts or use additional plug-ins that define some additional ones.</p> <p>Keep in mind that web applications are browser dependend and that you should NEVER assumes that if it works on your favorite-tweak-most-powerfull-browser, it will react the same way on your friend's one.</p>
9,043
<p>I expected the two <code>span</code> tags in the following sample to display next to each other, instead they display one below the other. If I set the <code>width</code> of the class <code>span</code>.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible <code>padding/margin</code> which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; } html, body { margin: 0; padding: 0; height: 100%; width: 100%; border: none; } div.header { width: 100%; height: 80px; vertical-align: top; } span.left { height: 80px; width: 50%; display: inline-block; background-color: pink; } span.right { vertical-align: top; display: inline-block; text-align: right; height: 80px; width: 50%; background-color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Test Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class='header'&gt; &lt;span class='left'&gt;Left Span 50% width&lt;/span&gt; &lt;span class='right'&gt;Right Span 50% width&lt;/span&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <hr /> <p>Thanks for the explanation. The <code>float:left</code> works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge</p>
<pre><code>float: left; </code></pre> <p>Try adding that to span.left</p> <p>It will cause it to float to the left (as suggested by the syntax).</p> <hr> <p>I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it.</p> <p>If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. <a href="http://w3schools.com/css/pr_class_clear.asp" rel="nofollow noreferrer">W3Schools</a> have a page on this property too.</p> <p>And welcome to Stackoverflow.</p>
<p>I don't like this hack but it seems to do the job both in Firefox and IE6:</p> <pre class="lang-css prettyprint-override"><code>span.right { vertical-align:top; display:inline-block; text-align:right; height:80px; width:50%; *width:100%; background-color:red; } </code></pre> <p>Note the <code>*width: 100%</code> which seems to satisfy IE6's requirement and is ignored by Firefox.</p>
5,489
<p>I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection.</p> <p>The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.</p>
<p>Grab <a href="https://proj.org" rel="nofollow noreferrer">PROJ Cartographic Projections library</a> - open source library.</p> <p>Suggested parameters for 10TM:</p> <blockquote> <p>+proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27</p> </blockquote> <p>According to <a href="http://mapserver.gis.umn.edu/data2/wilma/mapserver-users/0311/msg00336.html" rel="nofollow noreferrer">this post</a> you may need to:</p> <blockquote> <p>change the ellps to GRS80 if your 10TM data is referenced to the NAD83 datum (instead of NAD27/clrk66). You may also need to change the false northing (y_0) to be -5000000 if your 10TM coordinates for Alberta are less than 5,000,000 (an AltaLIS &quot;standard&quot;).</p> </blockquote> <p>I should mention that proj.4 is <em>the library</em> to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do.</p> <p>I also recommend reading <a href="https://pubs.er.usgs.gov/publication/pp1395" rel="nofollow noreferrer">Map Projections-A Working Manual (Paperback) by John Snyder</a> if you are into these kinds of things.. it's a classic. :) (fixed the link)</p>
<p>You can also use <a href="http://code.google.com/p/android-openmap-framework/" rel="nofollow">http://code.google.com/p/android-openmap-framework/</a> which can convert an Android Location to a LatLonPoint, UTMPoint, or MGRSPoint.</p>
6,335
<p>I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.</p> <p>Not until I force the browser to clear the cache do I see the changes.</p> <p>Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the <a href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&amp;s=google-web-toolkit-doc-1-5&amp;t=FAQ_GWTApplicationFiles" rel="noreferrer">Google Web Toolkit</a> where they actually create a <strong>new</strong> JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.</p> <p>Is there a list of best practices somewhere?</p>
<p>We append a product build number to the end of all Javascript (and CSS etc.) like so:</p> <pre><code>&lt;script src="MyScript.js?4.0.8243"&gt; </code></pre> <p>Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload.</p> <p>This has the additional benefit that you can set HTTP headers that mean "never cache!"</p>
<p>I am also of the method of just renaming things. It never fails, and is fairly easy to do.</p>
7,807
<p>I want to be able to do:</p> <pre><code>For Each thing In things End For </code></pre> <p>CLASSIC ASP - NOT .NET!</p>
<p>Something like this?</p> <pre><code>dim cars(2),x cars(0)=&quot;Volvo&quot; cars(1)=&quot;Saab&quot; cars(2)=&quot;BMW&quot; For Each x in cars response.write(x &amp; &quot;&lt;br /&gt;&quot;) Next </code></pre> <p>See <a href="http://web.archive.org/web/20140305020029/http://www.w3schools.com/vbscript/vbscript_looping.asp" rel="nofollow noreferrer">www.w3schools.com</a>.</p> <p>If you want to associate keys and values <a href="https://web.archive.org/web/20210619173138/https://www.4guysfromrolla.com/webtech/102898-1.shtml" rel="nofollow noreferrer">use a dictionary object</a> instead:</p> <pre><code>Dim objDictionary Set objDictionary = CreateObject(&quot;Scripting.Dictionary&quot;) objDictionary.Add &quot;Name&quot;, &quot;Scott&quot; objDictionary.Add &quot;Age&quot;, &quot;20&quot; if objDictionary.Exists(&quot;Name&quot;) then ' Do something else ' Do something else end if </code></pre>
<p>As Brett said, its better to use a vb component to create collections. Dictionary objects are not very commonly used in ASP unless for specific need based applications. </p>
2,446
<p>I've seen several questions about dyes in regards to food-safety, with no conclusive answers, as well as anecdotes on the RepRap wiki about how the mechanical properties of dyed PLA tend to vary by color. The general unsatisfactory answer is that dyes and additives used are proprietary secrets of filament manufacturers. However, 3D printer filament is a sufficiently large industry, with sufficiently many players now, that many of these "secrets" surely have to be "open secrets" to some extent by now.</p> <p>What is known about what types of dyes and additives that tend to be used in filaments for 3D printing? Is there information on distinguishing between them with optical, chemical, etc. properties?</p> <p>My thought is that by knowing some of the common dyes used by some manufacturers, it would be possible to:</p> <ol> <li>choose those if interested in properties of them, and; </li> <li>devise test procedures to evaluate if a different/"generic" filament seems to be using the same ones.</li> </ol>
<p>I spoke with a chemist tonight. He said to start with the SDS (or MSDS) for the filament, which is required to be available for most materials. It should list the pigments and additives if they are not recognized as safe. If they are safe, non-toxic, not flammable, non-reactive, they might not be disclosed on the data sheet. </p> <p>He warns that sometimes the SDS lists just an industry name for a common pigment, and sometimes is the full chemical name. IMO, Google may help with translation. </p> <p>The chemist has a deep background in color science and pigments. </p>
<p>I fear your supposition about <em>secret</em> --> <em>open secret</em> is too optimistic. Manufacturers are very unlikely to reveal their components, or the mix ratio, used to create a given color. </p> <p>Consider the Coca-cola formula. It's been a secret for over a hundred years, despite a number of competing cola-ish brands. Consider also that the label you buy is the label of the supplier, and there's no guarantee that a given supplier won't change the manufacturer they use for bulk material at any time (raw colored plastic, just not drawn into filament). </p> <p>As to doing analysis on your own, I fear the cost of a good gas chromatograph, mass spectrometer, etc. is staggeringly high. </p>
1,366
<p>I've put together a flashlight mount for a camera coldshoe in OpenSCAD. I originally modeled it in FreeCAD and it was easy to round the edges of the clamp with a fillet and that makes it a little easier to get the light in and out of the mount.</p> <p>I'm not sure how to do it in OpenSCAD. Naively, I'm sure I could calculate where on my semicircle I would need to add some cylinders in order to round the sharp corners, but it seems like there'd be something a little easier than that.</p> <p>Am I missing something?</p> <p>Here's the <a href="https://github.com/tncbbthositg/cold_shoe_light_mount/blob/795489c90f412502a2545536e906ad8971cfd691/cold_shoe_light_mount.scad" rel="nofollow noreferrer">coldshoe light mount SCAD file</a> and this is what it looks like: <a href="https://i.stack.imgur.com/StF93.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/StF93.png" alt="coldshoe light mount" /></a></p>
<p>I'm far from a wizard with OpenSCAD, but enjoy using the program, learning something new every time. In your case, it's likely that you can use the <a href="https://github.com/Irev-Dev/Round-Anything" rel="nofollow noreferrer">roundanything library</a> to accomplish your objective.</p> <p>The library will present various implementations in the samples, making it an exercise for the reader to determine which module calls will present the solution.</p> <p>The image below shows a part which has had the radii applied in a manner similar to your image:</p> <p><a href="https://i.stack.imgur.com/DWbgd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DWbgd.png" alt="round anything implementation" /></a></p>
<p>I ended up taking a third option I suppose. I decided I was cutting the gap wrong. I was using <code>difference</code> to take a rectangle out of the ring.</p> <p>I decided I'd simplify that and take out an extruded triangle.</p> <pre><code>ringRadius = radius + thickness; verticalOffset = tan(gapAngle / 2) * ringRadius; linear_extrude(height = height) polygon(points = [[0, 0], [ringRadius, verticalOffset], [ringRadius, -verticalOffset]]); </code></pre> <p>That way, the thickness of the plane that needed rounding is uniformely the thickness of the ring. Then, it was just a matter of adding cylinders, centering them in the ring, and rotating them into position.</p> <pre><code>for(side = [-1, 1]) { cornerRadius = radius + thickness / 2; rotate([0, 0, gapAngle / 2 * side]) translate([cornerRadius, 0, 0]) color(&quot;blue&quot;) cylinder(r = thickness / 2, h = height); } </code></pre> <p>Eventually I'd like to make it a little more complex and help accommodate a light better, but for now it gets me the rounded ends I was looking for.</p> <p><a href="https://i.stack.imgur.com/NQll4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NQll4.png" alt="Rounded ends of ring" /></a></p> <p>I'm still going to accept the round everything answer because, though I decided it was more complexity than it was worth on this model, it looks like it would solve other rounding issues too.</p>
1,865
<p>Let's compile a list of tips.</p> <p>(Understandably there will be some subjectivity involved, but some pointers would be useful to someone overwhelmed by tackling a large project within the Flash framework.)</p>
<p>These are just scattered thoughts on organization for projects being worked on mostly with the Flash IDE.</p> <p>First, I highly recommend using source control, like Subversion, CVS, or Git. </p> <p>Organization of filesystem folder structure is subjective, but I generally have a "src" folder for all my source FLAs and AS class files, and a "deploy" or "bin" folder for compiled files. The src folder would contain class package files, with class packages organized in reverse domain style (e.g. - com.codehinting.projectname.context ). Modify the publish path of your FLA to publish to the deploy folder by tracing back up using the "../" path segment, for as many levels as needed to trace back from the nesting in the src folder.</p> <p>Also, I typically place third-party libraries (that are pretty well "baked") in a separate location and then modify the global classpath in the Flash IDE to point to this location.</p> <p>Two extremely handy plugins for the Flash IDE are Create Basic Layers and Library Generator, which quickly create your skeleton layer and library folder structure - saves time versus manually creating layers and folders.</p>
<p>A complex project will have many dependencies. In my Flash projects, I put all my libraries in a version controlled location as they are. Third party libraries are usually a mishmash of assets, code, demos and docs. </p> <p>I keep a small yaml file that keeps track of the location of each type of resource associated with each library on my system. When I add a new library, its location goes into this file first, then I run my Ruby script to move the files over to a single location. This way there is no jockeying around with third party library paths, and making sure include paths in my projects match in my fla files and Flex builder projects. </p> <p>A single source to bind them all.</p>
6,841
<p>I'm trying to print a large piece with polycarbonate but it keeps warping, I'm using a Taz 5 printer and setting 290 C in the extruder and 145 C in the heating bed. </p> <p>Other setting I have are:</p> <ol> <li>printing speed: 20 mm/s</li> <li>layer height: 2.5mm</li> <li>infil: 20%</li> <li>brim: 15mm</li> </ol> <p>Can anyone tell me any tips or suggestions to avoid warping?</p>
<p>Adjusting the design may also be able to help limit the amount of warping you get.</p> <p>One of the major causes of warping is upper layers contracting while cooling when laid down over now-cool(er) lower layers which no longer contract so much but are still thin enough to flex when subject to tension along their upper edge. Insertion of strategically placed gaps in upper layers can reduce the tension such layers are able to apply.</p> <p>I was printing some long thin beams in ABS. I inserted horizontal-axis holes along the beams (making them look a bit like <a href="https://assets.madaboutbricks.uk/wp-content/uploads/2014/03/23161640/Lego-40490-Black-Technic-Beam-9_2.jpg" rel="nofollow noreferrer">LEGO Technic</a> beams rather than solid pieces). It did the job for me.</p>
<p>I would take a look <a href="http://reprap.org/wiki/Polycarbonate" rel="nofollow noreferrer">here</a> and <a href="https://www.matterhackers.com/articles/how-to-succeed-when-printing-with-polycarbonate-filament" rel="nofollow noreferrer">here</a>. Literally the first two results of Google.</p> <p>To summarize what they say,</p> <p>You need good bed adhesion to keep the first layer from warping near the edges like you will get normally with ABS or PC(Polycarbonate). Some use hairspray or gluestick. I manage myself with buildtak surface. I would stay away from blue painters tape. Your looking for something very sticky. This of course makes it a nightmare to get the part off the bed but well worth the trouble if it keeps your print on the bed and flat.</p> <p>Make sure the part receives adequate heat. Like someone wrote in the comments, a enclosure works best to keep the temperature of the entire print warm instead of just the few layers closest to the bed.</p> <p>More perimeter layers works very well by providing more structural strength to try and combat the warping. I've stumbled upon this solution when I had trouble with ABS.</p> <p>Lastly, first layer is always the most important part of any print. You want to make sure it is as level as possible and a good tip is to raise your bed just so slightly than usual so the first layer is jammed hard against the bed. This provides better surface area. Just be careful not to clog your printhead cause if you constrict the flow out of the nozzle too much, you'll might end up with plastic trying to flow upwards or maybe grind the filament with the extruder gear.</p>
739
<p>I'd like to build a pretty simple plug-in for Visual Studio, but I don't really know how this has to be done. Is this doable in (non-managed) C++? </p> <p>I'd like to know what resources you'd recommend me.</p>
<p>I've never tried, so I don't know about doing it in C++, but this website has loads of information: <a href="http://msdn.microsoft.com/en-us/vsx/default.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vsx/default.aspx</a></p>
<p>Found this MSDN tutorial: <a href="http://msdn.microsoft.com/en-us/library/aa699351%28VS.60%29.aspx" rel="nofollow noreferrer">Creating Add-ins Using Visual C++</a>. Thanks Matt.</p>
6,554
<p>Are there any noted differences in appearance rendering of HTML and XHTML in Google Chrome from Firefox? From IE? From other browsers? What browser does it render the code the most similar to?</p>
<p>Since it's based on WebKit, its rendering will most closely resemble Safari and Konqueror.</p>
<p>There are <a href="http://www.flickr.com/photos/kurafire/2822606444/" rel="nofollow noreferrer">anti-aliasing differences</a> between Safari 3.1 and Google Chrome, for whatever that's worth. This will doubtless be because Safari on Windows uses its own text-rendering and anti-aliasing layer instead of Windows's GDI.</p>
9,528
<p>What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?</p>
<p>Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.</p> <p>So where you have a function:</p> <pre><code>function foo($stuff) { ... return ...; } </code></pre> <p>I would change it to:</p> <pre><code>function foo($stuff) { trace_push_fn('foo'); ... trace_pop_fn('foo'); return ...; } </code></pre> <p>(This is one of those cases where multiple returns in a function become a hinderance.)</p> <p>And SQL:</p> <pre><code>function bar($stuff) { trace_push_fn('bar'); $query = ...; trace_push_sql($query); mysql_query($query); trace_pop_sql($query); trace_pop_fn('bar'); return ...; } </code></pre> <p>In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks.</p>
<p>Whenever I look at performance problems, I think the best thing to do is time how long your pages take to run, and then look at the slowest ones. When you get these real metrics, you can often improve performance on the slowest ones by orders of magnitude, either by fixing a slow SQL query or perhaps tightening up the code a bit.</p> <p>This of course requires no new hardware or special software, just a critical eye on the existing code.</p> <p>That said, this will only work for so long... if you really are getting enough traffic to hit the limits of your hardware, and/or there is some code that is just inherently slow and really required, you will have to look at other possibilities.</p>
3,360
<p>I've been here for a little while. I am still a low-reputation of SE, with most of my involvement being here. I know that each SE has it's own personality, somewhat derived from the charter, somewhat from the written standards, and somewhat determined by the customary practices in the community.</p> <p>I have found from reading many answers that the first line is often &quot;soft&quot;. A welcome to a new user. A word of appreciation for the question. A social throat-clearing before jumping into the substance of the answer. Over time, I have adopted this form myself, especially with a user who is new to 3D Printing SE.</p> <p>Three days ago, one of my answers was edited to remove the preliminary social lubricant. I'm fine with this, and I understand it is in keeping with the position that the value of SE to the investors is in the responsive content of the answers, not in the social glue. I would have approved the edits myself except that one can not do that from the app. Today, I connected through a desktop and found that the edit had been auto-approved. Again, no problem.</p> <p>But to the question.</p> <p>We want to be welcoming to new users, and we hope they will stay close to the site and become active members. To do so requires communication, the informal, person-to-person communication that builds oxytocin rather than facts. This doesn't fit the business purpose of SE, but it is necessary to support the mission of SE which must succeed for the business to succeed.</p> <p>Is the right method to:</p> <ol> <li>Welcome people in an answer,</li> <li>Welcome people in a comment, where it is also not appropriate,</li> <li>Do not welcome people -- just stick to the facts, or</li> <li>Welcome people in an answer but go back later and strip it out?</li> </ol>
<p>I struggled with the same question since I saw the edit, good that you brought this to Meta! Thanks!</p> <p>As the community of regular and active members is limited, I think it is okay to welcome people in a comment or an answer. It would be a shame to scare people away after their first question, resulting in abandoned questions and unaccepted answers. But, we do need to conform to the Q&amp;A format and sometimes need to remind people this isn't a forum of threaded messages and we do have some rules to participate. We have created some <a href="/q/303/">standard comments</a> that welcome and thank new members but at the same time lead them to the rules of the site.</p> <p>It might be a good idea to approach first time (SE) members friendly. Welcoming comments can and tend to be deleted after a while when users aren't new anymore (everybody can raise a flag on a comment to vote for <em>”It's no longer needed&quot;</em>). So option 4 would be my preferred option.</p> <p>Personally I think this site is more welcoming than larger sites as SO for instance. My first experiences at SO didn't make me feel welcome.</p>
<p>I struggled with the same question since I saw the edit, good that you brought this to Meta! Thanks!</p> <p>As the community of regular and active members is limited, I think it is okay to welcome people in a comment or an answer. It would be a shame to scare people away after their first question, resulting in abandoned questions and unaccepted answers. But, we do need to conform to the Q&amp;A format and sometimes need to remind people this isn't a forum of threaded messages and we do have some rules to participate. We have created some <a href="/q/303/">standard comments</a> that welcome and thank new members but at the same time lead them to the rules of the site.</p> <p>It might be a good idea to approach first time (SE) members friendly. Welcoming comments can and tend to be deleted after a while when users aren't new anymore (everybody can raise a flag on a comment to vote for <em>”It's no longer needed&quot;</em>). So option 4 would be my preferred option.</p> <p>Personally I think this site is more welcoming than larger sites as SO for instance. My first experiences at SO didn't make me feel welcome.</p>
77
<p>If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?</p>
<p><a href="https://web.archive.org/web/20180330233216/http://www.brokenbuild.com/blog/2006/08/15/mysql-triggers-how-do-you-abort-an-insert-update-or-delete-with-a-trigger/" rel="noreferrer">Here is one hack</a> that may work. It isn't clean, but it looks like it might work:</p> <p>Essentially, you just try to update a column that doesn't exist.</p>
<pre><code>DELIMITER @@ DROP TRIGGER IF EXISTS trigger_name @@ CREATE TRIGGER trigger_name BEFORE UPDATE ON table_name FOR EACH ROW BEGIN --the condition of error is: --if NEW update value of the attribute age = 1 and OLD value was 0 --key word OLD and NEW let you distinguish between the old and new value of an attribute IF (NEW.state = 1 AND OLD.state = 0) THEN signal sqlstate '-20000' set message_text = 'hey it's an error!'; END IF; END @@ DELIMITER ; </code></pre>
2,239
<p>I am a bit confused about socket programming in C.</p> <p>You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article <s><a href="http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html" rel="nofollow noreferrer">Network programming under Unix systems</a></s> to be very informative.</p> <p>What confuses me is the timing of data arriving on the socket.</p> <p>How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? </p> <p>My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?</p>
<p>Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete.</p> <p>When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes.</p> <p>Here's a typical C function for reading a set number of bytes from a socket:</p> <pre><code>/* buffer points to memory block that is bigger than the number of bytes to be read */ /* socket is open socket that is connected to a sender */ /* bytesToRead is the number of bytes expected from the sender */ /* bytesRead is a pointer to a integer variable that will hold the number of bytes */ /* actually received from the sender. */ /* The function returns either the number of bytes read, */ /* 0 if the socket was closed by the sender, and */ /* -1 if an error occurred while reading from the socket */ int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead) { *bytesRead = 0; while(*bytesRead &lt; bytesToRead) { int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead); if(ret &lt;= 0) { /* either connection was closed or an error occurred */ return ret; } else { *bytesRead += ret; } } return *bytesRead; } </code></pre>
<p>Sockets operate at a higher level than raw packets - it's like a file you can read/write from. Also, when you try to read from a socket, the operating system will block (put on hold) your process until it has data to fulfill the request.</p>
7,132
<p>The <a href="https://help.prusa3d.com/article/6Gtws6Yqjg-pei-print-surface-preparation" rel="noreferrer">Prusa3d knowledge base</a> mentions that acetone will "rejuvenate" PEI in addition to cleaning oil and grease from the surface.</p> <blockquote> <p>About once a week, or when <strong>prints stop sticking</strong>, use <strong>ACETONE</strong> to clean the bed. It removes grease better than IPA or Windex. It also <strong>rejuvenates</strong> the print surface. However, if you use acetone every day, PEI will become brittle and start cracking.</p> </blockquote> <p>From a chemical or physical perspective, how does acetone affect the PEI surface?</p>
<p>Rejuvenate is probably a bit of an exaggerated term. The number one adhesion suppressor is grease. The stuff that comes off of the fingers used to handle the sheet. Even if you are careful and only handle the sides, the grease will be carried to the center of the plate next time its cleaned with less aggressive solvents.</p> <p>Isopropyl alchohol does break down grease but not to the extent that acetone does. Acetone also attacks plastic particles that accumulate on the print surface over time.</p> <p>PEI is resistant to a wide array of chemicals[1] including acetone but it can become brittle if exposed to it too much especially when hot so acetone is not recommended for daily cleaning. </p> <p>[1] <a href="https://www.emcoplastics.com/assets/pdf/ultem/ULTEM%20Product%20Brochure%20GE.pdf" rel="noreferrer">Ultem Product Broshure</a> table 4-3</p>
<p>Acetone is smelly nasty stuff. Here's a sample recommendation for PEI maintenance from one of a few (million?) 3d printing help sites. </p> <blockquote> <p>Use isopropyl alcohol, methyl alcohol, soap, Heptane, Hexane, or Naphtha. Avoid ketones (such as MEK) or strong bases (such as sodium hydroxide).</p> </blockquote>
1,283
<p>Is this possible? Does the .NET framework depend on the meta data in the bytecode? I'd like to have an application i write not work in reflector or a similar .NET decompiler.</p>
<p>If you remove the metadata the framework won't be able to load your code, or figure out which other assemblies it references, or anything like that, so no, that's not a good idea.</p> <p>Obfuscators will make it a lot harder for an 'attacker' to decompile your code, but at the end of the day if someone is motivated and smart there's not a lot you can do to stop them.<br> .NET will always compile down to MSIL, and MSIL is inherently easier to read than raw x86. That's just one of the tradeoffs you make for using .NET. </p> <p>Don't worry about it. The source code to apache, linux, and everything else is freely available on the net, but it's not providing much competitive advantage to microsoft is it :-)</p>
<p>I don't think you can remove the meta data, but you can obfuscate your code if you're looking to protect your IP. </p>
5,159
<p>I've created an "attached behaviour" in my WPF application which lets me handle the Enter keypress and move to the next control. I call it EnterKeyTraversal.IsEnabled, and you can see the code on my blog <a href="http://www.madprops.org/blog/enter-to-tab-as-an-attached-property/" rel="noreferrer">here</a>.</p> <p>My main concern now is that I may have a memory leak, since I'm handling the PreviewKeyDown event on UIElements and never explicitly "unhook" the event.</p> <p>What's the best approach to prevent this leak (if indeed there is one)? Should I keep a list of the elements I'm managing, and unhook the PreviewKeyDown event in the Application.Exit event? Has anyone had success with attached behaviours in their own WPF applications and come up with an elegant memory-management solution?</p>
<p>I do not agree DannySmurf</p> <p>Some WPF layout objects can clog up your memory and make your application really slow when they are not garbage collected. So I find the choice of words to be correct, you are leaking memory to objects you no longer use. You expect the items to be garbage collected, but they aren't, because there is a reference somewhere (in this case in the from an event handler).</p> <p>Now for a real answer :)</p> <p>I advise you to read this <a href="http://msdn.microsoft.com/en-us/library/bb613565.aspx" rel="nofollow noreferrer">WPF Performance article on MSDN</a></p> <blockquote> <p>Not Removing Event Handlers on Objects may Keep Objects Alive</p> <p>The delegate that an object passes to its event is effectively a reference to that object. Therefore, event handlers can keep objects alive longer than expected. When performing clean up of an object that has registered to listen to an object's event, it is essential to remove that delegate before releasing the object. Keeping unneeded objects alive increases the application's memory usage. This is especially true when the object is the root of a logical tree or a visual tree.</p> </blockquote> <p>They advise you to look into the <a href="http://msdn.microsoft.com/en-us/library/aa970850.aspx" rel="nofollow noreferrer">Weak Event pattern</a></p> <p>Another solution would be to remove the event handlers when you are done with an object. But I know that with Attached Properties that point might not always be clear..</p> <p>Hope this helps!</p>
<p>Well that (the manager bit) I can certainly understand, and sympathize with.</p> <p>But whatever Microsoft calls it, I don't think a "new" definition is appropriate. It's complicated, because we don't live in a 100% managed world (even though Microsoft likes to pretend that we do, Microsoft itself does not live in such a world). When you say memory leak, you could mean that a program is consuming too much memory (that's a user's definition), or that a managed reference will not be freed until exit (as here), or that an unmanaged reference is not being properly cleaned up (that would be a real memory leak), or that unmanaged code called from managed code is leaking memory (another real leak).</p> <p>In this case, it's obvious what "memory leak" means, even though we're being imprecise. But it gets awfully tedious talking to some people, who call every over-consumption, or failure-to-collect a memory leak; and it's frustrating when these people are programmers, who supposedly know better. It's kind of important for technical terms to have unambiguous meanings, I think. Debugging is so much easier when they do.</p> <p>Anyway. Don't mean to turn this into an airy-fairy discussion about language. Just saying...</p>
3,492
<p>I recently purchased a BIGTREETECH SKR mini E3 V1.2 and need to adjust some of the settings in configuration h to accommodate for my custom built 3d printer. In the past I've used the RAMPS 1.4 board and adjusted the firmware in the arduino IDE. What is the best way/recommended way to do this for the mini E3 V1.2.</p> <p>Thanks.</p>
<h1>Basics</h1> <p>Firmware can be distributed in 2 ways:</p> <ul> <li>As a compiled file (for example as .hex).</li> <li>As an uncompiled repository (as in a preconfigured marlin distribution) that needs to be compiled at the users' side.</li> </ul> <h1>compiled file</h1> <p>Compiled files <strong>can't</strong> be altered easily. The only way to change settings after installation is to send the correct commands via a <a href="https://3dprinting.stackexchange.com/questions/10573/what-is-a-printer-console-terminal">console</a> to alter the settings in the SRAM then save the new settings into the EEPROM via <a href="https://marlinfw.org/docs/gcode/M500.html" rel="nofollow noreferrer"><code>M500</code></a> from the <a href="https://3dprinting.stackexchange.com/questions/11438/m502-will-reset-all-configurable-settings-to-their-factory-defaults-which-set/11440#11440">M50X family of commands</a> - and hoping that EEPROM was activated in the firmware to begin with.</p> <h1>uncompiled distribution</h1> <p>To alter an uncompiled Repository, you can follow the basic path in <a href="https://3dprinting.stackexchange.com/questions/12153/updating-marlin-firmware-step-by-step-guide">Updating Marlin Firmware - Step by Step Guide </a></p>
<h1>Basics</h1> <p>Firmware can be distributed in 2 ways:</p> <ul> <li>As a compiled file (for example as .hex).</li> <li>As an uncompiled repository (as in a preconfigured marlin distribution) that needs to be compiled at the users' side.</li> </ul> <h1>compiled file</h1> <p>Compiled files <strong>can't</strong> be altered easily. The only way to change settings after installation is to send the correct commands via a <a href="https://3dprinting.stackexchange.com/questions/10573/what-is-a-printer-console-terminal">console</a> to alter the settings in the SRAM then save the new settings into the EEPROM via <a href="https://marlinfw.org/docs/gcode/M500.html" rel="nofollow noreferrer"><code>M500</code></a> from the <a href="https://3dprinting.stackexchange.com/questions/11438/m502-will-reset-all-configurable-settings-to-their-factory-defaults-which-set/11440#11440">M50X family of commands</a> - and hoping that EEPROM was activated in the firmware to begin with.</p> <h1>uncompiled distribution</h1> <p>To alter an uncompiled Repository, you can follow the basic path in <a href="https://3dprinting.stackexchange.com/questions/12153/updating-marlin-firmware-step-by-step-guide">Updating Marlin Firmware - Step by Step Guide </a></p>
1,645
<p>Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? </p> <p>For example, is there a clean way to implement <em>swap( intA, intB )</em> in Actionscript?</p>
<p>I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object:</p> <pre><code>function swapAB(aValuesContainer:Object):void { if (!(aValuesContainer.hasOwnProperty("a") &amp;&amp; aValuesContainer.hasOwnProperty("b"))) throw new ArgumentError("aValuesContainer must have properties a and b"); var tempValue:int = aValuesContainer["a"]; aValuesContainer["a"] = aValuesContainer["b"]; aValuesContainer["b"] = tempValue; } var ints:Object = {a:13, b:25}; swapAB(ints); </code></pre>
<p>If ActionScript works like Javascript,</p> <pre><code>[a,b] = [b,a] </code></pre>
7,152
<p>I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?</p>
<pre><code>var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty} </code></pre>
<p>I don't think that you can using pure LINQ. However, if you're doing this sort of thing a lot in your code you may be able to make this work with reflection.</p>
6,825
<p>Can someone suggest some good automated test suite framework for Perl?</p>
<p>It really depends on what you're trying to do, but here's some background for much of this.</p> <p>First, you would generally write your test programs with Test::More or Test::Simple as the core testing program:</p> <pre><code>use Test::More tests =&gt; 2; is 3, 3, 'basic equality should work'; ok !0, '... and zero should be false'; </code></pre> <p>Internally, Test::Builder is called to output those test results as TAP (<a href="http://testanything.org/wiki/index.php/Main_Page" rel="noreferrer">Test Anything Protocol</a>). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command:</p> <pre><code>prove --verbose t/numbers.t </code></pre> <p>Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories):</p> <pre><code>prove --verbose -r t/ </code></pre> <p>(--verbose, of course, is optional).</p> <p>As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools.</p>
<p>I'd go for Test::More, or in general, anything that outputs <a href="http://en.wikipedia.org/wiki/Test_Anything_Protocol" rel="nofollow noreferrer">TAP</a></p>
7,227
<p>I'd like to use the camera in my Macbook in a program. I'm fairly language agnostic - C, Java, Python etc are all fine. Could anyone suggest the best place to look for documents or "Hello world" type code?</p>
<p>The ImageKit framework in Leopard has an <a href="http://developer.apple.com/documentation/GraphicsImaging/Reference/IKImagePicker_Class/IKImagePicker_Reference.html#//apple_ref/occ/cl/IKPictureTaker" rel="nofollow noreferrer"><code>IKPictureTaker</code></a> class that will let you run the standard picture-taking sheet or panel that you seen in iChat and other applications.</p> <p>If you don't want to use the standard picture-taker panel/sheet interface, you an use the <a href="http://developer.apple.com/documentation/QuickTime/Conceptual/QTKitCaptureProgrammingGuide/" rel="nofollow noreferrer">QTKit Capture</a> functionality to get an image from the iSight.</p> <p>Both of these will require writing some Cocoa code in Objective-C, but that shouldn't really be an obstacle these days.</p>
<p>Quartz Composer is also a pleasant way to capture and work with video, when it's applicable. There's a video input patch.</p> <p>Quartz Composer is a visual programming environment that integrates into a larger Cocoa program if need be.</p> <p><a href="http://developer.apple.com/graphicsimaging/quartz/quartzcomposer.html" rel="nofollow noreferrer">http://developer.apple.com/graphicsimaging/quartz/quartzcomposer.html</a></p>
8,165
<p>I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p><strong>For Example -</strong> You have <em>Home</em>, <em>Products</em>, <em>About Us</em>, and <em>Contact</em>. I want to have buttons for <em>Dealer</em>, <em>Distributor</em>, and maybe other information if the user is logged in. So I will have <em>Home</em>, <em>Products</em>, <em>About Us</em>, <em>Contacts</em>, Dealer (if dealer login), <em>Distributor</em> (if distributor login), and so forth. </p> <p>Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>Regarding security, <strong>you cannot trust what comes from the client</strong>:</p> <ul> <li>The visitor can see all your code (HTML and Javascript, not PHP) and try stuff</li> <li>The visitor may not even use a browser; it's trivially easy to send a request with a script</li> </ul> <p>This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.</p> <p>If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.</p>
<p>Basically where you have your menu in html, say as a list <code>&lt;ul&gt; &lt;li&gt;Home&lt;/li&gt; &lt;/ul&gt;</code> you add php after <code>&lt;/li&gt;</code> of the last item:</p> <pre><code>&lt;?php if($session-logged_in) { ?&gt; &lt;li&gt;My Account&lt;/li&gt; &lt;?php } ?&gt; </code></pre>
2,868
<p>I've seen many references to a FDM print being weakest in the Z axis, due to poor bonding between layers compared to the extruded walls. </p> <p>Thinking about optimising this for a specific material (excluding temperature and geometry), is there an optimum layer height? It seems obvious that too thick a layer will give less compression and maybe less heat transfer into the layer below (so 0.3 with a 0.4mm nozzle might be expected to be a bit weak). Is there a single break point (i.e. less than half the nozzle is good), or are super fine layers either good or bad?</p> <p>I'm specifically using PLA at the moment, in case different materials have different behaviour in this respect.</p> <p>I am <strong>not</strong> asking how to model the strength of layer bonds or how to take that into account when designing a part.</p>
<p>My3dmatter.com performed a <a href="http://my3dmatter.com/influence-infill-layer-height-pattern//influence-infill-layer-height-pattern/" rel="nofollow noreferrer">series of tests</a> with PLA, using "a universal testing machine". They conclude:</p> <blockquote> <p>Layer height influences the strength of a printed part when it becomes thin. A printed part at 0.1mm shows a max stress of only 29MPa, as opposed to 35MPa for 0.2mm (21% increase).</p> <p>Past 0.2mm, the max stress remains fairly constant around 36 MPa (we confirmed this conclusion with an extra test at 0.4mm, not shown here because it was not part of the same batch).</p> </blockquote> <p><a href="https://i.stack.imgur.com/i2fXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i2fXm.png" alt="enter image description here"></a></p> <p>Note: It is recommended to read the full article to comprehend the complexity of the subject matter.</p>
<p>Just adding another datapoint. CNCKitchen has a new <a href="https://youtu.be/fbSQvJJjw2Q" rel="nofollow noreferrer">video</a> where he analyses this for cross layer and between layer tension. He also references some other research (which is rather inconclusive). He supports the coarse estimate of 'no more than 50% of the nozzle diameter, with performance also dropping at very low layer height.</p> <p>He found cross layer tension supported more than 2x the layer-to-layer tension (with a typical 3-wall, low infill pattern).</p>
1,010
<p>Kicked off the second long print in a series (printing Lack enclosure components). First 10 hour print was flawless. Started this one, saw the first layer laid down well, went to bed. Woke up to this (you can see the successful prints in the background):</p> <p><a href="https://i.stack.imgur.com/HYYcU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HYYcU.jpg" alt="enter image description here"></a></p> <p>The whole heater block and nozzle is entombed in PLA. The leads to the heater and the thermistor are too. I'm assuming there's no solvent for this, and I'm better off just buying a new hot end.</p> <p>Thoughts?</p>
<h2>Yes</h2> <p>I had a somewhat similar clog once, and I could fix it back up. However, it is a lot of work.</p> <h2>Hobbyist Way</h2> <h3>Step 1: heat</h3> <p>As long as the heater cartridge is still ok, just fire up the printer, move up the print head by 50 mm and wait some two or three minutes till the goop is warmed enough at the core to melt. Set the hot end to 200 °C and no cooling fan.</p> <h3>Step 2: rough clean</h3> <p>Check the cables for your hot end and thermistor as long as the plastic has not yet softened up around them and especially surrounding the thermistor: When the glob is removed in one swoop, you might tear the lines! It's better to use a sculpting tool or exacto-blade on the softening plastic and make an opening that allows the glob to be pulled away safely with minimal pull on the cabling.</p> <p>When the blob has softened enough, you can just pull at the outer of the blob to pull it down. Use a tool like pliers and pull off the worst that still sticks to the hotend. Pulling the blob free can take a while, so be patient and careful.</p> <p>If you have a soldering iron, you can use that as a heated scraper from the outside and skip on heating from the inside. If you have no temperature control (as if your thermosensor is shot) outside heat is the only safe way.</p> <h3>Step 3: Cool down</h3> <p>After having made a rough clean up from the outside, let it cool down so you can dismantle it.</p> <h3>Step 4: dismantle and clean the hotend.</h3> <p>This is actually rather simple, and I will point <a href="https://3dprinting.stackexchange.com/questions/7920/heatercartridge-bolt-stuck/7923#7923">to a question where I outlined that for a broken thermistor cartridge</a>. You have a working thermosensor at least, so less problems on that front.</p> <h2>Shortcut</h2> <p>If you have a hot air gun for hot air soldering, you can be much faster! Skip step 1 to 3, dismantle the hotend and go straight to Step 4, dismantling it and cleaning it out of the machine with the hot air soldering tool as a heat source. Heat and scrape away, and get out the thermosensor and thermosensor as soon as possible to prevent destroying them.</p>
<p>If you can remove the hot-end it is easier. If not, carefully use hot air to soften (not melt) the PLA so you can more easily pull away chunks.</p> <p>When the hot-end is removed from the other plastic parts, you can get more aggressive with hot air. BUT, be careful of the thermistor and heater wires. They are fragile, and can easily be broken or pulled out of their devices.</p> <p>Heat and patience is the key. If you do break a heater or thermister, they are pretty easy to replace. Depending on the hot-end, the heater and/or the thermister may be locked in place by a set screw. That set-screw is probably locked in place by plastic, so use the hot-air gun to melt that plastic and allow you to back out the set-screw.</p>
1,220
<p>When using Resharper to encapsulate a class's properties, is there a way to get it to do more than one property at a time?</p>
<p>You might or might not already know this (R# does suffer from a lack of discoverability, unless you get the one-page key-shortcut page printed out), but ALT-INS opens a box which can at least mass-generate properties for fields.</p> <p>Not sure if that's any use - it's not the same as a retrospective encapsulation.</p>
<p>I don't think there such a feature out of the box.</p> <p>However, you could write a RS plugin that does this. But this would be another question...</p>
5,588
<p>I'm just wondering if there's a better way of doing this in SQL Server 2005.</p> <p>Effectively, I'm taking an originator_id (a number between 0 and 99) and a 'next_element' (it's really just a sequential counter between 1 and 999,999). We are trying to create a 6-character 'code' from them. </p> <p>The originator_id is multiplied up by a million, and then the counter added in, giving us a number between 0 and 99,999,999.</p> <p>Then we convert this into a 'base 32' string - a fake base 32, where we're really just using 0-9 and A-Z but with a few of the more confusing alphanums removed for clarity (I, O, S, Z).</p> <p>To do this, we just divide the number up by powers of 32, at each stage using the result we get for each power as an index for a character from our array of selected character.</p> <pre> Thus, an originator ID of 61 and NextCodeElement of 9 gives a code of '1T5JA9' (61 * 1,000,000) + 9 = 61,000,009 61,000,009 div (5^32 = 33,554,432) = 1 = '1' 27,445,577 div (4^32 = 1,048,576) = 26 = 'T' 182,601 div (3^32 = 32,768) = 5 = '5' 18,761 div (2^32 = 1,024) = 18 = 'J' 329 div (1^32 = 32) = 10 = 'A' 9 div (0^32 = 1) = 9 = '9' so my code is 1T5JA9 </pre> <p>Previously I've had this algorithm working (in Delphi) but now I really need to be able to recreate it in SQL Server 2005. Obviously I don't quite have the same functions to hand that I have in Delphi, but this is my take on the routine. It works, and I can generate codes (or reconstruct codes back into their components) just fine.</p> <p>But it looks a bit long-winded, and I'm not sure that the trick of selecting the result of a division into an int (ie casting it, really) is necessarily 'right' - is there a better SQLS approach to this kind of thing?</p> <pre> CREATE procedure dummy_RP_CREATE_CODE @NextCodeElement int, @OriginatorID int, @code varchar(6) output as begin declare @raw_num int; declare @bcelems char(32); declare @chr int; select @bcelems='0123456789ABCDEFGHJKLMNPQRTUVWXY'; select @code=''; -- add in the originator_id, scaled into place select @raw_num = (@OriginatorID * 1000000) + @NextCodeElement; -- now to convert this to a 6-char code -- 5^32 select @chr = @raw_num / 33554432; select @raw_num = @raw_num - (@chr * 33554432); select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1); -- 4^32 select @chr = @raw_num / 1048576; select @raw_num = @raw_num - (@chr * 1048576); select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1); -- 3^32 select @chr = @raw_num / 32768; select @raw_num = @raw_num - (@chr * 32768); select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1); -- 2^32 select @chr = @raw_num / 1024; select @raw_num = @raw_num - (@chr * 1024); select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1); -- 1^32 select @chr = @raw_num / 32; select @raw_num = @raw_num - (@chr * 32); select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1); -- 0^32 select @code = @code + SUBSTRING(@bcelems, 1 + @raw_num, 1); -- that's it! end; </pre> <p>I'm not desperately concerned about optimisation unless this method is actually an order of magnitude (or so) worse than any alternative. </p> <p>The code only ever gets executed in small bursts, maybe generating 20 or 30 codes every 10 minutes or so. Because of the large range of numbers I don't want to pre-calculate the codes into a huge table (only small pockets of the overall code range will be used in any given installation).</p> <p>However, I'm sure there's probably a tidier way of achieving the same result - particularly those divisions and subtractions.</p> <p>Any constructive criticism, observations or suggestions would be most welcome. </p>
<p>Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code.</p>
<p>Although it can clearly be done in SQL Server 2005, I think that it's of sufficient 'non-database-ness' that some kind of precompiled, high-level language routine makese sense.</p> <p>I've written DLLs for Interbase/Firebird, and T-SQL sprocs for SQL Server, but never a CLR routine. It will be an interesting exercise!</p>
7,907
<p>So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another.</p> <p>What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic?</p> <p>I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a <i>bad</i> choice in other contexts?</p>
<p>A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value.</p> <p>ie. for a directory tree consisting of the following:</p> <pre><code>C:\ Temp Windows System32 </code></pre> <p>You would have the following nodes</p> <pre><code>Key Name Parent Path 1 C: *1* 2 Temp 1 *1*2* 3 Windows 1 *1*3* 4 System32 3 *1*3*4* </code></pre> <p>Path is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges.</p> <p>ie. to find C:\Temp and all its children:</p> <pre><code>WHERE Path LIKE '*1*2*%' </code></pre> <p>This representation is the only place I can think of where storing <em>id's</em> in a string like this is ok.</p>
<p>A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value.</p> <p>ie. for a directory tree consisting of the following:</p> <pre><code>C:\ Temp Windows System32 </code></pre> <p>You would have the following nodes</p> <pre><code>Key Name Parent Path 1 C: *1* 2 Temp 1 *1*2* 3 Windows 1 *1*3* 4 System32 3 *1*3*4* </code></pre> <p>Path is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges.</p> <p>ie. to find C:\Temp and all its children:</p> <pre><code>WHERE Path LIKE '*1*2*%' </code></pre> <p>This representation is the only place I can think of where storing <em>id's</em> in a string like this is ok.</p>
4,752
<p>I haven't used <code>C++</code> since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for <code>Launchy</code>. </p> <blockquote> <p>Is there a good book to read to get back into it?</p> </blockquote> <p>My experience since college is mainly <code>C#</code> and recently <code>ruby</code>. I bought some book for <code>C#</code> developers and it ended up being on how to write <code>C++</code> with <code>CLI</code>. While a good book it wasn't quite what I was looking for.</p>
<p>The best way to get back into C++ is to jump in. You can't learn a real language without spending any serious time in a country where they speak it. I wouldn't try to learn a programming language without spending time coding in it either.</p> <p>I wouldn't recommend learning C first though. That's a good way to pick up some bad habits in C++.</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0201700735" rel="nofollow noreferrer" rel="nofollow noreferrer">The C++ Programming Language</a> by Bjarne Stroustrup covers C++ in depth. Bjarne is the inventor of C++. It also provides insights into why the language is the way it is. Some people find the book a little terse. I found it to be an enjoyable read. If you have done some C++ before it's a great place to start. It is by no means a beginners book on C++.</p>
5,810
<p>Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection. </p> <p>Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?) </p>
<p>This widget can be made with three items: a text input, button input, and an unordered list to hold the results.</p> <pre><code> __________ _ |__________||v|__ &lt;-- text and button | | &lt;-- ul (styled to appear relative to text input) | | | | |______________| </code></pre> <p>ul shown on:</p> <ul> <li>'keyUp' event of the text input (if value is non-empty) </li> <li>'click' event of the button input (if currently not visible)</li> </ul> <p>ul hidden on:</p> <ul> <li>'click' event of the button input (if currently visible)</li> <li>'click' event of list items</li> </ul> <p>When the ul is shown or the 'keyUp' event of the text input is triggered an AJAX call to the server needs to be made to update the list. </p> <p>On success the results should be placed in the ul. When creating the list items they should have a 'click' event attached to them that sets the text input value and hides the ul (may have to add a link inside the li to attach the event to).</p> <p>The hardest part is really the CSS. The JavaScript is simple especially with a solid library like prototype that supports multiple browsers. </p> <p>You will probably want to support some IDs for the items, so you can add some hidden inputs to each list item with the id and next to the text input to store the selected items ID.</p>
<p>In my opinion, you shouldn't use AJAX for this at all. </p> <p>here's why:</p> <p>(1) On focus: ALL the options that he can select are shown in the dropdown. This means that all possible options are already sent to the client.</p> <p>(2) If the user types something in, the number of entries in the drop down are filtered down to match. This can easily be done on the client side. Being ajax'y and going back to the server at this point will just slow things down.</p> <p>phpguru.org has a control which is 'almost exactly' what you need:</p> <p><a href="http://www.phpguru.org/static/AutoComplete.html#demo" rel="nofollow noreferrer">http://www.phpguru.org/static/AutoComplete.html#demo</a></p> <p>It differs slightly from what you need in that it shows the dropdown on double-click instead of on focus. That should be fairly easy to modify.</p> <p>I hope this helps.</p>
6,165
<p>How do I create a branch in subversion that is deeper' than just the 'branches' directory?</p> <p>I have the standard <code>trunk</code>, <code>tags</code> and <code>branches</code> structure and I want to create a branch that is several directories deeper than the 'branches' tag.</p> <p>Using the standard svn move method, it gives me a <strong>folder not found</strong> error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.</p> <p>What do I need to do to create this?</p> <p>For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?</p>
<pre><code>svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject </code></pre> <p>That should create the directory you want to put the subproject in (<code>--parents</code> means "create the intermediate directories for me").</p>
<p>If you're using <code>TortoiseSVN</code>, you can use its <strong>Repository Explorer</strong> to do such things. Makes it all pretty <code>WYSIWYG</code> simple.</p>
7,610
<p>When you have Auto Mesh Bed Leveling enabled on your printer, it's not possible to continue a failed print, is it?</p>
<p>Continuing a failed print has nothing to do with automatic bed leveling. It has everything to do with knowing which line failed, repositioning to resume from that point, and resuming from that line of code.</p>
<p>So like resuming any print, if you've already done the work to find the layer you failed at, edited the G-code to start from that layer. But now you feel stuck because to start a print you need to home your printer right? And homing with a BLTouch makes it probe the center of your bed... which happens to be where your print is at. IF you're on Klipper, you can put something like this here:</p> <pre><code>[homing_override] set_position_z:0 gcode: G90 G1 Z10 F600 G28 X Y #G1 X161 Y125 F6000 ;old bed center G1 X245 Y215 F6000 ;far right corner of the bed. You may have to adjust your X and Y for your BLTouch location as mine is on a Hero Me hotend G28 Z G1 Z100 F24000 ; move Z-axis up so hotend doesn't hit the print when zeroing. Adjust this as needed to clear your print from where it failed G1 X0 Y0 F24000 </code></pre> <p>And from there, the printer should Home and you can start your partial G-code from here. IF YOU HAVE KLIPPER. Make sure to remove any purge lines or stuff like that from your Start Print code.</p>
595
<p>How do you generate and analyze a thread dump from a running JBoss instance?</p>
<p>There is a JBoss-specific method that is slightly more user-friendly:</p> <p><a href="http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole" rel="nofollow noreferrer">http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole</a></p> <p>This is especially useful when you don't have direct access to the host machine (which "kill" would require).</p>
<p>Sometimes JBoss locks so much that even jmx-concole doesn't respond. In such case use kill -3 on Linux and <a href="http://www.latenighthacking.com/projects/2003/sendSignal/" rel="nofollow">SendSignal</a> on Windows.</p>
8,448
<p>Any recommendations for a javascript form validation library. I could try and roll my own (but I'm not very good at javascript). Needs to support checking for required fields, and preferably regexp validation of fields.</p>
<p>I am about to start implementing javascript validation in my forms using <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="noreferrer">jQuery Validation</a>. I think that StackOverflow users this jQuery plugin as well. It seems to be a very mature validation library, however it does build on top of jQuery, so it might not fit for you.</p> <p>Like Tom said, don't forget that server side validation.</p>
<p>I've used <a href="http://tetlaw.id.au/view/javascript/really-easy-field-validation" rel="nofollow noreferrer">this library</a> for a couple of personal projects. It's pretty good, though I have had to make my own modifications to it a couple of times - nothing major, though, and it's easy enough to do so.</p> <p>I'm sure you already do this, but also validate all of your information on the server-side, as well. Client-side-only validation is rarely, if ever, a good idea. </p>
3,841
<p>Are there any lists of default CSS stylesheets for different browsers? (browser stylesheets in tabular form)</p> <p>I want to know the default font of text areas across all browsers for future reference.</p>
<p>Not tabular, but the source CSS may be helpful if you're looking for something specific:</p> <ul> <li><a href="http://hg.mozilla.org/mozilla-central/file/tip/layout/style/res/html.css" rel="nofollow noreferrer">Firefox default HTML stylesheet</a></li> <li><a href="http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css" rel="nofollow noreferrer">WebKit default HTML stylesheet</a></li> </ul> <p>You're on your own with IE and Opera though.</p>
<p>There was some discussion and testing done on www-style not too long ago:</p> <p><a href="http://lists.w3.org/Archives/Public/www-style/2008Jul/0124.html" rel="nofollow noreferrer">http://lists.w3.org/Archives/Public/www-style/2008Jul/0124.html</a></p> <p><a href="http://lists.w3.org/Archives/Public/www-style/2008Jul/att-0124/defaultstyles.htm" rel="nofollow noreferrer">http://lists.w3.org/Archives/Public/www-style/2008Jul/att-0124/defaultstyles.htm</a></p>
5,287
<p>I'm looking for a way to redirect all the stderr streams in interactive bash (ideally to its calling parent process).</p> <p>I don't want to redirect stderr stream from each individual command, which I could do by appending <code>2&gt; a_file</code> to each command.</p> <p>By default, these stderr streams are redirected to the stdout of an interactive bash. I would like to get them on the stderr of this interactive bash process in order to prevent my stdout to be polluted by error messages and be able to treat them separatly.</p> <p>Any ideas?</p> <p>I still haven't found an answer ... But maybe it's actually a tty parameter. Does anybody knows something about tty/interactive shell responsibility for handling stderr ?</p>
<p>Use the <code>exec</code> builtin in bash:</p> <p><code>exec 2&gt; /tmp/myfile</code></p>
<p>Tried <code>ssh -t</code> to create a pseudo-TTY at the remote end?</p>
4,992
<p>Modern database systems today come with loads of features. And you would agree with me that to learn one database you must unlearn the concepts you learned in another database. For example, each database would implement locking differently than others. So to carry the concepts of one database to another would be a recipe for failure. And there could be other examples where two databases would perform very very differently. </p> <p>So while developing the database driven systems should the programmers need to know the database in detail so that they code for performance? I don't think it would be appropriate to have the DBA called for performance later as his job is to only maintain the database and help out the developer in case of an emergency but not on a regular basis. </p> <p>What do you think should be the extent the developer needs to gain an insight into the database?</p>
<p>I think these are the most important things (from most important to least, IMO):</p> <ul> <li><strong>SQL (obviously)</strong> - It helps to know how to at least do basic queries, aggregates (sum(), etc), and inner joins</li> <li><strong>Normalization</strong> - DB design skills are an major requirement</li> <li><strong>Locking Model/MVCC</strong> - Its nice to have at least a basic grasp of how your databases manage row locking (or use MVCC to accomplish similar goals with optimistic locking)</li> <li><strong>ACID compliance, Txns</strong> - Please know how these work and interact</li> <li><strong>Indexing</strong> - While I don't think that you need to be an expert in tablespaces, placing data on separate drives for optimal performance, and other minutiae, it does help to have a high level knowledge of how index scans work vs. tablescans. It also helps to be able to read a query plan and understand why it might be choosing one over the other.</li> <li><strong>Basic Tools</strong> - You'll probably find yourself wanting to copy production data to a test environment at some point, so knowing the basics of how to restore/backup your database will be important.</li> </ul> <p>Fortunately, there are some great FOSS and free commercial databases out there today that can be used to learn quite a bit about db fundamentals.</p>
<p>Basic things about Sql queries are must. then you can develop simple system. but when you are going to implement Complex systems you should know Normalization, Procedures, Functions, etc.</p>
4,381
<p>Recently, the ticking sounds started to come from feeder of my UM2. Inspecting it I have noticed that once in a while stepper motor jumps back for few steps. I have an idea of what can be the reason, but I just want to hear what you can think of. That is the video of feeder during the printing :) <a href="https://youtu.be/z6CzudMOeD0" rel="nofollow">https://youtu.be/z6CzudMOeD0</a> First tick at 10sec</p>
<p>Ultimately, your stepper motor is unsuccessful in driving the filament through the extruder. A couple potential reasons:</p> <ul> <li>extruder temperature isn't high enough. This could either be operator error from not setting the temperature correctly or your machine is getting a false reading. Typically, for ABS/PLA, you can get away with a low extruding temperature of about 210c.</li> <li>filament tension is too high. This happens if, say, your spool of filament gets kinked or wrapped around the spool spindle.</li> <li>your nozzle is clogged. I've encountered where I had back flow coming out of the nozzle (filaments oozed around from the hotend at the threads). This was a result of not putting the hotend back together correctly. There was a enough hardened plastic backed up in the hotend that when I threaded the nozzle back on, it technically didn't fit back on all the way.</li> </ul>
<p>Oh yeah that is way too low for the ultimaker.</p> <p>That temp is a general "this is what PLA melts at" so if you took plastic, heated it up to that temp it would melt.</p> <p>However, you don't heat all the plastic at once. Your hotend it at that temp and if you let it sit it would heat up (fairly quickly). Printers like the ultimaker are fast, and well designed. They have a very small heat melt zone. So the plastic only has a fraction of time to heat up.</p> <p>Solution? Higher temps!</p> <p>(do not do this example. Not liable if you hurt yourself) You know how you can take a lighter and almost slowly wave your finger thought it without getting burned? You know if you let it stay even a full second you would regret it. Same thing here. It is going too fast to heat up.</p>
240
<p>Today I was working on a tab navigation for a webpage. I tried the <a href="http://www.alistapart.com/articles/slidingdoors2/" rel="noreferrer">Sliding Doors</a> approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). </p> <p>I wanted to use a nested anchor, which didn't work because it is <a href="http://www.w3.org/TR/html4/struct/links.html#h-12.2.2" rel="noreferrer">not</a> allowed. Then I saw the tab- navigation at <a href="http://www.pageflakes.com" rel="noreferrer">Pageflakes</a>, which was actually working (including nested hyperlinks). Why?</p>
<p>They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS).</p> <p>Here is what the html looks like:</p> <pre><code>&lt;a class="page_tab page_tab"&gt; &lt;div class="page_title" title="Click to rename this page."&gt;Click &amp; Type Page Name&lt;/div&gt; &lt;a class="delete_page" title="Click to delete this page" style="display: block;"&gt;X&lt;/a&gt; &lt;/a&gt; </code></pre>
<p>Actually, the code I had pasted previously was the generated DOM, after all JS manipulation. If you don't have the <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a> extension for Firefox, you should get it now.</p> <p>Edit: Deleted the old post, it was no longer useful. Firebug is, so this one is staying :)</p>
4,130