instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I'm just about to make my first trip into the world of JNI (Java Native Interface) to provide file system change notifications from platform specific C/C++ code to Java. That is unless someone suggest some brilliant library for doing this that I've missed.</p> <p>Being new to JNI I've managed to find much documentation on the interface side of it and library generation side of it, but I've not found much on building the native library.</p> <p>I've got an existing build based on ant for the pre-existing Java source, so I'm trying to work out if I should get ant to call make to create the library or if it's best to get make to call ant after creating the library?</p> <p>Neither option jumps out as being terribly nice, but both seem better than trying to get ant to call a compiler to compile the code and generate the library directly.</p>
<p>I strongly dislike make because of its implicit ruleset and treatment of whitespace. Personally I would use cpp tasks (<a href="http://ant-contrib.sourceforge.net/cpptasks/index.html" rel="nofollow noreferrer">http://ant-contrib.sourceforge.net/cpptasks/index.html</a>) to do my C compilation. They are not as flexible as make but they are also far less complex and it will mean you don't have to burden your developers with learning make. </p>
<p>You could also try the terp C++ tasks at <a href="http://codemesh.com/products/terp" rel="nofollow noreferrer">Codemesh</a>. They are not free but they offer a high level of abstraction coupled with the ability to discover/specify the C++ compiler and the ability to iterate over more than one compiler/processor architecture/compiler configuration for multiplatform builds.</p>
3,611
<p>I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:</p> <pre><code>try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } </code></pre> <p>Now, I have two problems:</p> <ul> <li><p>I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?</p></li> <li><p>This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.</p></li> </ul> <p>Any help with either would be great.</p>
<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (<a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">linky</a>) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.</p>
<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (<a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">linky</a>) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.</p>
7,162
<p>I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from <code>System.Int32</code> to <code>System.Decimal</code>. When I try to change the datatype in the <code>DataSet Designer</code> I receive the following error:</p> <blockquote> <p>Property value is not valid. Cannot change DataType of a column once it has data.</p> </blockquote> <p>From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error.</p> <p>Does any one have any ideas?</p>
<p>I get the same error but only for columns with its <code>DefaultValue</code> set to any value (except the default <code>&lt;DBNull&gt;</code>). So the way I got around this issue was:</p> <ol> <li>Column DefaultValue : Type in <code>&lt;DBNull&gt;</code></li> <li>Save and reopen the dataset</li> </ol>
<ul> <li>Close the DataSet in the visual designer</li> <li>Right click the dataset, choose <code>Open With...</code></li> <li>Choose <code>XML (Text) Editor</code></li> <li>Find the column in the XML, in your dataset it will look something like:</li> </ul> <pre><code>&lt;xs:element name="DataColumn1" msprop:Generator_ColumnVarNameInTable="columnDataColumn1" msprop:Generator_ColumnPropNameInRow="DataColumn1" msprop:Generator_ColumnPropNameInTable="DataColumn1Column" msprop:Generator_UserColumnName="DataColumn1" type="xs:int" minOccurs="0" /&gt; </code></pre> <ul> <li>Change the <code>type="xs:int"</code> to <code>type="xs:decimal"</code></li> <li>Save and close the XML editor</li> <li>You may need to right click the DataSet again and choose <code>Run Custom Tool</code></li> </ul>
6,943
<p>I'm not really sure if I'm asking the right question here, but I just made a noob mistake of buying 3 mm filaments instead of 1.75 mm. I have a Makerbot Replicator 2 which I've been using and so far it is pulling in 1.75 mm quite well.</p> <p>Is there any way I can still make use the 3 mm filaments, or do I need to use the filaments on different models? If it is the latter, which particular model is able to pull in 3 mm filament well?</p>
<p>This is not a definitive answer (and has turned into a ramble), as I have not yet had to change my filament size. </p> <p>However, initially, I would have thought that only the hotend and the hotend's nozzle would need to be changed, from one that can handle the 1.75 mm filament to 3 mm. If the extruder is spring loaded, then it should adjust itself to the thicker filament, without a problem. If not, then you may have to do a slight manual adjustment.</p> <p>However, after doing some further reading, there may be other factors that need to be considered, such as:</p> <ul> <li>Extruder gearing;</li> <li>Melt time (which would imply a different feed rate)</li> </ul> <p>It could be worth having a close look at the aperture of your hotend. If, in the unlikely situation, it looks as if the hotend would accept 3 mm (or if you could remove the lining so that it can), you <em>may</em> not need to actually change any hardware, but instead just try tweeking the <strong>feedrate</strong> in the software, because as your nozzle is less than the width of the filament anyway, then it will be fine for both 1.75 mm <em>and</em> 3 mm. A 3 mm filament would require more heating, and therefore a slower feedrate than a 1.75 mm feedrate. Once the filament has melted, so long as the pressure from the extruder is sufficient, then the molten filament should come out of the nozzle. However, this may be a less than satisafctory method and result in some dubious prints.</p> <p>There is an interesting thread on the RepRap wiki, <a href="http://forums.reprap.org/read.php?1,128719,page=1" rel="nofollow noreferrer">1.75mm Filament vs 3mm Filament</a>, that discusses most of the points above.</p> <p>It should be noted that the advantages of 3 mm filament has over 1.75 mm are that it is:</p> <ul> <li>cheaper</li> <li>stiffer (less flexible) and thus "easier" to push through the hotend.</li> </ul> <p>As an aside, one interesting point raised in the thread, is that maybe a smaller extruder can be used, for the narrower 1.75 mm filament, thus resulting in a lighter print head. I am not sure how true that is.</p> <p>This article, <a href="http://hackaday.com/2015/10/17/converting-a-3d-printer-from-3mm-to-1-75mm/" rel="nofollow noreferrer">Converting a 3D printer from 3mm to 1.75mm</a>, does the reverse of what you want, and comes with a <a href="https://www.youtube.com/watch?v=UcMw-3RizIw" rel="nofollow noreferrer">video</a>. It states that, as you have already found, that the hotend needs to be changed:</p> <blockquote> <p>The printer [Thomas] is changing out to accept 1.75mm is the Lulzbot Mini, one of the most popular printers that would ever need this modification. The only required materials is a new hot end suitable for 1.75mm filament, a 4mm drill, and a few wrenches and allen keys. It would be a smart idea to get a hot end that uses the same thermistor as the old one, but that’s not a deal-breaker as the problem can be fixed in the firmware.</p> </blockquote> <p>Alternatively, you could leave your printer as it is and use a <a href="http://www.thingiverse.com/thing:72336" rel="nofollow noreferrer">3mm to 1.75mm filament converter</a>, which may be a bit of overkill for just one reel of filament<sup>1</sup>.</p> <h3>The bottomline</h3> <p>To be honest, is it worth the hassle, time and expense of having to modify and re-calibrate your printer (or worst case, change the model of the printer), just for the price of a reel of filament (assuming that you did not bulk purchase a bunch of reels)? It may be better to stick to one filament size (i.e. your original size) for all of your projects, and so resell the reel of 3 mm and stick with the 1.75 mm printer and buy the correct filament<sup>2</sup>.</p> <hr> <p><sup>1</sup> See also <a href="https://3dprinting.stackexchange.com/questions/38/conversion-of-3mm-abs-filament-to-1-75mm">Conversion of 3mm ABS filament to 1.75mm</a></p> <p><sup>2</sup> See also <a href="https://3dprinting.stackexchange.com/questions/38/conversion-of-3mm-abs-filament-to-1-75mm#answer-42">Tom's answer</a> to <a href="https://3dprinting.stackexchange.com/questions/38/conversion-of-3mm-abs-filament-to-1-75mm">Conversion of 3mm ABS filament to 1.75mm</a></p> <p>See also <a href="https://3dprinting.stackexchange.com/questions/269/can-1-75mm-filament-be-used-in-a-printer-that-takes-3mm-filament">Can 1.75mm filament be used in a printer that takes 3mm filament?</a></p>
<p>Late to the party here but I am doing this exact thing. I stupidly bought like a dozen rolls of 3mm filament for about $6 a Kg. I think trying the switch should be fun...but I have 7 printers so its no big deal to tinker on one of them.</p> <p>What you need to do is modify the extruder. I have done this successfully using the crappy plastic extruders which come with most budget printers. You have to drill out the filament path to fit the 3 mm filament. It does get a little tricky to get the filament to run through nicely.</p> <p>You actually <strong>do not</strong> need to modify your hot end other than your Bowden tube and your nozzle. Regular Bowden tube is 2 mm ID and 4 mm OD, so you just order 3 mm ID and 4 mm OD tube. Please note that this plan <strong>will not</strong> work for an all metal 1.75 mm hotend.</p> <p>For the nozzle you can often find 3 mm compatible nozzles. Unfortunately they don't seem to be made for the MK10 hotend. So I simply ordered big ole 1 mm nozzles made for 1.75 mm and I am going to drill out the back for the 2.85 mm (3 mm) filament.</p> <p>I am excited to see how this all works. You can get some really good deals on 3 mm filament <em>and</em> I suspect that it will actually work much better for things like TPU since it is significantly more rigid due to the increased diameter!</p>
507
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail">How do you send email from a Java app using Gmail?</a> </p> </blockquote> <p>How do I send an SMTP Message from Java?</p>
<p>Here's an example for Gmail smtp:</p> <pre><code>import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.smtp.*; public class Distribution { public static void main(String args[]) throws Exception { Properties props = System.getProperties(); props.put("mail.smtps.host","smtp.gmail.com"); props.put("mail.smtps.auth","true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("mail@tovare.com"));; msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("tov.are.jacobsen@iss.no", false)); msg.setSubject("Heisann "+System.currentTimeMillis()); msg.setText("Med vennlig hilsennTov Are Jacobsen"); msg.setHeader("X-Mailer", "Tov Are's program"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", "admin@tovare.com", "&lt;insert password here&gt;"); t.sendMessage(msg, msg.getAllRecipients()); System.out.println("Response: " + t.getLastServerResponse()); t.close(); } } </code></pre> <p>Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache</p> <p><a href="http://commons.apache.org/email/" rel="noreferrer">http://commons.apache.org/email/</a> </p> <p>Regards</p> <p>Tov Are Jacobsen</p>
<pre><code>import javax.mail.*; import javax.mail.internet.*; import java.util.*; public void postMail(String recipients[], String subject, String message , String from) throws MessagingException { //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", "smtp.jcom.net"); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(false); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i &lt; recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); } </code></pre>
9,932
<p>I'm really asking this by proxy, another team at work has had a change request from our customer.</p> <p>The problem is that our customer doesn't want their employees to login with one user more than one at the same time. That they are getting locked out and sharing logins. </p> <p>Since this is on a web farm, what would be the best way to tackle this issue?</p> <p>Wouldn't caching to the database cause performance issues?</p>
<p>You could look at using a distributed cache system like <a href="http://www.danga.com/memcached/" rel="noreferrer">memcached</a></p> <p>It would solve this problem pretty well (it's MUCH faster than a database), and is also excellent for caching pretty much anything else too</p>
<p>It depends on how the authentication is done. If you store the last successful login datetime (whatever the backend), so maybe you can change the schema to store a flag "logged_in" and that won't involve an extra performance cost. (ok, it's not clean at all)</p>
5,369
<p>Unable to find a SQL diff tool that meets my needs, I am writing my own. Between the INFORMATION_SCHEMA and sys tables, I have a mostly-complete working version. But one thing I can't find in the metadata is the <em>definition</em> of a trigger, you know, the actual SQL code. Am I overlooking something?</p> <p>Thanks.</p> <hr> <p>Thanks, Pete, I didn't know about that!</p> <p>Scott, I'm working with very basic hosting packages that don't allow remote connections to the DB. I don't know from the specs on RedGate (which I can't afford anyway) whether they provide a workaround for that, and although there are also API's out there (such as the one from Apex), I didn't see the point in investing in a solution that was still going to require more programming on my part. :)</p> <p>My solution is to drop an ASPX page on the site that acts as a kind of "schema service", returning the collected metadata as XML. I set up a little AJAX app that compares any number of catalog instances to a master and shows the diffs. It's not perfect, but a major step forward for me.</p> <p>Thanks again!</p>
<p>sp_helptext works to get the sql that makes up a trigger.</p> <p>The text column in the syscomments view also contains the sql used for object creation.</p>
<p>this query return trigger with its name and body.</p> <pre><code>Select [tgr].[name] as [trigger name], [tbl].[name] as [table name] , OBJECT_DEFINITION(tgr.id) body from sysobjects tgr join sysobjects tbl on tgr.parent_obj = tbl.id WHERE tgr.xtype = 'TR' </code></pre>
6,566
<p>When developing a new web based application which version of html should you aim for?</p> <p>EDIT:</p> <p>cool I was just attempting to get a feel from others I tend to use XHTML 1.0 Strict in my own work and Transitional when others are involved in the content creation.</p> <p>I marked the first XHTML 1.0 Transitional post as the 'correct answer' but believe strongly that all the answers given at that point where equally valid.</p>
<p>HTML 4.01. There is absolutely <strong>no reason</strong> to use XHTML for anything but experimental or academic problems that you only want to run on the 'obscure' web browsers.</p> <p>XHTML Transitional is completely pointless even to <em>those</em> browsers, so I'm not sure why anyone would aim for that. It's actually pretty alarming that a number of people would recommend that.</p> <p>I'd say aiming for HTML 4.01 is the most predictable, but Teifion is right really, "anything that renders your page will do".</p> <p>in response to <a href="https://stackoverflow.com/questions/3654/html-version-choice#3659">Michael Stum</a>:</p> <blockquote> <p>XHTML is XML based, so it allows easier parsing and you can also use the XML Components of most IDEs to programatically query and insert stuff.</p> </blockquote> <p>This is certainly not true. A lot of XHTML on the web (if not most) does not conform to XML validity (and it needn't - it's not being sent as XML). Trying to treat this like XML when dealing with it is just going to earn you a lot of headaches. This page on Stack Overflow, for instance, will generate errors with many unforgiving XML tools for having invalid mark-up.</p>
<p>HTML 4.0 Strict, or ISO HTML.</p>
2,572
<p>I'm using the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">AutoComplete</a> control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. </p> <p>I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. </p> <p>Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.</p>
<p>We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: <a href="http://www.drive.com.au" rel="nofollow noreferrer">http://www.drive.com.au</a> </p> <p>The textbox id is <code>MainSearchBox_SearchTextBox</code>. Have a look at about line 586 &amp; you can see where I'm wiring up all the events (I'm actually using prototype for this bit.</p> <p>Basically on the focus event of the textbox I set a global var called <code>textBoxHasFocus</code> to true and on the blur event I set it to false. The on the load event of the page I call this script:</p> <pre><code>if (textBoxHasFocus) { $get("MainSearchBox_SearchTextBox").blur(); $get("MainSearchBox_SearchTextBox").focus(); } </code></pre> <p>This resets the textbox. It's really dodgy, but it's the only solution I could find</p>
<p>How are you setting focus? I haven't tried the specific scenario you've suggested, but here's how I set focus to my controls:</p> <pre><code>Public Sub SetFocus(ByVal ctrl As Control) Dim sb As New System.Text.StringBuilder Dim p As Control p = ctrl.Parent While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm))) p = p.Parent End While With sb .Append("&lt;script language='JavaScript'&gt;") .Append("function SetFocus()") .Append("{") .Append("document.") .Append(p.ClientID) .Append("['") .Append(ctrl.UniqueID) .Append("'].focus();") .Append("}") .Append("window.onload = SetFocus;") .Append("") .Append("&lt;/script") .Append("&gt;") End With ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString()) End Sub </code></pre> <p>So, I'm not sure what method you're using, but if it's different than mine, give that a shot and see if you still have a problem or not.</p>
6,444
<p>What is the best way to write a Safari extension? I've written a couple XUL extensions for Firefox, and now I'd like to write versions of them for Safari. Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?</p>
<p>Safari plugin development is non-trivial. The interface is written in Objective-C, and most of it is not even part of WebKit (so you can't see the source), but there's machinery to inspect and patch the object hierarchy of a running application. It requires understanding of Cocoa and Objective-C, but no lower.</p> <p>Here's a high level overview I had in my bookmarks of the process <a href="http://livingcode.org/2006/tab-dumping-in-safari" rel="nofollow noreferrer">http://livingcode.org/2006/tab-dumping-in-safari</a>. It goes over creating Safari plugins using Python with working (probably outdated) code. Instead of Python you can use anything that has Objective-C bindings.</p> <p>There are two major parts to it:</p> <ul> <li><p>You need to attach your code to a running Safari. This is typically done with SIMBL <a href="http://www.culater.net/software/SIMBL/SIMBL.php" rel="nofollow noreferrer">http://www.culater.net/software/SIMBL/SIMBL.php</a>.</p></li> <li><p>Once you're inside, you need to figure what to patch. There's a tutorial on reversing Cocoa applications <a href="http://www.culater.net/wiki/moin.cgi/CocoaReverseEngineering" rel="nofollow noreferrer">http://www.culater.net/wiki/moin.cgi/CocoaReverseEngineering</a>, which links to the most important tool, class-dump <a href="http://www.codethecode.com/projects/class-dump/" rel="nofollow noreferrer">http://www.codethecode.com/projects/class-dump/</a> (the link on wiki is broken). Class-dump gives you a complete hierarchy of Safari's classes, where you can guess by names what, specifically, you need to patch. This is a very trial and error mode.</p></li> </ul> <p>Reading the links above will give you the scope of the project.</p>
<p>Also, to note - Apple has stated that InputManagers are being severely limited as of Leopard and will not run in 64-bit applications per Apple <a href="http://developer.apple.com/releasenotes/Cocoa/AppKit.html#NSInputManager" rel="nofollow noreferrer">Leopard Release Notes</a>. This is especially interesting considering most applications will be 64-bit in Snow Leopard (including presumably Safari). Apple is definitely trying to obliterate InputManager as a vector to overriding and extending functionality. Safari desperately needs an extension mechanism.</p>
8,512
<p>I've writen an Excel-based, database reporting tool. Currentely, all the VBA code is associated with a single XLS file. The user generates the report by clicking a button on the toolbar. Unfortunately, unless the user has saved the file under another file name, all the reported data gets wiped-out.</p> <p>When I have created similar tools in Word, I can put all the code in a template (.dot) file and call it from there. If I put the template file in the Office startup folder, it will launch everytime I start Word. Is there a similar way, to package and distribute my code in Excel? I've tried using Add-ins, but I didn't find a way to call the code from the application window.</p>
<p>You can modify the user's personal.xls file, stored in the excel startup directory (varies between Office versions). If you have lots of users though, that can be fiddly.</p> <p>An alternative way to get over your problem is to store the macro in a template (.xlt) file. Then when the users opens it they can't save it back over the original file, but have to specify a new filename to save it as. The disadvantage of this method is that you then get multiple copies of your original code all over the place with each saved file. If you modify the original .xlt and someone reruns the old macro in a previously-saved .xls file then things can get out of step.</p>
<p>Have you looked into ClickOnce deploying the Excel file?</p>
4,929
<p>In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.</p> <p>I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:</p> <p>As long as the derived constructor has not been executed the object is <strong>not</strong> yet a <em>derived</em> instance.</p> <p>So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:</p> <pre><code>class base { public: base() { std::cout &lt;&lt; "foo is " &lt;&lt; foo() &lt;&lt; std::endl; } virtual int foo() { return 42; } }; class derived : public base { int* ptr_; public: derived(int i) : ptr_(new int(i*i)) { } // The following cannot be called before derived::derived due to how C++ behaves, // if it was possible... Kaboom! virtual int foo() { return *ptr_; } }; </code></pre> <p>It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for <em>the principle of least surprise</em>? </p> <p>Which do you think is the correct choice?</p>
<p>There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object.</p> <p>In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body.</p> <p>The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed.</p>
<p>Delphi makes good use of virtual constructors in the VCL GUI framework: </p> <pre><code>type TComponent = class public constructor Create(AOwner: TComponent); virtual; // virtual constructor end; TMyEdit = class(TComponent) public constructor Create(AOwner: TComponent); override; // override virtual constructor end; TMyButton = class(TComponent) public constructor Create(AOwner: TComponent); override; // override virtual constructor end; TComponentClass = class of TComponent; function CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent; begin Result := ComponentClass.Create(AOwner); end; var MyEdit: TMyEdit; MyButton: TMyButton; begin MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit; MyButton := CreateAComponent(TMyButton, Form) as TMyButton; end; </code></pre>
5,743
<p>I'm needing to access Excel workbooks from .Net. I know all about the different ways of doing it (I've written them up in a <a href="http://blog.functionalfun.net/2008/06/reading-and-writing-excel-files-with.html" rel="noreferrer" title="Reading and Writing Excel files in .Net">blog post</a>), and I know that using a native .Net component is going to be the fastest. But the question is, which of the components wins? Has anybody benchmarked them? I've been using Syncfusion XlsIO, but that's very slow for some key operations (like deleting rows in a workbook containing thousands of Named ranges).</p>
<p>I haven't done any proper benchmarks, but I tried out several other components,and found that <a href="http://spreadsheetgear.com/" rel="nofollow noreferrer">SpreadsheetGear</a> was considerably faster than XlsIO which I was using before. I've written up some of my findings in this <a href="http://blog.functionalfun.net/2008/08/which-net-excel-io-component-should-i.html" rel="nofollow noreferrer">post</a></p>
<p>Yes but I'm not going to publish them both out of a courtesy to Syncfusion (they ask you not to publish benchmarks), because I'm not an experienced tester so my tests are probably somewhat flawed but mostly because what you actually benchmark makes a huge difference to who wins and by how much. </p> <p>I took one of their "performance" examples and added the same routine in EPPlus to compare them. XLSIO was around 15% faster with just straightforward inserts, depending on the row/column ratio (I tried a few), memory usage seemed very similar. When I added a routine that, after all the rows were added, deleted every 10th row and then inserted a new row 2 rows up from that - XLSIO was significantly slower in that circumstance. </p> <p>A generic benchmark is pretty-much useless to you. You need to try them against each other in the specific scenarios you use.</p> <p>I have been using EPPlus for a few years and the performance has been fine, I don't recall shouting at it.</p> <p>More worthy of your consideration is the functionality, support (Syncfusion have been good, in my experience), Documentation, access to the source code if that is important, and - importantly - how much sense the API makes to you, the syntax can be quite different. eg. Named Styles</p> <p>XLSIO</p> <pre><code>headerStyle.BeginUpdate(); workbook.SetPaletteColor(8, System.Drawing.Color.FromArgb(255, 174, 33)); headerStyle.Color = System.Drawing.Color.FromArgb(255, 174, 33); headerStyle.Font.Bold = true; headerStyle.Borders[ExcelBordersIndex.EdgeLeft] .LineStyle = ExcelLineStyle.Thin; headerStyle.Borders[ExcelBordersIndex.EdgeRight] .LineStyle = ExcelLineStyle.Thin; headerStyle.Borders[ExcelBordersIndex.EdgeTop] .LineStyle = ExcelLineStyle.Thin; headerStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin; headerStyle.EndUpdate(); </code></pre> <p>EPPlus</p> <pre><code>ExcelNamedStyleXml headerStyle = xlPackage.Workbook.Styles.CreateNamedStyle("HeaderStyle"); headerStyle.Style.Fill.PatternType = ExcelFillStyle.Solid; // &lt;== needed or BackgroundColor throws an exception headerStyle.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(255, 174, 33)); headerStyle.Style.Font.Bold = true; headerStyle.Style.Border.Left.Style = ExcelBorderStyle.Thin; headerStyle.Style.Border.Right.Style = ExcelBorderStyle.Thin; headerStyle.Style.Border.Top.Style = ExcelBorderStyle.Thin; headerStyle.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; </code></pre>
3,528
<p>I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions.</p> <p>I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour.</p> <p>I think these can be stored using the <code>jQuery.data()</code> function:</p> <pre><code>//save old hover behavior (somehow) $('#foo').data('oldhoverin',???) $('#foo').data('oldhoverout',???); //set new hover behavior $('#foo').hover(newhoverin,newhoverout); </code></pre> <p>Do stuff with new hover behaviour...</p> <pre><code>//restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); </code></pre> <p>But how do I get the currently registered hover functions from jQuery?</p> <p>Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"</p>
<p>Calling an event <code>bind</code> method (such as <code>hover</code>) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events.</p> <p>You can add your own events, and then remove them without affecting any other events then use Event namespacing: <a href="http://docs.jquery.com/Events_(Guide)#Namespacing_events" rel="nofollow noreferrer">http://docs.jquery.com/Events_(Guide)#Namespacing_events</a></p>
<p>I'm not sure if this is what you mean, but you can bind custom events and then trigger them.</p> <p><a href="http://docs.jquery.com/Events/bind" rel="nofollow noreferrer">http://docs.jquery.com/Events/bind</a></p> <p>So add your hover event, script the functionality you need for that hover, then trigger your custom event.</p>
7,135
<p>My Craftbot Plus Craftware slicer estimates cost per job based on filament prices I add as parameters. What costs per meter would you use? I created spreadsheets to calculate this for 1.75mm diameter filament and arrived at PLA = 6.6 cents per meter, ABS = 6.1 and PET XT = 18.6 cents per meter.</p> <p>Edit: thanks for feedback! I paid \$22 per kilogram for PLA and ABS. I paid \$57 for .75 kilogram of Colorfab XT Black.</p>
<p>This strongly depends on the cost of the spool in question. Prices are not consistent among materials at all; a spool of ABS can cost anywhere from \$15 to \$60 and the same price range applies to pretty much all other plastic.</p> <p>For the purpose of this question I am going to assume that a 1 kilogram spool costs \$25 (regardless of material) but you can scale the figures to what is appropriate for your brand of filament.</p> <p><a href="https://www.toybuilderlabs.com/blogs/news/13053117-filament-volume-and-length" rel="nofollow noreferrer">ToyBuilder Labs</a> lists the density of ABS at 1.04g/ml, whereas PLA is somewhat more dense at 1.25g/ml. As such, a 1kg spool of ABS would be 400 meters (1.75mm filament) or 156 meters (2.85mm filament). PLA would come out to 333 meters (125 meters for 2.85mm filament)</p> <p>We thus have the following costs (cost per meter for 2.85mm filament in parenthesis):</p> <ul> <li><p>ABS: 6.25 cents/meter (16)</p></li> <li><p>PLA: 7.5 cents/meter (20)</p></li> </ul> <p>The density of PETG is roughly the same as PLA, so they have the same cost per meter (for similarly priced spools).</p> <p>In general, to compute the cost per meter, you would use the following formula:</p> <p><span class="math-container">$$[\text{\$/m}]=[\text{cost of 1 }kg] \times [\text{density in }g/mm^3] \times \frac{[\text{diameter in }mm]^2\ \times \pi }{4000}$$</span></p>
<p>The simplest method is to divide spool price by its length. That's obvious I think. If PLA 1.75 (1kg net) has about 120m length and it costs 16usd then it looks like 1m costs arount 13c. =price/length</p> <p>I think everyone can buy different filament at different price from different vendors so there is no good general price to enter into your slicer app. It has to be calculated each time you use new filament.</p> <p>There are also other parts of the price. Electricity, time, wear, depreciation, know-how even the rent is some part of the ending price of the final product. Of course most of them are incalculable as they are permiles or so. But if you don't plan to sell it you can base on the filament price only.</p>
333
<p>"Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services."</p> <p>I find using SQL Server Profiler extremely useful during development, testing and when I am debugging database application problems. Does anybody know if there is an equivalent program for MySql?</p>
<p>Something cool that is in version 5.0.37 of the community server is <a href="http://web.archive.org/web/20110609054749/http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html" rel="noreferrer">MySQL's new profiler</a>. </p> <p>This may give you what info you are looking for.</p>
<p>I don't know about any profiling apps as such, but it's commonplace to use the EXPLAIN syntax for analysing queries. You can use these to figure out the best indexes to create, or you can try changing the overall query and see how it changes the efficiency, etc.</p>
4,062
<p>I would like to automatically generate PDF documents from <a href="https://en.wikipedia.org/wiki/WebObjects" rel="nofollow noreferrer">WebObjects</a> based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen?</p>
<p>The canonical response when asked about PDFs from WebObjects has generally been <a href="http://www.reportmill.com/" rel="nofollow noreferrer">ReportMill</a>. It's a PDF document generating framework that works a lot like WebObjects, and includes its own graphical PDF builder tool similar to WebObjects Builder and Interface Builder. You can bind elements in your generated PDFs to dynamic data in your application just as you would for a <code>WOComponent</code>.</p> <p>They have couple of tutorial videos on the <a href="http://reportmill.com/product/" rel="nofollow noreferrer">ReportMill product page</a> that should give you an idea of how the tool works. It'll probably be a lot easier than trying to work with FOP programmatically.</p>
<p>ScArcher2>></p> <p>I have looked into different routes for creating PDFs on the fly including FOP and a few Java libraries. I think what I am really asking is if anyone has already done this in the WebObjects framework. My hope is that someone familiar with WebObjects might have done this already and have some insight that would save me some time. </p>
3,250
<p>Can anyone provide some real examples as to how best to keep script files for views, stored procedures and functions in a SVN (or other) repository.</p> <p>Obviously one solution is to have the script files for all the different components in a directory or more somewhere and simply using TortoiseSVN or the like to keep them in SVN, Then whenever a change is to be made I load the script up in Management Studio etc. I don't really want this.</p> <p>What I'd really prefer is some kind of batch script that I can run periodically (nightly?) that would export all the stored procedures / views etc that had changed in a given timeframe and then commit them to SVN.</p> <p>Ideas?</p>
<p>Sounds like you're not wanting to use Revision Control properly, to me.</p> <blockquote> <p>Obviously one solution is to have the script files for all the different components in a directory or more somewhere and simply using TortoiseSVN or the like to keep them in SVN</p> </blockquote> <p>This is what should be done. You would have your local copy you are working on (Developing new, Tweaking old, etc) and as single components/procedures/etc get finished, you would commit them individually until you have to start the process over.</p> <p>Committing half-done code just because it's been 'X' time since it was last committed is sloppy and guaranteed to cause anyone else using the repository grief.</p>
<p>You can always try integrating SourceSafe with SQL Server. Here's a quick start : <a href="http://msdn.microsoft.com/en-us/library/ms181089(VS.80).aspx" rel="nofollow noreferrer">link</a> . To work with it you've got to have Managment Studio Developers Edition.</p>
7,433
<p>In Ruby 1.8 and earlier,</p> <pre><code>Foo </code></pre> <p>is a constant (a Class, a Module, or another constant). Whereas</p> <pre><code>foo </code></pre> <p>is a variable. The key difference is as follows:</p> <pre><code>module Foo bar = 7 BAZ = 8 end Foo::BAZ # =&gt; 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module </code></pre> <p>That's all well and good, but Ruby 1.9 <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html" rel="nofollow noreferrer">allows UTF-8 source code</a>. So is <code>℃</code> "uppercase" or "lowecase" as far as this is concerned? What about <code>⊂</code> (strict subset) or <code>Ɖfoo</code>?</p> <p>Is there a general rule?</p> <p><em>Later:</em></p> <p>Ruby-core is already considering some of the mathematical operators. For example</p> <pre><code>module Kernel def √(num) ... end def ∑(*args) ... end end </code></pre> <p>would allow</p> <pre><code>x = √2 y = ∑(1, 45, ...) </code></pre> <p>I would love to see</p> <pre><code>my_proc = λ { |...| ... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 </code></pre>
<p>I don't know what ruby would do if you used extended UTF8 characters as identifiers in your source code, but I know what I would do, which would be to slap you upside the back of the head and tell you DON'T DO THAT</p>
<blockquote> <p>I would love to see</p> </blockquote> <pre><code>my_proc = λ { |...| ... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 </code></pre> <p>I would love to see someone trying to type that program on an English keyboard :P</p>
4,278
<p>Is this function declaration in C#:</p> <pre><code>void foo(string mystring) </code></pre> <p>the same as this one in C:</p> <pre><code>void foo(char *) </code></pre> <p>i.e. In C#, does the called function receive a pointer behind the scenes?</p>
<p>In this specific instance, it is more like:</p> <pre><code>void foo(const char *); </code></pre> <p>.Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes.</p>
<p>As far as I know, all classes in C# (not sure about the others) are reference types.</p>
9,028
<p>I'm looking for something like the <code>tempfile</code> module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...</p> <p>It seems, .NET does not have the &quot;batteries included&quot; features of the <code>tempfile</code> module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (<code>mkstemp()</code> I think): <a href="https://docs.python.org/library/tempfile.html" rel="nofollow noreferrer">https://docs.python.org/library/tempfile.html</a></p> <hr /> <p>Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...</p>
<p>I've also had the same requirement before, and I've created a small class to solve it:</p> <pre><code>public sealed class TemporaryFile : IDisposable { public TemporaryFile() : this(Path.GetTempPath()) { } public TemporaryFile(string directory) { Create(Path.Combine(directory, Path.GetRandomFileName())); } ~TemporaryFile() { Delete(); } public void Dispose() { Delete(); GC.SuppressFinalize(this); } public string FilePath { get; private set; } private void Create(string path) { FilePath = path; using (File.Create(FilePath)) { }; } private void Delete() { if (FilePath == null) return; File.Delete(FilePath); FilePath = null; } } </code></pre> <p>It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either <code>Dispose</code> or the destructor), it deletes the file. You get the name of the file created (and path) through the <code>FilePath</code> property. You can certainly extend it to also open the file for writing and return its associated <code>FileStream</code>.</p> <p>An example usage:</p> <pre><code>using (var tempFile = new TemporaryFile()) { // use the file through tempFile.FilePath... } </code></pre>
<p>I don't know of any built in (within the framework) classes to do this, but I imagine it wouldn't be too much of an issue to roll your own..</p> <p>Obviously it depends on the type of data you want to write to it, and the "security" required..</p> <p><a href="http://www.developerfusion.co.uk/show/3913/" rel="nofollow noreferrer">This article</a> on DevFusion may be a good place to start?</p>
4,048
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
<p>The answer is no.</p> <p>At least, not until something like the following is implemented:</p> <pre><code>from __future__ import braces </code></pre>
<p>Many Python IDEs and generally-capable text/source editors can handle the whitespace for you.</p> <p>However, it is best to just "let go" and enjoy the whitespace rules of Python. With some practice, they won't get into your way at all, and you will find they have many merits, the most important of which are:</p> <ol> <li>Because of the forced whitespace, Python code is simpler to understand. You will find that as you read code written by others, it is easier to grok than code in, say, Perl or PHP.</li> <li>Whitespace saves you quite a few keystrokes of control characters like { and }, which litter code written in C-like languages. Less {s and }s means, among other things, less RSI and wrist pain. This is not a matter to take lightly.</li> </ol>
8,862
<p>I have a windows service that runs various system monitoring operations. However, when running <code>SNMP</code> related checks, I always get a <code>NullReference exception</code>. </p> <p>The code runs fine when run through the user interface (under my username and password), but always errors running as the service. </p> <p>I've tried running the service as different user accounts (including mine), with no luck. I've tried replacing the <code>SNMP</code> monitoring code with calling the <code>PowerShell cmdlet get-snmp</code> (from the <code>/n NetCmdlets</code>), but that yields the same error.</p> <p>The application I'm working with is <a href="http://codeplex.com/polymon" rel="nofollow noreferrer">PolyMon</a>. </p> <p>Any ideas?</p>
<p>Some ways to debug:</p> <ul> <li>Is there any additional information in the Windows events log?</li> <li>I believe you should be able to listen to some kind of global-exception event like Application_Exception in windows services. I can't remember the exact name but you can atelast dump stack trace from there.</li> <li>You should be able to start debugging the project in service mode.</li> </ul> <p>Some code snippets/stack trace/information will definitely help.</p>
<p>A couple of things we've seen - more about differences between interactive vs services, but might help...</p> <p>One thing we've seen that does not seem relevant is the difference with what is on the user vs system path. </p> <p>Another thing we've seen relates to temporary files - the service we had was creating lots in the windows\temp directory - we tracked this down when it had created something like 65000 of these files and thus hit the limit of what a directory can hold...</p> <p>Regards, Chris</p>
7,106
<p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
<p>It really depends on what you're trying to do, exactly, as it's:</p> <ol> <li>OS dependent</li> <li>Not quite clear what you're trying to do.</li> </ol> <p>Nevertheless, I'll try to provide some information for you to decide.<br> On UNIX, <code>fork()</code> creates a clone of your process from the place where you called fork. Meaning, if I have the following process:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; int main() { printf( "hi 2 u\n" ); int mypid = fork(); if( 0 == mypid ) printf( "lol child\n" ); else printf( "lol parent\n" ); return( 0 ); } </code></pre> <p>The output will look as follows:</p> <blockquote> <blockquote> <p>hi 2 u<br> lol child<br> lol parent </p> </blockquote> </blockquote> <p>When you <code>fork()</code> the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that "hi2u" is only printed once... by the <strong>parent</strong>.</p> <p><code>execve()</code> and its family of functions are almost always used with <code>fork().</code> <code>execve()</code> and the like overwrite the current stackframe with the name of the application you pass to it. <code>execve()</code> is almost always used with <code>fork()</code> where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. <code>execve()</code> is also almost always used with <code>waitpid()</code> -- waitpid takes a pid of a child process and, quite literally, <em>waits</em> until the child terminates and returns the child's exit status to you. </p> <p>Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using <code>fork()</code>, <code>execve()</code> and <code>waitpid()</code>.</p> <p><strong>NOTE: This is *nix specific! This will NOT work on Windows.</strong> </p> <p>Hope this helped.</p>
<p>If you need to check/read/parse the output of your external command, I would suggest to use popen() instead of system().</p>
3,785
<p>If you have Subversion installed on your development machine and you don't work in a team, is there any reason why you should use the <em>svn</em> protocol instead of <em>file</em>?</p>
<p>If you are working by yourself on a single machine, then in my experience using the file:// protocol works fine. Even when my team was using Subversion off a remote server, I would set up a local file-based repository for my own personal projects. If you get to the point where you need to access it from a different machine, then I would go to the trouble of setting up a server-based repository. You might also look at a distributed system like Mercurial - we were evaluating it at my last company just before I left - but definitely pick one or the other, mixing svn and hg doesn't work well at all.</p>
<p>Even if working by myself ... my protocol is to <strong>always</strong> use source control even for personal projects. It gives you a single point of backup for all of your code work, and allows you to change your mind and/or retrieve older versions.</p>
5,255
<p>Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project?</p> <p>What do other people do?</p>
<p>store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case</p> <p>Edit for 2017: This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on .net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example <a href="https://www.sonatype.com/nexus-repository-oss" rel="noreferrer">Sonatype Nexus</a> or <a href="https://www.jfrog.com/open-source/" rel="noreferrer">JFrog Artifcatory</a>, among many others.</p>
<p>store everything you'll need to build the project, so you can check it out and build without doing anything.</p> <p>(and, as someone who has experienced the pain - please keep a copy of everything needed to get the controls installed and working on a dev platform. I once got a project that could build - but without an installation file and reg keys, you couldn't make any alterations to the third-party control layout. That was a fun rewrite)</p>
7,167
<p>Carbon 3d made a 100x faster printer which has a simple and cheap mechanism using a Teflon layer. It appears to have a 20mn in RnD Costs and $7000 mass market production cost.</p> <p>The only access method for one is a USD$ 161,250 yearly subscription.</p> <p>Their printer is not available in shapeways... Is there something wrong with Carbon 3D so that it does not view consumers as a direct market, and has no market news on it's website?</p> <p>How can they spend 222 million in investment money and not have a 3d printer in shapeways or public access? </p>
<p>I will take the question seriously, and consider reasons why Carbon 3D might choose to offer their technology through a yearly subscription, rather than building a product accessible to the consumer market. These reasons are speculation and do not reflect any specific knowledge about Carbon 3D, the details of their technology, or anything unique about their corporate mission.</p> <p>1) The mission of a company, especially in the beginning while competition makes it possible, to make as much money as possible. If the technology is unique and brings good value to a large enough set of interested customers, it can easily consume the full attention of a company to service those customers. The price those companies pay for access may be higher than others would pay because their derived value is higher.</p> <p>2) If a technology is new, and perhaps still somewhat immature, there may be very high support efforts and cost required. Through this time, the learning curve does it's job, the technology improves and matures, and the costs go down.</p> <p>3) If the technology is immature, and perhaps is evolving quickly, it could be to the advantage of a supplier to only offer the technology on a service rather than capital acquisition basis. It simplifies replacing components. </p> <p>4) If the technology is immature, selling the service may be easier than selling the hardware. It simplifies the acquisition process, and makes it easier for customer's to expand their usage since the supplier's capital is used to finance the machines instead of the customer's.</p> <p>5) Even with a mature, proven technology, it can be advantageous to maintain a higher price point. The game is optimizing the profit on volume times price. The point they operate at is influenced by their perception of the market.</p> <p>6) In the early adopter phase, it is critical that the customer experience be stellar. They may be limited in how rapidly they can scale in some critical dimension -- consumables supply chain, manufacturing capacity, trained installation technicians, local service offices, or many other limits. Anything going wrong makes for a bad customer experience.</p> <p>It doesn't surprise me that they aren't going after the consumer market at this time.</p> <p>But, I'm not in the CEO's office, and I don't see where his pain comes from. My purpose here is only to propose some plausible reasons why the company has not launched a consumer facing product.</p>
<p>It looks like they have only one innovation: their resins. Everything else looks like standard SLA. </p> <p>All the things Carbon 3D are pitching on their website are more about having a dedicated support team than some fancy printer, and that's what they're selling. </p> <p>As to why they don't make a home version: why would they? It's <em>at best</em> a distraction from their core business.</p>
667
<p>I've come back to using NHibernate after using other technologies (<a href="http://www.lhotka.net/" rel="nofollow noreferrer">CSLA</a> and <a href="http://subsonicproject.com/" rel="nofollow noreferrer">Subsonic</a>) for a couple of years, and I'm finding the querying a bit frustrating, especially when compared to Subsonic. I was wondering what other approaches people are using?</p> <p>The Hibernate Query Language doesn't feel right to me, seems too much like writing SQL, which to my mind is one of the reason to use an ORM tools so I don't have to, furthermore it's all in XML, which means it's poor for refactoring, and errors will only be discovered at runtime?</p> <p>Criteria Queries, don't seem fluid enough.</p> <p>I've <a href="http://jhollingworth.wordpress.com/2008/03/28/subsonic-like-nhibernate-query-generator-button-in-visual-studio/" rel="nofollow noreferrer">read</a> that Ayende's <a href="http://www.ayende.com/projects/downloads/nhibernate-query-generator.aspx" rel="nofollow noreferrer">NHibernate Query Generator</a>, is a useful tool, is this what people are using? What else is out there?</p> <p>EDIT: Worth a read <a href="http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx" rel="nofollow noreferrer">http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx</a></p>
<p>The thing with LINQ for NHibernate is still in beta; I'm looking forward to NHibernate 2.1, where they say it will finally make the cut.</p> <p>I made a presentation on LINQ for NHibernate around a month ago, you might find it useful. I blogged about it here, including slides and code:</p> <p><a href="http://dotnet.kapenilattex.com/?p=85" rel="nofollow noreferrer">LINQ for NHibernate: O/R Mapping in Visual Studio 2008 Slides and Code</a></p>
<p>scrap nHibernate and go back to Subsonic if you can. In my opinion, Subsonic is a far more fluent and testable ORM/DAL. I absolutely hate HQL what's the point of a weakly typed query in an ORM? And why would I use Linq/nH/SQL when I can just use Linq to SQL and cut out a layer?</p> <p>nHibernate was a good ORM when Subsonic wasn't around, but now, it's just plain awful to work with in comparison. It easily takes me 2 times longer to do stuff with nHibernate vs Subsonic. Testing is a pain since nHibernate is runtime, so now I need to employ a few QA engineers to "click" around the site instead of getting a compile time error.</p>
6,500
<p>Some WPF controls (like the <code>Button</code>) seem to happily consume all the available space in its' container if you don't specify the height it is to have.</p> <p>And some, like the ones I need to use right now, the (multiline) <code>TextBox</code> and the <code>ListBox</code> seem more worried about just taking the space necessary to fit their contents, and no more. </p> <p>If you put these guys in a cell in a <code>UniformGrid</code>, they will expand to fit the available space. However, <code>UniformGrid</code> instances are not right for all situations. What if you have a grid with some rows set to a * height to divide the height between itself and other * rows? What if you have a <code>StackPanel</code> and you have a <code>Label</code>, a <code>List</code> and a <code>Button</code>, how can you get the list to take up all the space not eaten by the label and the button?</p> <p>I would think this would really be a basic layout requirement, but I can't figure out how to get them to fill the space that they could (putting them in a <code>DockPanel</code> and setting it to fill also doesn't work, it seems, since the <code>DockPanel</code> only takes up the space needed by its' subcontrols).</p> <p>A resizable GUI would be quite horrible if you had to play with <code>Height</code>, <code>Width</code>, <code>MinHeight</code>, <code>MinWidth</code> etc. </p> <p>Can you bind your <code>Height</code> and <code>Width</code> properties to the grid cell you occupy? Or is there another way to do this?</p>
<p>There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:</p> <pre><code>HorizontalContentAlignment="Stretch" </code></pre> <p>... to force the contents of a control to stretch horizontally. Or you can say:</p> <pre><code>HorizontalAlignment="Stretch" </code></pre> <p>... to force the control itself to stretch horizontally to fill its parent.</p>
<p>Use the <strong>HorizontalAlignment</strong> and <strong>VerticalAlignment</strong> layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.</p> <p>The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.</p> <p>The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for <strong>HorizontalAlignment</strong> and Top, Center and Bottom for <strong>VerticalAlignment</strong>.</p>
5,677
<p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p> <pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer()); </code></pre> <p>Where ContactServer is a predicate function object.<br> On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p> <p>What do you say?</p>
<p>I think I would go for it.</p> <p>The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.</p> <p>You might want to rename <code>ContactServer</code> to indicate that it is a predicate; <code>CanContactServer</code>? (But then people would complain about hidden side effects. Hmm...)</p>
<p>Isn't that what <code>find_if</code> is for?</p> <p>Note though, that it will find <em>all</em> the servers, if you iterate over the iterator - but you aren't going to do that (according to OP).</p>
4,724
<p>I'm interested in grabbing the EPG data from DVB-T streams. Does anyone know of any C libraries or an alternative means of getting the data?</p>
<p>tv_grab_dvb can do this. See the <a href="http://www.darkskiez.co.uk/svn/tv_grab_dvb/trunk/" rel="nofollow noreferrer">subversion repository</a> for sources.</p> <p>tv_grab_dvb is made to work with the stream grabbed from the DVB-T card using <a href="http://sourceforge.net/projects/dvbtools/" rel="nofollow noreferrer">dvbtools</a> on Linux, but it may be portable to other platforms - I think it just works with the raw data from the stream.</p>
<p>...a new answer to an old question:</p> <p>I wrote a utility called <code>dvbtee</code> that can be used as a c++ library, a cross-platform command line utility, or a node.js module.</p> <p>(despite it being a c++ library, one could still link to it from c code)</p> <p>The command line utility will parse your streams and output the EPG, depending on the arguments you specify, it can generate plain text or a JSON block of data.</p> <p><a href="http://mkrufky.github.io/libdvbtee" rel="nofollow noreferrer">dvbtee: a digital television streamer / parser / service information aggregator supporting various interfaces including telnet CLI &amp; http control</a></p> <p>The node.js module will emit events containing the PSIP table data (along with EPG info)</p> <p><a href="https://www.npmjs.com/package/dvbtee" rel="nofollow noreferrer">node-dvbtee: MPEG2 transport stream parser for Node.js with support for television broadcast PSIP tables</a></p>
8,146
<p>I'm working with a group at the MIT Launch startup accelerator for high school and I was hoping to do some market research regarding some of the current problems with desktop 3D printers. I was hoping to get some feedback from all your experience with 3D printing and the hours of troubleshooting you've likely encountered.</p> <p>What workarounds and aftermarket modifications are the most useful? If you could change one thing about your printer what would it be? How do you troubleshoot issues and how long does it take? What would make you more likely to 3d print more often (ie never clogged, didn't have to watch first layer, etc)? In your opinion, what are the biggest issues the desktop 3D printing industry faces? Just share any wishes, thoughts, hopes, dreams, etc about 3D printing</p> <p>Thank you so much for your time and sharing your experience!</p>
<p>First, regarding <strong>"Why do 3D Printers Suck?"</strong> - The answer is <strong>They Don't!</strong></p> <p>Every tool has its limitations and you need to work withing the limitations of the tool.</p> <p>Second, there are <strong>A LOT</strong> of different types/technologies, manufacturers, and price points and all of these have specific limitations.</p> <p>I live in Tigard, OR and both my boys are in High School. Our High School has a pretty advanced Technologies Department. We have had a 3D printer for a several years and use it for printing parts for our after school programs (we have three FTC teams, one FRC team, and one (underwater) MATE team). This last year the school introduced a CAD class and added about 15-20 new Afina printers so that the students can print what they design.</p> <p>I talked to my sons (they have both used the printers) and they said the only problems they ran into were mistakes they made. Two examples of that are:</p> <ul> <li>Printing with ABS and having it warp (probably bed temp)</li> <li>Trying to print a design with too thin a wall</li> </ul> <p>I think there is a BIG opportunity for improvement here. Having a "Slicing" program that doesn't require tweaking and would warn of likely print problems would help A LOT. I like the idea of the new <a href="http://prusacontrol.org/" rel="nofollow noreferrer">PrusaControl</a>. If this idea could be extended further as <a href="https://www.youtube.com/watch?v=YYqVhhM7XIc" rel="nofollow noreferrer">Thomas Sanladerer suggested in his video review</a></p> <p>I know the Head of Technologies Department (I help mentor several of the after school programs). He has been responsible for getting printers and I recall he was concerned about more high-level things:</p> <ul> <li>Service, Maintenance and Repair</li> <li>Fumes (this is a lot of printers in one place with students in the same room)</li> <li>Network interface and driver compatibility with school computer/network standards.</li> </ul> <p>I believe there is another opportunity here. If you could provide some sort of a "printer farm" where the students could send their print to the "farm" and then have a highly visible indicator on the selected printer would their name/ID when their print starts. That way you can get more efficient use of the printers and the space they consume. </p>
<p>First, regarding <strong>"Why do 3D Printers Suck?"</strong> - The answer is <strong>They Don't!</strong></p> <p>Every tool has its limitations and you need to work withing the limitations of the tool.</p> <p>Second, there are <strong>A LOT</strong> of different types/technologies, manufacturers, and price points and all of these have specific limitations.</p> <p>I live in Tigard, OR and both my boys are in High School. Our High School has a pretty advanced Technologies Department. We have had a 3D printer for a several years and use it for printing parts for our after school programs (we have three FTC teams, one FRC team, and one (underwater) MATE team). This last year the school introduced a CAD class and added about 15-20 new Afina printers so that the students can print what they design.</p> <p>I talked to my sons (they have both used the printers) and they said the only problems they ran into were mistakes they made. Two examples of that are:</p> <ul> <li>Printing with ABS and having it warp (probably bed temp)</li> <li>Trying to print a design with too thin a wall</li> </ul> <p>I think there is a BIG opportunity for improvement here. Having a "Slicing" program that doesn't require tweaking and would warn of likely print problems would help A LOT. I like the idea of the new <a href="http://prusacontrol.org/" rel="nofollow noreferrer">PrusaControl</a>. If this idea could be extended further as <a href="https://www.youtube.com/watch?v=YYqVhhM7XIc" rel="nofollow noreferrer">Thomas Sanladerer suggested in his video review</a></p> <p>I know the Head of Technologies Department (I help mentor several of the after school programs). He has been responsible for getting printers and I recall he was concerned about more high-level things:</p> <ul> <li>Service, Maintenance and Repair</li> <li>Fumes (this is a lot of printers in one place with students in the same room)</li> <li>Network interface and driver compatibility with school computer/network standards.</li> </ul> <p>I believe there is another opportunity here. If you could provide some sort of a "printer farm" where the students could send their print to the "farm" and then have a highly visible indicator on the selected printer would their name/ID when their print starts. That way you can get more efficient use of the printers and the space they consume. </p>
652
<p>I have a classic client/server (fat client and database) program written in Delphi 2006. When certain conditions are met in the client, I need to notify all the other clients very quickly. Up until now this has been done using UDP broadcasts, but this is no longer viable as clients now connect from outside the LAN and the UDP broadcast is limited to the local network. </p> <p>I'm aware of the Indy libraries but am not really sure of which components to use and how to structure it. I'm guessing I'll need to have a server that the clients connect to which will receive and distribute the messages...? Any samples out there to get me started?</p> <p>Are there any other component sets or technologies I should look at instead/as well?</p>
<p>The simple answer is that the standard protocols available in Delphi (and other tools) don't allow for notification in reverse. I looked into this for a project where I wanted to use SOAP. They all assume client asks server, server responds and that's it. </p> <p>For me, the solution was the RemObjects SDK. This allows you to send notifications to clients, and the notification can have any data you like (just like the client to server). Myself I use the SuperTCP connection, but it works with others too. It can still offer a SOAP interface for clients that must use it, but for where you have control of both client and server it works extremely well. </p>
<p>You should be able to use Multicast UDP for the same purpose. The only difference will be to join the multicast group from every client.</p> <p><a href="http://en.wikipedia.org/wiki/IP_Multicast" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/IP_Multicast</a></p> <p><a href="http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol</a></p> <p><strong>Edit:</strong> Just to clarify, multicast let you join a given "group" associated to a multicast ip address. Any packet sent to that address will reach every client who has join the group</p>
8,300
<p>Occasionally, on a ASP (classic) site users will get this error:</p> <pre><code>[DBNETLIB][ConnectionRead (recv()).]General network error. </code></pre> <p>Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?</p>
<p>Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.</p>
<p>I'd seen this error many times. It could be caused by many things including network errors too :).</p> <p>But one of the reason could be built-in feature of MS-SQL. </p> <p>The feature detects DoS attacks -- in this case too many request from web server :).</p> <p>But I have no idea how we fixed it :(.</p>
6,899
<p>Need some advice on working out the team velocity for a sprint.</p> <p>Our team normally consists of about 4 developers and 2 testers. The scrum master insists that every team member should contribute equally to the velocity calculation i.e. we should not distinguish between developers and testers when working out how much we can do in a sprint. The is correct according to Scrum, but here's the problem.</p> <p>Despite suggestions to the contrary, testers never help with non-test tasks and developers never help with non-dev tasks, so we are not cross functional team members at all. Also, despite various suggestions, testers normally spend the first few days of each sprint waiting for something to test. </p> <p>The end result is that typically we take on far more dev work than we actually have capacity for in the sprint. For example, the developers might contribute 20 days to the velocity calculation and the testers 10 days. If you add up the tasks after sprint planning though, dev tasks add up to 25 days and test tasks add up to 5 days.</p> <p>How do you guys deal with this sort of situation?</p>
<p>Since Agile development is about transparency and accountability it sounds like the testers should have assigned tasks that account for their velocity. Even if that means they have a task for surfing the web waiting for testing (though I would think they would be better served developing test plans for the dev team's tasks). This will show the inefficiencies in your organization which isn't popular but that is what Agile is all about. The bad part of that is that your testers may be penalized for something that is a organizational issue.</p> <p>The company I worked for had two separate (dev and qa) teams with two different iteration cycles. The qa cycle was offset by a week. That unfortunatey led to complexity when it came to task acceptance, since a product wasn't really ready for release until the end of the qa's iteration. That isn't a properly integrated team but neither is yours from the sound of it. Unfortunately the qa team never really followed scrum practices (No real planning, stand up, or retrospective) so I can't really tell if that is a good solution or not.</p>
<p>Sounds to me like your system is working, just not as well as you'd like. Is this a paid project? If it is, you could make pay be a meritocracy. Pay people based on how much of the work they get done. This would encourage cross discipline work. Although, it might also encourage people to work on pieces that weren't theirs to begin with, or internal sabotage.</p> <p>Obviously, you'd have to be on the lookout for people trying to game the system, but it might work. Surely testers wouldn't want to earn half of what devs do.</p>
7,080
<p>I recently asked about <a href="https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks">keyword expansion in Git</a> and I'm willing to accept the design not to really support this idea in Git. </p> <p>For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:</p> <pre><code>svn propset svn:keywords "Id" expl3.dtx </code></pre> <p>to keep this string up-to-date:</p> <pre><code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $ </code></pre> <p>But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:</p> <blockquote> <p>"We ignore all SVN properties except svn:executable"</p> </blockquote> <p>But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?</p>
<p>What's going on here: Git is optimized to switch between branches as quickly as possible. In particular, <code>git checkout</code> is designed to not touch any files that are identical in both branches.</p> <p>Unfortunately, RCS keyword substitution breaks this. For example, using <code>$Date$</code> would require <code>git checkout</code> to touch every file in the tree when switching branches. For a repository the size of the Linux kernel, this would bring everything to a screeching halt.</p> <p>In general, your best bet is to tag at least one version:</p> <pre><code>$ git tag v0.5.whatever </code></pre> <p>...and then call the following command from your Makefile:</p> <pre><code>$ git describe --tags v0.5.15.1-6-g61cde1d </code></pre> <p>Here, git is telling me that I'm working on an anonymous version 6 commits past v0.5.15.1, with an SHA1 hash beginning with <code>g61cde1d</code>. If you stick the output of this command into a <code>*.h</code> file somewhere, you're in business, and will have no problem linking the released software back to the source code. This is the preferred way of doing things.</p> <p>If you can't possibly avoid using RCS keywords, you may want to start with this <a href="http://kerneltrap.org/mailarchive/git/2007/10/12/335953" rel="noreferrer">explanation by Lars Hjemli</a>. Basically, <code>$Id$</code> is pretty easy, and you if you're using <code>git archive</code>, you can also use <code>$Format$</code>.</p> <p>But, if you absolutely cannot avoid RCS keywords, the following should get you started:</p> <pre><code>git config filter.rcs-keyword.clean 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/"' git config filter.rcs-keyword.smudge 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date: `date`\\\$/"' echo '$Date$' &gt; test.html echo 'test.html filter=rcs-keyword' &gt;&gt; .gitattributes git add test.html .gitattributes git commit -m "Experimental RCS keyword support for git" rm test.html git checkout test.html cat test.html </code></pre> <p>On my system, I get:</p> <pre><code>$Date: Tue Sep 16 10:15:02 EDT 2008$ </code></pre> <p>If you have trouble getting the shell escapes in the <code>smudge</code> and <code>clean</code> commands to work, just write your own Perl scripts for expanding and removing RCS keywords, respectively, and use those scripts as your filter.</p> <p>Note that you <em>really</em> don't want to do this for more files than absolutely necessary, or git will lose most of its speed.</p>
<p>You could set the ident attribute on your files, but that would produce strings like</p> <pre><code>$Id: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef$ </code></pre> <p>where <code>deadbeef...</code> is the sha1 of the blob corresponding to that file. If you really need that keyword expansion, and you need it in the git repo (as opposed to an exported archive), I think you're going to have to go with the <code>ident</code> gitattribute with a custom script that does the expansion for you. The problem with just using a hook is then the file in the working tree wouldn't match the index, and git would think it's been modified.</p>
8,763
<p>I'm packaging up a .NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=cc96c246-61e5-4d9e-bb5f-416d75a1b9ef&amp;DisplayLang=en" rel="nofollow noreferrer" title="Microsoft Report Viewer Redistributable 2008 Download">download page for Report Viewer 2008</a>, it lists .NET 3.5 as a requirement. </p> <p>Is having .Net 3.5 installed really needed Report Viewer 2008? We targeted .Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks.</p> <p>We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package.</p>
<p>Keep in mind that MSFT might be requiring the 3.5 Framework so they can write against it in future updates/releases, which might place your app in an unsupported (by MSFT) state.</p>
<p>If it works without a hitch then you don't need .NET 3.5 Framework for now. Installing .NET 3.5 Framework is easy enough to do along with later versions of your software <em>if and only if your software stops working at that point</em>.</p>
4,056
<p>I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following:</p> <pre><code># This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError =&gt; mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end </code></pre> <p>Everything works except it does not find a Reverse DNS.</p> <p>Sample output that I'm getting is this:</p> <pre><code>10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 </code></pre> <p>If I do <code>nslookup 10.26.6.12</code> then I get the correct reverse DNS so that shows that my machine is seeing the DNS server.</p> <p>I have tried <code>Socket.gethostbyname</code>, <code>gethostbyaddr</code>, but it doesn't work.</p> <p>Any guidance will be much appreciated.</p>
<p>Today I also needed reverse DNS lookup and I've found very simple standard solution:</p> <pre><code>require 'resolv' host_name = Resolv.getname(ip_address_here) </code></pre> <p>It seems it uses timeout which helps in rough cases.</p>
<p>This also works:</p> <pre><code>host_name = Socket.getaddrinfo(current_ip,nil) append_to_file("#{host_name[0][2]} - #{current_ip} - #{mac_addr}\n") </code></pre> <p>I'm not sure why <code>gethostbyaddr</code> didn't also work.</p>
2,513
<p>I am wondering if there is a method or format string I'm missing in .NET to convert the following:</p> <pre><code> 1 to 1st 2 to 2nd 3 to 3rd 4 to 4th 11 to 11th 101 to 101st 111 to 111th </code></pre> <p><a href="http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx" rel="noreferrer">This link</a> has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.</p> <p><strong>Solution</strong></p> <p>Scott Hanselman's answer is the accepted one because it answers the question directly.</p> <p>For a solution however, see <a href="https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284">this great answer</a>.</p>
<p>No, there is no inbuilt capability in the .NET Base Class Library.</p>
<p>I think the ordinal suffix is hard to get... you basically have to write a function that uses a switch to test the numbers and add the suffix.</p> <p>There's no reason for a language to provide this internally, especially when it's locale specific.</p> <p>You can do a bit better than that link when it comes to the amount of code to write, but you have to code a function for this...</p>
9,466
<p>The surfaces of my printed parts using PLA plastic look rough and uneven.</p> <p>Would changing filament to a better one make any difference?</p> <p>If not, what kind of methods can I use to achieve a smoother finish for my for 3D-printed objects?</p>
<p><a href="https://en.wikipedia.org/wiki/Polylactic_acid">PLA</a> parts can be finished with a coat of epoxy like <a href="http://www.smooth-on.com/Epoxy-Coatings-XTC/c1397_1429/index.html">XTC-3D from Smooth-On</a>. This will smooth out the part and give it a pretty nice shine.</p> <p>I've also had a fair amount of success sanding prints, giving them a coat of automotive filler primer, and using glossy spray paint.</p> <p>You can also get great results with an acetone <a href="https://en.wikipedia.org/wiki/Vapor_polishing">vapor finish</a> if you're willing to switch to <a href="https://en.wikipedia.org/wiki/Acrylonitrile_butadiene_styrene">ABS</a>. Though that will require a heated bed and can be a bit more finicky to work with than PLA.</p>
<p>It is called <strong>Acetone Finishing</strong></p> <p>Basically the 3D printed part stays in acetone vapor and the outer shell turns to smooth surface. I have heard that it works better with ABS. </p> <p>This article shows how <em>with videos</em>:</p> <ul> <li>(<a href="https://ultimaker.com/en/community/10412-acetone-finishing-on-pla" rel="nofollow noreferrer">Acetone Finishing on PLA</a> - dead link). </li> <li>New link: <a href="https://community.ultimaker.com/topic/8530-acetone-finishing-on-pla/" rel="nofollow noreferrer">Acetone Finishing on PLA</a> </li> </ul>
89
<p>This is regarding the circuit of my 3D printer Tronxy X5SA's stepper motor for X axis.</p> <p><strong>I had an observation:</strong> It has a cooling fan (40X10 24V) which is having issues lately - it stops working sometimes, and when pushed to rotate, spins back.</p> <p><strong>Problem:</strong> Now one of the stepper motors (NEMA 17 ~3.5kgfcm) in my core XY has been malfunctioning, where it misses rotation sometimes out of the blue, which shifts the whole print. I thought this is due to the driver limiting the current to the motor, so I rotated the screw terminal clockwise a bit more to allow more current for the motor. This works fine for a while, but the problem comes back.</p> <p>Now, I also noticed a few times that this issue occurred when the cooling fan for the drivers stopped working.</p> <p>Can the stopping of the cooling fan cause the stepper motor to falter?</p> <p>Another observation is that the stepper motor which is faltering is placed close to another stepper motor. Although I know stepper motors can work in extreme conditions, can this cause the issue?</p> <p>If you require any more info to investigate the issue, please do let me know</p>
<p>I think this is resolved. After looking at every conceivable source of over-extrusion and coming up negative, <code>R.. GitHub STOP HELPING ICE</code> suggested that it might be a mechanical problem in Z axis movement, like in <a href="https://3dprinting.stackexchange.com/questions/8022/first-3-mm-prints-poorly-then-fine-after-that">this question</a>.</p> <p>I checked by leveling the bed and zeroing the Z axis at 0.05 mm above the bed, using a feeler gauge. I gave it the instruction to move the Z axis up by 0.2 mm (to simulate a single layer), then checked it with a 0.25 mm feeler gauge. It did not fit. I raised it .01 mm at a time, and I was not able to insert the gauge until it hit 0.5 mm!</p> <p>I printed a 20 mm test cube and measured the Z height: <a href="https://i.stack.imgur.com/4Lvq2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/4Lvq2.jpg" alt="Initial 20 mm test cube" /></a></p> <p>At 19.58 mm, it was short. Only a little bit though, which is consistent with Z problems only occurring in the first few layers for some reason.</p> <p>Based on the advice in the other question, I fiddled with the eccentric nuts on the left and right side of X axis gantry, adjusting them to be tight enough that turning the wheels moves the gantry up and down, but loose enough that I can still turn the wheels if I hold the gantry in place.</p> <p>I checked again with the feeler gauge, and this time the 0.25 mm gauge fit just fine at 0.2 mm. Cool! I printed another test cube and measured:</p> <p><a href="https://i.stack.imgur.com/Yq2zW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Yq2zW.jpg" alt="Revised 20 mm test cube" /></a></p> <p>OK, at 20.06 mm it's not perfect, but it's a lot better. I printed the hinges again:</p> <p><a href="https://i.stack.imgur.com/Q4MYZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Q4MYZ.jpg" alt="Hinges" /></a></p> <p>Again not perfect, but so much better. And the specific problem of uncontrollable expansion in the 2nd and 3rd layers is totally gone.</p>
<p>I had the same problem with my Ender-3 V2.</p> <p>You need to check if the feeder bracket is square like explained in <a href="https://www.youtube.com/watch?v=xnzNd_FIMKY" rel="nofollow noreferrer">this YouTube</a></p> <p>If that is not the problem maybe you need a custom bracket to change the spacing between the Z-motor and the frame like <a href="https://www.thingiverse.com/thing:2752080" rel="nofollow noreferrer">this</a>, <a href="https://www.thingiverse.com/thing:4699747" rel="nofollow noreferrer">this</a> or <a href="https://www.thingiverse.com/thing:4723087" rel="nofollow noreferrer">this</a></p> <p>I have improved mine a lot using:</p> <ul> <li><a href="https://www.thingiverse.com/thing:2752080" rel="nofollow noreferrer">This Z-motor mount</a></li> <li>Using <a href="https://www.amazon.com/s?k=Elmer%E2%80%99s+Disappearing+Purple+Glue+Stick" rel="nofollow noreferrer">glue stick</a> instead of squeezing the first layer</li> <li><a href="https://www.youtube.com/watch?v=rDm9OziZ6dY" rel="nofollow noreferrer">Leveling the bed using a feeler gauge</a> instead of a piece of paper</li> <li>Initial fan speed 100 %, all layers the same</li> <li>Same flow rate, line width, line height on all layers</li> <li>Build plate 40 °C, nozzle 205 °C</li> <li>Seam Corner Preference: Hide or Expose Seam</li> </ul>
1,696
<p>Has anyone had a chance to dig into how <a href="http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx" rel="noreferrer">F# Units of Measure</a> work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other .net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)?</p>
<p>According to a <a href="http://blogs.msdn.com/andrewkennedy/archive/2008/08/22/units-of-measure-in-f-part-two-unit-conversions.aspx#8920660" rel="noreferrer">response</a> on the next related blog post, they are a purely static mechanism in the F# compiler. So there is no CLR representation of the units data.</p> <p>Its not entirely clear whether it currently works with non-float types, but from the perspective of the type system it is theoretically possible. </p>
<p>The best (and I think official) place to find out about this is on Andrew Kennedy's blog.</p> <p>Here are the (current) relevant posts.</p> <ul> <li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-one-introducing-units" rel="nofollow noreferrer">Units of Measure in F#: Part One, Introducing Units</a></li> <li><a href="http://web.archive.org/web/20100118052651/http://blogs.msdn.com/andrewkennedy/archive/2008/09/02/units-of-measure-in-f-part-two-unit-conversions.aspx" rel="nofollow noreferrer">Units of Measure in F#: Part Two, Unit Conversions</a></li> <li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-three-generic-units" rel="nofollow noreferrer">Units of Measure in F#: Part Three, Generic Units</a></li> <li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-four-parameterized-types" rel="nofollow noreferrer">Units of Measure in F#: Part Four, Parameterized Types</a></li> </ul> <p>As I said in the post that your answerer referred to, this is most definitely something that you CAN'T do in C# (though I wish you could).</p>
6,211
<p>At the moment there are two tags related to fans:</p> <ul> <li><a href="https://3dprinting.stackexchange.com/questions/tagged/print-fan" class="post-tag" title="show questions tagged &#39;print-fan&#39;" rel="tag">print-fan</a></li> <li><a href="https://3dprinting.stackexchange.com/questions/tagged/fans" class="post-tag" title="show questions tagged &#39;fans&#39;" rel="tag">fans</a></li> </ul> <p>If you look at the topics there is no distinction which fans are meant, this must be read in the questions.</p> <p>Should we create separate tags for specific fan applications?</p>
<p>There aren't that many topics labelled with either one of the existing tags, so re-tagging will not be a problem.</p> <p>Indeed these tags are generic tags and do not cover the range of fans specifically for the application they are used for. There are 3 types of applications for fans in 3D printers, </p> <ul> <li>electronics cooling fans (board/stepper/stepper drivers cooling), </li> <li>part cooling fans (filament cooling after deposition), and </li> <li>cold end cooling fans (extruder cold end cooling).</li> </ul> <p>How about making 3 categories and re-tag? (in the same order as the previous list)</p> <ul> <li><a href="https://3dprinting.stackexchange.com/questions/tagged/electronics-fan" class="post-tag" title="show questions tagged &#39;electronics-fan&#39;" rel="tag">electronics-fan</a>,</li> <li><a href="https://3dprinting.stackexchange.com/questions/tagged/part-cool-fan" class="post-tag" title="show questions tagged &#39;part-cool-fan&#39;" rel="tag">part-cool-fan</a> (or <a href="https://3dprinting.stackexchange.com/questions/tagged/filament-fan" class="post-tag" title="show questions tagged &#39;filament-fan&#39;" rel="tag">filament-fan</a> or <a href="https://3dprinting.stackexchange.com/questions/tagged/print-fan" class="post-tag" title="show questions tagged &#39;print-fan&#39;" rel="tag">print-fan</a>), and</li> <li><a href="https://3dprinting.stackexchange.com/questions/tagged/extruder-fan" class="post-tag" title="show questions tagged &#39;extruder-fan&#39;" rel="tag">extruder-fan</a>.</li> </ul> <p>Alternatively, we could just use a single tag and let the poster make sure that he explains clearly which fan is used.</p>
<p>3 tags is probably overly complex. I've not looked at the question list but I expect that these questions should also have a print quality or electronics tag, making the categorisation of the question fairly clear. The problem to me of having several tags is choosing which one would be relevant to a question, and also having to literally look through all the individual tags if you were looking for a question that matches a certain type of issue.</p> <p>Looking at the questions so far, the vast majority are discussing the part cooling fans, or the distinction between part cooling and extruder/heatbreak cooling. I don't see any questions about specifically cooling the circuit board as was indicated in the tag wiki for <a href="https://3dprinting.stackexchange.com/questions/tagged/print-fan" class="post-tag" title="show questions tagged &#39;print-fan&#39;" rel="tag">print-fan</a>.</p> <p>Given the potential confusion about what a fan is for, and the lack of a need so far to identify questions about PSU cooling, a single <a href="https://3dprinting.stackexchange.com/questions/tagged/fans" class="post-tag" title="show questions tagged &#39;fans&#39;" rel="tag">fans</a> tag still makes sense.</p> <p>Tags can be combined as <a href="https://3dprinting.stackexchange.com/questions/tagged/fans" class="post-tag" title="show questions tagged &#39;fans&#39;" rel="tag">fans</a> <a href="https://3dprinting.stackexchange.com/questions/tagged/print-quality" class="post-tag" title="show questions tagged &#39;print-quality&#39;" rel="tag">print-quality</a>, or <a href="https://3dprinting.stackexchange.com/questions/tagged/fans" class="post-tag" title="show questions tagged &#39;fans&#39;" rel="tag">fans</a> <a href="https://3dprinting.stackexchange.com/questions/tagged/power-supply" class="post-tag" title="show questions tagged &#39;power-supply&#39;" rel="tag">power-supply</a>, but tags can't rely on being combined to make sense.</p>
51
<p>Can anyone out there recommend a good online resource for CSS 'design patterns'?</p> <p>I know design patterns in a software context usually refer to OO based design patterns, but I mean design patterns in the broader sense of the term: i.e. common, clean solutions to common problems / tasks.</p> <p>An example of such a resource would be <a href="http://www.smashingmagazine.com/2008/08/13/top-10-css-table-designs/" rel="noreferrer">this list of table designs</a>, this gives you all you really need to know about how to make tables look nice using a set of CSS techniques.</p> <p>Other examples of common problems which could have nice set solutions would be things like rounded corners on divs, highly usable form layouts etc.</p>
<p><strong>Some websites that address web design patterns are listed below</strong>. They do not specifically provide the HTML and/or CSS in order to achieve the desired results, but they do provide examples of live sites that you can <em>view source</em> on (or, even better, use <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a>).</p> <h2><a href="http://ui-patterns.com/" rel="noreferrer">UI-patterns</a></h2> <p>This is probably the best of the bunch. It breaks things down into categories that cover the breadth of web page design tasks. You'll find categories such as tag-clouds, live preview and user registration among many others. This is a really comprehensive resource that is well organized. It explains each pattern and provides plenty of examples.</p> <h2><a href="http://patterntap.com/" rel="noreferrer">Pattern Tap</a></h2> <p>Similar to UI-Patterns although currently not as comprehensive. It takes a more social approach to collating design patterns by allowing users to create their own categories ("user sets") and populate them with their own selection of sites.</p> <h2><a href="http://developer.yahoo.com/ypatterns/" rel="noreferrer">Yahoo Design Pattern Library</a></h2> <p>Unlike the other two, this one doesn't provide many examples of real sites. It is well organized and quite comprehensive.</p> <h2><a href="http://www.smileycat.com/design_elements/" rel="noreferrer">Elements of Design</a></h2> <p>This is a blog showcasing various elements of web design. It doesn't discuss the patterns, but is good as a quick source of inspiration, or as a means to start your own analysis.</p>
<p>The already mentioned <a href="http://www.alistapart.com/" rel="nofollow noreferrer">A List Apart</a> is really good. Another site I've used since I started web development is SitePoint.com. Here is their <a href="http://reference.sitepoint.com/css" rel="nofollow noreferrer">CSS Reference</a>. If you want a good CSS book their's is one of my favorites.</p>
5,616
<p>I am trying to print the 3 jaw lathe chuck on <a href="https://www.thingiverse.com/thing:624625" rel="nofollow noreferrer">Thingiverse</a>. This specific piece is the scroll.stl, but it applies on every big piece. The print material is (transparent) PLA, that I print on custom glass bed, which is heated by a regular heated bed at 65&nbsp;°C. However, my print is warping on the external edges of a solid 2&nbsp;mm for a 85&nbsp;mm diameter print.</p> <p><a href="https://i.stack.imgur.com/O7rCP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O7rCP.jpg" alt="Print warping"></a></p> <p>I didn't use the cooling fan. And I don't have an enclosure to keep the warmth inside the printing area. The nozzle temperature is around 200&nbsp;°C.</p> <p>What could be wrong? The printer is a slightly modified Prusa i3 MK2.</p>
<p>Several things I've done to stop warping when it occurred:</p> <ol> <li><p>Use a wider brim.</p></li> <li><p>If the brim isn't sticking, use a higher bed temperature for the first layer.</p></li> <li><p>If the brim comes up only on one side or warping is only on one side, make sure the bed is level. </p></li> <li><p>Slowing down the print will keep you from having as long of a strand cooling down. This will lower the contraction force and reduce warping. </p></li> <li><p>A hotter bed temperature will reduce the temperature difference between the extrusion and the bed, thus reducing the contraction force. </p></li> </ol> <p>200&nbsp;°C is a good temperature for getting PLA to stick. I've tried lower extrusion temperatures to reduce the temperature difference between the extruder and the bed, but this decreases adhesion to the bed and is counterproductive. </p>
<p>Glass is tricky. Try using a glue stick. It makes the problem getting it off more than keeping it on. Magigoo and Aquanet also come highly recommended for glass. Another thing would be printing with a raft. Raft's stick pretty well, and most prints stick to a raft, and those prints won't lift. A third trick would be using an extrusion multiplier <em>on your first layer only.</em> As far as slicer tricks go, check to see when (if at all) your cooling fans turn on. usually, fans will turn on about 12-15 layer into your print. Any earlier, and they may peel. Bed level, although crucial to have to some degree of accuracy, is somewhat nullified when a raft is used. </p> <p>Hope that helps!</p>
1,289
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
<p>p1.py:</p> <pre><code>execfile(&quot;p2.py&quot;) </code></pre> <p>p2.py:</p> <pre><code>import inspect, os print (inspect.getfile(inspect.currentframe())) # script filename (usually with path) print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory </code></pre>
<p>I used the approach with __file__<br> <code>os.path.abspath(__file__)</code><br> but there is a little trick, it returns the .py file when the code is run the first time, next runs give the name of *.pyc file<br> so I stayed with:<br> <code>inspect.getfile(inspect.currentframe())</code><br> or<br> <code>sys._getframe().f_code.co_filename</code> </p>
7,327
<p>What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?</p> <p>Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.</p>
<p>I'm sure there is an easier way, but you could loop through the sysobjects table in the database and grant permissions to any user table objects that exist. You could then run that multiple times whenever new tables are added.</p>
<p>We use something similar where I work. Looping through every Tables, Views, Stored Procedures of the system. </p> <pre><code>CREATE PROCEDURE dbo.SP_GrantFullAccess @username varchar(300) AS DECLARE @on varchar(300) DECLARE @count int SET @count = 0 PRINT 'Granting access to user ' + @username + ' on the following objects:' DECLARE c CURSOR FOR SELECT name FROM sysobjects WHERE type IN('U', 'V', 'SP', 'P') ORDER BY name OPEN c FETCH NEXT FROM c INTO @on WHILE @@FETCH_STATUS = 0 BEGIN SET @count = @count + 1 EXEC('GRANT ALL ON [' + @on + '] TO [' + @username + ']') --PRINT 'GRANT ALL ON [' + @on + '] TO ' + @username PRINT @on FETCH NEXT FROM c INTO @on END CLOSE c DEALLOCATE c PRINT 'Granted access to ' + cast(@count as varchar(4)) + ' object(s).' GO </code></pre>
6,654
<p>In the linux file system, where should user scripts be placed?</p> <p>I'm thinking specifically python scripts to be called by cron.</p>
<p>the information i got:</p> <pre><code>/usr/local/sbin custom script meant for root /usr/local/bin custom script meant for all users including non-root </code></pre> <p>chatlog snips from irc.debian.org #debian:</p> <pre><code>(02:48:49) c33s: question: where is the _correct_ location, to put custom scripts for the root user (like a script on a webserver for createing everything needed for a new webuser)? is it /bin, /usr/local/bin,...? /usr/local/scripts is mentioned in (*link to this page*) (02:49:15) Hydroxide: c33s: typically /usr/local/sbin (02:49:27) Hydroxide: c33s: no idea what /usr/local/scripts would be (02:49:32) Hydroxide: it's nonstandard (02:49:53) Hydroxide: if it's a custom script meant for all users including non-root, then /usr/local/bin (02:52:43) Hydroxide: c33s: Debian follows the Filesystem Hierarchy Standard, with a very small number of exceptions, which is online in several formats at http://www.pathname.com/fhs/ (also linked from http://www.debian.org/devel/ and separately online at http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html) (02:53:03) Hydroxide: c33s: if you have the debian-policy package installed, it's also in several formats at /usr/share/doc/debian-policy/fhs/ on your system (02:53:37) Hydroxide: c33s: most linux distributions follow that standard, though usually less strictly and with more deviations than Debian. </code></pre> <p>thanks go out to Hydroxide</p>
<p>You can also add paths to your crontab file as shown in a <a href="https://stackoverflow.com/questions/13204/why-doesnt-my-cron-job-work-properly#13220">previous cron-related question</a>.</p>
3,595
<p>I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?</p>
<p>Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.</p> <p>You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:</p> <pre><code>public static class CommandBank { /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; } /// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); // ... } </code></pre> <p>Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:</p> <pre><code>/// Closes the window provided as a parameter public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e) { ((Window)e.Parameter).Close(); } /// Allows a Command to execute if the CommandParameter is not a null value public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Parameter != null; e.Handled = true; } </code></pre> <p>The second method there can even be shared with other Commands without me having to repeat it all over the place.</p> <p>Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.</p> <pre><code>public partial class SimpleWindow : Window { private void WindowLoaded(object sender, RoutedEventArgs e) { // ... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull)); foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count &gt; 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } } // menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; // ... } // .... } </code></pre> <p>I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.</p> <p>Let me know if you have any follow up questions. :)</p>
<p>The thing about XAML is that it is fine for 'simple' programs, but sadly, it doesn't work well when you want to do things like share functions. Say you have several classes and UI's all of which had commands that were never disabled, you'd have to write a 'CanAlwaysExecute' method for each Window or UserControl! That's just not very <em>DRY</em>.</p> <p>Having read several blogs and through trying several things, I've made the choice to make XAML purely about looks, styles, animation and triggers. All my hooking up of event handlers and commanding is now down in the code-behind. :)</p> <p>Another gotcha by the way is Input binding, in order for them to be caught, focus must be on the object that contains the Input bindings. For example, to have a short cut you can use at any time (say, F1 to open help), that input binding must be set on the Window object, since that always has focus when your app is Active. Using the code method should make that easier, even when you start using UserControls which might want to add input bindings to their parent Window.</p>
2,990
<p>I'm struggling to find the right terminology here, but if you have jQuery object...</p> <pre><code>$('#MyObject') </code></pre> <p>...is it possible to extract the base element? Meaning, the equivalent of this:</p> <pre><code>document.getElementById('MyObject') </code></pre>
<p>Yes, use <code>.get(index)</code>. According to the <a href="https://api.jquery.com/get/#get1" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>The <code>.get()</code> method grants access to the DOM nodes underlying each jQuery object.</p> </blockquote>
<p>A jQuery object is a set of elements. In your case, a set of one element. This differs from certain other libraries, which wrap single elements and provide alternate syntax for selectors that return multiple matches. </p> <p><em><a href="https://stackoverflow.com/questions/47837/getting-the-base-element-from-a-jquery-object#47848">Aaron W</a> and <a href="https://stackoverflow.com/questions/47837/getting-the-base-element-from-a-jquery-object#47844">VolkerK</a> already explained how to access the first (index 0) element in the set.</em></p>
7,011
<p>Can anyone advise on how to crop an image, let's say jpeg, without using any .NET framework constructs, just raw bytes? Since this is the only* way in Silverlight...</p> <p>Or point to a library?</p> <p>I'm not concerned with rendering i'm wanting to manipulate a jpg before uploading.</p> <p>*There are no GDI+(System.Drawing) or WPF(System.Windows.Media.Imaging) libraries available in Silverlight.</p> <p>Lockbits requires GDI+, clarified question</p> <p>Using fjcore: <a href="http://code.google.com/p/fjcore/" rel="nofollow noreferrer">http://code.google.com/p/fjcore/</a> to resize but no way to crop :(</p>
<p><a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a> does a pretty good job. If you're ok with handing off editing tasks to your server...</p> <p>(Seriously? The recommended way of manipulating images in Silverlight is to work with <em>raw bytes</em>? That's... incredibly lame.)</p>
<p>where is silverlight executed? Is there any reason at all to send an complete picture to the client to make the client crop it? Do it on the server... (if you are not creating an image editor that is..)</p>
5,769
<p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p> <p>If it's not, how would you do it with POST? Just out of curiosity.</p> <p>Cheers!</p>
<p>You can actually do it all with GET methods. However, you'll want to use a full challenge response protocol for the logins. (You can hash on the client side using javascript. You just need to send out a unique challenge each time.) You'll also want to use SSL to ensure that no one can see the strings as they go across.</p> <p>In some senses there's no real security difference between GET and POST requests as they both go across in plaintext, in other senses and in practice... GET is are a hell of a lot easier to intercept and is all over most people's logs and your web browser's history. :)</p> <p>(Or as suggested by the other posters, use a different method entirely like HTTP auth, digest auth or some higher level authentication scheme like AD, LDAP, kerberos or shib. However I kinda assumed that if you didn't have POST you wouldn't have these either.)</p>
<p>Logging in securely is very subjective. Full 'security' is not easy to achieve (if at all possible...debatable). However, you can come close. </p> <p>If POST is not an option, maybe you can use a directory security method such as .htaccess or windows authentication depending on what system you're on.</p> <p>Both of the above will get you the pop-up window that allows for a username and password to be entered.</p> <p>To use POST as the method to send the login credentials, you'd just use an HTML form with method="post" and retrieve the information from, say, a PHP or ASP page, using the $_POST['varname'] method in PHP or the request.form("varname") method in ASP. From the PHP or ASP page, as an example, you can do a lookup in a database of users, to see if that username/password combination exists, and if so, redirect them to the appropriate page.</p> <p>As reference, use <a href="http://www.w3schools.com/ASP/showasp.asp?filename=demo_simpleform" rel="nofollow noreferrer">http://www.w3schools.com/ASP/showasp.asp?filename=demo_simpleform</a> for the HTML/ASP portion</p>
9,540
<p>I currently use nant, ccnet (cruise control), svn, mbunit. I use msbuild to do my sln build just because it was simpler to shell out. </p> <p>Are there any merits to switching my whole build script to MSBuild? I need to be able to run tests, watir style tests, xcopy deploy. Is this easier?</p> <p><strong>Update: Any compelling features that would cause me to shift from nant to msbuild?</strong></p>
<p>I like MSBuild. One reason is that .csproj files are msbuild files, and building in VS is just like building at the command line. Another reason is the good support from TeamCity which is the CI server I've been using. If you start using MSBuild, and you want to do more custom things in your build process, get the <a href="http://msbuildtasks.tigris.org/" rel="noreferrer">MSBuild Community Tasks</a>. They give you a bunch of nice extra tasks. I haven't used NAnt for several years now, and I haven't regretted it.</p> <p>Also, as Ruben mentions, there are the <a href="http://www.codeplex.com/sdctasks" rel="noreferrer">SDC Tasks</a> tasks on CodePlex.</p> <p>For even more fun, there is the <a href="http://www.codeplex.com/MSBuildExtensionPack" rel="noreferrer">MSBuild Extension Pack on CodePlex</a>, which includes a twitter task.</p>
<p>I use MSBuild <em>alongside</em> Nant, because the current version of Nant can't as yet compile .NET 3.5 applications (same was true when .NET 2.0 first came out).</p>
3,183
<p>On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that: </p> <pre><code>[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1 [08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed. </code></pre> <p>First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.</p> <p>The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.</p> <p>Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?</p> <p>Thanks</p>
<p><a href="http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx" rel="nofollow noreferrer">Here is an article describing what might be your problem.</a></p>
<p>I also experienced it on my XP.</p> <p>I searched for it, and the result was that some kind of beta .NET remained on my PC.</p> <p>There is a <a href="http://blogs.msdn.com/astebner/archive/2005/04/08/406671.aspx" rel="nofollow noreferrer">tool to remove all</a> .NET framework from the system. I run it and after it I successfully installed 3.5 SP1.</p>
4,731
<p>SQL:</p> <pre><code>SELECT u.id, u.name, isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h ON u.id=h.id AND h.dateCol&lt;GETDATE()-1 GROUP BY u.Id, u.name </code></pre>
<p>A solution, albeit one that defers handling of the null value to the code, could be:</p> <blockquote> <p>DateTime yesterday = DateTime.Now.Date.AddDays(-1);</p> </blockquote> <pre><code>var collection= from u in db.Universe select new { u.id, u.name, MaxDate =(DateTime?) ( from h in db.History where u.Id == h.Id &amp;&amp; h.dateCol &lt; yesterday select h.dateCol ).Max() }; </code></pre> <p>This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward.</p>
<p>This isn't a full answer for you, but on the left join piece you can use the DefaultIfEmpty operator like so:</p> <pre><code>var collection = from u in db.Universe join history in db.History on u.id = history.id into temp from h in temp.DefaultIfEmpty() where h.dateCol &lt; DateTime.Now.Date.AddDays(-1) select u.id, u.name, h.dateCol ?? '1900-01-01' </code></pre> <p>I haven't had the need to do any <code>groupby</code> commands yet, so I left that out as to not send you down the wrong path. Two other quick things to note. I have been unable to actually join on two parameters although as above there are ways to get around it. Also, the ?? operator works really well in place of the <code>isnull</code> in SQL. </p>
2,325
<p>Are there SLA printable resins that can be printed with optical clarity and whose index of refraction make them potentially useful for optical applications? I would assume the surface may need polishing, and that's okay - I'm just asking whether the materials and process are otherwise suitable.</p>
<p>No, at least not at a consumer level. The layering created by the printing process would create imperfections, and clear resin frequently yellows if not cured properly and then protected form strong UV light. Resins that do not yellow tend to have a blue cast to them.</p> <p>You would be better off using a commercial grade casting resin and a pressure chamber to remove bubbles. Even then it would be inferior to silicates for even basic lenses.</p>
<h1>Clear Resin isn't clear everywhere</h1> <p>Any light-curing resin has a specific bandwidth to which it is totally opaque just to be able to cure. This is typically a blue color, but at this and adjacent wavelength, the lens will not allow light to pass through it, no matter if you can manage to get imperfections down.</p> <h1>Resins change color</h1> <p>Then there is the problem of resins changing coloration. Most cast resins become yellow, and some go blue, but in either case, they do absorb some spectrum to appear as this color.</p>
2,153
<p>To date I have used <a href="http://replicat.org/" rel="nofollow noreferrer">RepG</a> and <a href="https://www.repetier.com/" rel="nofollow noreferrer">Repetier with CuraEngine</a> to do my slicing. In various instances when printing a layer of a cylinder it will start in the middle and head out toward either side. Then it moves the nozzle back to the center and prints toward the other side.</p> <p>Knowledge of <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="nofollow noreferrer">TSP</a> suggests the print would go a lot quicker if the travel operation back to the middle were omitted. Here is an <a href="https://www.youtube.com/watch?v=hjGYc03HGU8&amp;feature=youtu.be" rel="nofollow noreferrer">example</a>.</p> <p>By that I mean that to fill the layer of a cylinder from one edge, across the middle to the edge on the right.</p> <p>My question is why is this done? <strong>What advantage does printing it in two passes have over printing it in one pass?</strong></p>
<p>I have seen this behavior a lot in CuraEngine slices. Mostly older versions of the slicer. Not sure if they actually improved it. You could see this a lot in long and complicated forms. I also don't like this. Not only for unnecessary moves, but also for imperfections due the start in the middle. Sometimes you can tell where the filling started and which segments were printed separately.</p> <p>I think it comes down to several issues here: 1.) Starting from the middle saves a move at the beginning of the fill. It probably starts the fill where is stopped printing the perimeter. If the change you want would be implemented, a move after the fill printing would become necessary to start at the right position. So therefore the benefit of faster printing might be gone already.</p> <p>2.) For the sclicer implementation it is hard to do. The algorithm that computes the print moves for the fill just knows the start point (end position of last perimeter line) and the points that define the area. It does not know if the area is round or square or shaped like a "C" or like a "Y". Usually the slicers have a preferred direction that changes with every layer. This way the fill lines of different layers cross each other and that probably increases stability. I have seen slices where the fill started several times in "C" shaped prints. Also if you think about the "Y" shape. If you start at the bottom then you can print horizontal lines and fill the form until you reach the split. Now you have to decide which arm to print fist. And then you have to do the other arm separately. As you can see a perfect way to fill all possible shapes in one go is impossible. And defining an algorithm that can fill any shape with only knowing the outline is already hard. I assume the solution has to do with splitting a form into segments and to then fill each segment after the other. Even your example form has probably more sections than only the two obvious ones.</p> <p>What could be done would be to "optimize" the sequence used to fill the segments. Basically adding a computing step that checks if by introducing a move to the best starting point the fill of the segments could be done in one move.</p> <p>Again that is probably rather hard to do, but CuraEngine and other slicers are open source, so if you or somebody else would like to invest some time to get this feature that would be great!</p>
<p>It doesn’t really have much of effect in the actual print. I’m pretty sure the setting can be modified either in the GUI or through gcode. Usually it’s just the standard process when filling in a flat surface. There could be some minor benefits that are quality related. But my main assumption would be for ironing if you have that setting enabled. It would allow it to smooth it better starting from the middle.</p>
1,521
<p>Having read the threads <a href="https://stackoverflow.com/questions/60919/is-sqlcommanddispose-enough">Is SqlCommand.Dispose enough?</a> and <a href="https://stackoverflow.com/questions/23867/closing-and-disposing-a-wcf-service">Closing and Disposing a WCF Service</a> I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?</p>
<h3>I want to clarify this situation.</h3> <p>According to Microsoft guidelines, it's a good practice to provide <code>Close</code> method where suitable. <a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern" rel="noreferrer">Here</a> is a citation from <a href="https://rads.stackoverflow.com/amzn/click/com/0321246756" rel="noreferrer" rel="nofollow noreferrer">Framework design guidelines</a></p> <blockquote> <p>Consider providing method <code>Close()</code>, in addition to the <code>Dispose()</code>, if close is standard terminology in the area. When doing so, it is important that you make the <code>Close</code> implementation identical to <code>Dispose</code> ...</p> </blockquote> <p>In most of cases <code>Close</code> and <code>Dispose</code> methods are equivalent. The <strong>main difference</strong> between <code>Close</code> and <code>Dispose</code> in the case of <code>SqlConnectionObject</code> is:</p> <blockquote> <p>An application can call <code>Close</code> more than one time. No exception is generated.</p> <p>If you called <code>Dispose</code> method <code>SqlConnection</code> object state will be reset. If you try to call any method on disposed <code>SqlConnection</code> object, you will receive exception.</p> </blockquote> <p>That said:</p> <ul> <li><strong>If you use connection object one time, use <code>Dispose</code>. A <code>using</code> block will ensure this is called even in the event of an exception.</strong></li> <li><strong>If connection object must be reused, use <code>Close</code> method.</strong></li> </ul>
<p>I just had an issue on net6 app using <code>TransactionScope</code>: I had multiple consequently created, opened and disposed connections, but was catching <code>This platform does not support distributed transactions</code> on completing scope (while clearly there were no distributed transactions).</p> <p>The issue was resolved by adding <code>Close</code> method call. The majority of answers say that <code>Dispose</code> and <code>Close</code> are identical, but it seems they aren't: from what I gleaned from source code, <code>Close</code> method explicitly returns connection to pool, while I could not find identical code for <code>Dispose</code>.</p>
8,622
<p>I'm interested in finding good icons/images that can be used in both 'free' and proprietary programs. </p> <p>Please include a description of any license restrictions associated with the source of the icons you suggest.</p>
<p>I use two search engines:</p> <p><a href="http://www.iconfinder.net/index.php?q=file" rel="noreferrer">IconFinder</a> and <a href="http://www.iconlook.com/search.icon?q=file&amp;s12=on&amp;s16=on&amp;s22=on&amp;s32=on&amp;s48=on&amp;s64=on&amp;s128=on" rel="noreferrer">IconLook</a>.</p> <p>If you can't find what you want, this <a href="http://speckyboy.com/2008/03/04/top-40-free-icon-resources-for-web-designers-updated-speckyboy/" rel="noreferrer">blog post</a> has a list of great resources.</p>
<p>I've had the best luck with <a href="http://www.iconbuffet.com" rel="nofollow noreferrer">Icon Buffet</a> and <a href="http://stockicons.com" rel="nofollow noreferrer">StockIcons</a></p>
7,025
<p>Does SQL Server 2008 ship with the .NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features?</p>
<p>Actually it ships with .NET 3.5 SP1. So yes, the stored procs can use 3.5 features and libraries.</p>
<p>I swear this isn't being pedantic, but is an important distinction -- I don't know what specifically you need when you say ".NET 3.5 CLR" -- probably the .NET 3.5 Framework? Possibly C# 3.0 language features? But the CLR that .NET 3.5 runs on <a href="http://msdn.microsoft.com/en-us/netframework/aa663314.aspx" rel="nofollow noreferrer">is still CLR 2.0.</a> (the link is to the same explanation re: .NET 3.0; I couldn't immediately find this info on 3.5. Actually, the best explanation of CLR vs. Framework vs. language version numbers I've yet found is on page 12 of <a href="https://rads.stackoverflow.com/amzn/click/com/0672329859" rel="nofollow noreferrer" rel="nofollow noreferrer"><em>Teach Yourself WPF in 24 Hours</em></a>*)</p> <p>So, my point is that you can even use the features of .NET 3.5 and C# 3.0 on SQL 2005 CLR stored procedures -- we do, at my company -- and there's not even really any trickery to it. All you have to do is have the free 3.5 framework on your server. Obviously the SQL 2005 answer isn't that relevant for your specific question, but hopefully this will be helpful to the person who eventually comes across this page via Google.</p> <p>*disclosure: I'm friends with the authors</p>
3,255
<p>I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.</p> <p>I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument</p> <p>I have 2 questions, the second regarding a workaround due to my inability to figure out the first.</p> <p>1: Ideal solution</p> <p>I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death</p> <pre><code>Dim xConnections As XElement For Each connection As Connection In connections.AsList For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements xConnections = &lt;Connections&gt; &lt;&lt;%= kvp.Key %&gt;&gt;&lt;%= kvp.Value %&gt;&lt;\&lt;%=kvp.Key %&gt;&gt; &lt;/Connections&gt; Next Next </code></pre> <p>I have vague memories of the T4 syntax (the &lt;%=%> syntax) being able to handle more complex operations (rather than direct assignment to the &lt;%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.</p> <p>2: Cludgy workaround</p> <p>Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.</p> <p>I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.</p> <p>Any thoughts or assistance greatly appreciated</p>
<p>VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.</p> <pre><code>Dim Elements = New Dictionary(Of String, String) Elements.Add("Key1", "Value1") Elements.Add("Key2", "Value2") Elements.Add("Key3", "Value3") Dim xConnections = &lt;Connections&gt; &lt;%= From elem In Elements _ Select &lt;&lt;%= elem.Key %&gt;&gt;&lt;%= elem.Value %&gt;&lt;/&gt; %&gt; &lt;/Connections&gt; </code></pre> <p>The empty closing tag <code>&lt;/&gt;</code> is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a <code>&lt;%= %&gt;</code> block.</p> <p>Calling xConnections.ToString renders the following:</p> <pre><code>&lt;Connections&gt; &lt;Key1&gt;Value1&lt;/Key1&gt; &lt;Key2&gt;Value2&lt;/Key2&gt; &lt;Key3&gt;Value3&lt;/Key3&gt; &lt;/Connections&gt; </code></pre>
<p>We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:</p> <ol> <li>Verifiable</li> <li>Extendable</li> </ol> <p>Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/XMLPListsConcept.html" rel="nofollow noreferrer">plists</a>?</p> <pre><code>&lt;dict&gt; &lt;key&gt;Author&lt;/key&gt; &lt;string&gt;William Shakespeare&lt;/string&gt; &lt;key&gt;Title&lt;/key&gt; &lt;string&gt;Romeo et&lt;/string&gt; &lt;key&gt;ISBN&lt;/key&gt; &lt;string&gt;?????&lt;/string&gt; &lt;/dict&gt; </code></pre>
7,379
<p>I've got a situation where I have a main form that pops up an advanced configuration form that just has half a dozen matched check boxes and combo boxes to select some advanced options (the check boxes to enable/disable, the combo to select a media if enabled).</p> <p>If I just pass the individual settings for the check and combo boxes in to the constructor for the dialog that's obviously a dozen arguments, which seems a bit excessive.</p> <p>My other obvious option would be since in the main form these settings are stored in a large IDictionary with all the other main form settings I could just pass this dictionary in and fetch it back afterward with the updated values, but my understanding is that this wouldn't really be very good coding practice.</p> <p>Am I missing a good way to do this that is both efficient and good coding practice?</p> <p>(this particular code is in C#, although I have a feeling a general solution would apply to other languages as well)</p>
<p>I personally would create a carrier object to store the values. You then get the nice intellisense for it, and changes to it would be quite straightforward. It would also be faster than dictionary lookups for parameter values. And of course, you get type safety. :)</p>
<p>Something like this should be good:</p> <pre><code>MyConfigurationDialog dialog = new MyConfigurationDialog(); //Copy the dictionary so that the dialog can't mess with our settings dialog.Settings = new Dictionary(existingSettings); if(DialogResult.OK == dialog.Show()) { //grab the settings that the dialog may have changed existingSettings["setting1"] = dialog.Settings["setting1"]; existingSettings["setting2"] = dialog.Settings["setting2"]; } </code></pre>
6,135
<p>Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?</p>
<p>I'm currently using this:</p> <pre><code>String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception ex ) { ex.printStackTrace(); } System.out.println(content); </code></pre> <p>But not sure if there's a better way.</p>
<p>Its not library but a tool named curl generally installed in most of the servers or you can easily install in ubuntu by </p> <pre><code>sudo apt install curl </code></pre> <p>Then fetch any html page and store it to your local file like an example </p> <pre><code>curl https://www.facebook.com/ &gt; fb.html </code></pre> <p>You will get the home page html.You can run it in your browser as well.</p>
5,139
<p>I have just bought my own 3D printer. However, I am now reading that there may be some safety risks to 3D printing. I will be taking some precautions, such as buying an enclosed 3D printer (the FlashForge Adventurer 3), using PLA instead of ABS, and putting my 3D printer in my garage. However, I am still concerned about the possible risks. What are some other good safety tips and best practices when 3D printing? Am I doing enough, or should I do more? What have other users of 3D printers done to mitigate potential safety issues? Please let me know.</p>
<p>Technically, you should never leave your printer running unattended. Printer fires are rare, but it can happen, especially with cheap printers with poor quality control. Personally, I would just make sure that there is a fire alarm near by, so you'd be alerted if there was a fire.</p> <p>Also, the fumes concern is valid in the sense that you don't want to sleep in the same room as your 3D printer. The following article points out that if you are spending time in the same room without proper ventilation you'd benefit from potentially using an enclosure with a HEPA filter. Also, the article points out that using PLA may be a safer choice than other materials such as ABS or Polycarbonate when it comes to harmful particles: <a href="https://3dinsider.com/3d-printer-fumes/" rel="nofollow noreferrer">https://3dinsider.com/3d-printer-fumes/</a></p>
<p>Install an overhead vent, like those you would have above your stove, to direct fumes and micro-filaments away from the area. You could alternatively use a box fan with a thin air filter attached to it, but the idea is to draw those fumes away from the room.</p>
1,893
<p>I am currently aware that ASP.NET 2.0 is out and about and that there are 3.x versions of the .Net Framework.</p> <p>Is it possible to upgrade my ASP.NET web server to version 3.x of the .Net Framework?</p> <hr> <p>I have tried this, however, when selecting which version of the .Net framwork to use in IIS (the ASP.NET Tab), only version 1.1 and 2.0 show.</p> <p>Is there a work around?</p>
<blockquote> <p>if I install 3.5 and have IIS setup to use 2.0. I will be able to use 3.5 features?</p> </blockquote> <p>Yes, that is correct. You have IIS set to 2.0 for both 2.0 and 3.5 sites, as they both run on the same CLR. 3.5 uses a different compile method than 2.0. This is declared in the web.config for the site. See <a href="http://blogs.msdn.com/vijaysk/archive/2008/03/20/running-asp-net-3-5-on-iis.aspx" rel="noreferrer">this post</a> for more details on this. But the setup in IIS for both 3.5 and 2.0 ASP.net sites is identical.</p>
<p>The version you are selecting in IIS is the version of the CLR to use. There are only two versions of the CLR. The .NET Framework 3.5 runs on CLR 2.0</p>
2,662
<p>What are the alternative's to using the <a href="http://www.ithenticate.com" rel="nofollow noreferrer">iThenticate</a> service for content comparison?</p>
<p>Wikipedia page on <a href="http://en.wikipedia.org/wiki/Plagiarism_detection" rel="nofollow noreferrer">plagiarism detection</a> has a list of commercial and free services.</p>
<p>I generally recommend <a href="http://www.copyscape.com" rel="nofollow">Copyscape</a> and/or <a href="http://etest.vbi.vt.edu/etblast3/" rel="nofollow">eTBlast</a> if you choose not to use iThenticate. </p>
7,414
<p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p> <pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate '' 10 words args.IsValid = args.Value.Split(" ").Length &lt;= 10 End Sub </code></pre> <p>Does anyone have a more thorough/accurate method of getting a word count?</p>
<p>You can use one of the builtin validators with a regex that counts the words.</p> <p>I'm a little rusty with regex so go easy on me:</p> <pre><code>(\b.*\b){0,10} </code></pre>
<p>I voted for mharen's answer, and commented on it as well, but since the comments are hidden by default let me explain it again:</p> <p>The reason you would want to use the regex validator rather than the custom validator is that the regex validator will also automatically validate the regex client-side using javascript, if it's available. If they pass validation it's no big deal, but every time someone fails the client-side validation you save your server from doing a postback.</p>
7,583
<p>I have an ender 5, and I'm not certain that the bed is getting up to temperature. Or maybe I'm not understanding what it should be like when it gets up to temperature.</p> <p>If I use an infrared thermometer, where should I aim it, and what should it be saying in comparison to what the screen on the printer says?</p> <p>For example, if the screen says 50 degrees should the thermometer read 50 degrees, or should it read something different because that's an internal temperature or something not a surface temperature?</p> <p>At the moment the bed seems &quot;nicely warm&quot; when the temperature on the display says that I should burn my hand if I touch it.</p>
<h2>Sensor mounting</h2> <p>An Infrared Thermometer prefers a non-reflective surface to accurately read the temperature reliably - glass is reflective for Infrared light under many angles and can in the worst case result in measuring anything <em>but</em> what you want to measure. To that degree, a piece of paper tape (Painter's tape or Washi-tape works fine) can act as a mounted measuring point.</p> <p>A contact temperature sensor can be mounted touching the plate in a location easily by putting it in contact using some tape.</p> <h2>Sensor positioning</h2> <p>However, do note that the temperature sensor of the printer is not mounted on the top of the build platform but at the heater element under it. This means two things:</p> <p>There is a temperature differential between the heater (which would be quite hot but not scorching in an instant of touching it) under the aluminium bed, the top of the aluminium bed, and even more if correlated against the surface of your build platform.</p> <p>On the other hand, to verify your sensor setting, you need to measure under the bed at the heating element or at the interface between the heater and the aluminium bed. For example, you could use a spot right next to the heater as your probing point. This is incidentally quite close to where the temperature sensor should be mounted anyway.</p> <h2>Bed temperature control</h2> <p>Depending on your setup, the temperature difference between heater and the build surface could be up to about 15 °C and I would deem that an acceptable number. In accounting for the wanted build surface temperature, one can adjust the set heater temperature accordingly, as shown in this experience I had:</p> <p>On particularly a cold day in late 2021 the heating in the room was not gaining enough heating water from the central unit set to a lower setting than it ought to. As a result, the room was down from the usual temperature to a rather cold ca. 12 °C. On that day I had to increase the bed temperature by a couple of degrees to gain proper bed adhesion, but it fixed itself once I figured out to fix the setting on the central unit.</p>
<p>The actual numerical reading doesn't really matter - as long as the first layer goes down, and stays down through the entire print.</p> <p>I've noticed that the center of the bed is ~2 degrees C under the set temp, and the edges could be 15 degrees low.</p> <p>So &quot;verify by effect&quot; - if the bed seems too cold and you're getting lifting, then raise the temp and use that new value. Write it on the side of the filament spool too.</p> <hr /> <p>If you're looking for a hardware solution, some of the IR cameras or camera add-ons for cellphones may be suitable.</p> <p>FLIR is one such device - be aware they're not cheap! Some photos at <a href="https://toms3d.org/2019/05/02/testing-5-different-heated-beds/" rel="nofollow noreferrer">https://toms3d.org/2019/05/02/testing-5-different-heated-beds/</a></p> <p><a href="https://i.stack.imgur.com/RqfkL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RqfkL.jpg" alt="enter image description here" /></a></p>
2,092
<p>What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. </p>
<p>There are two ways I usually do this, both use ssh:</p> <pre><code>scp -r sourcedir/ user@dest.com:/dest/dir/ </code></pre> <p>or, the more robust and faster (in terms of transfer speed) method:</p> <pre><code>rsync -auv -e ssh --progress sourcedir/ user@dest.com:/dest/dir/ </code></pre> <p>Read the man pages for each command if you want more details about how they work.</p>
<p>As non-root user ideally:</p> <p>scp -r src $host:$path</p> <p>If you already some of the content on $host consider using rsync with ssh as a tunnel.</p> <p>/Allan</p>
9,479
<p>User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons?</p>
<p>Unfortunately, almost no one of the participants ever clearly understands what are they talking about. Literally. Only <a href="https://stackoverflow.com/a/36088/285587">Kibbee</a> managed to make it straight.</p> <p>This topic is all about sanitization. But the truth is, such a thing like wide-termed &quot;general purpose sanitization&quot; everyone is so eager to talk about is <strong>just doesn't exist.</strong></p> <p>There are <strong>a zillion different mediums</strong>, each require <strong>it's own, distinct data formatting.</strong> Moreover - even <strong>single certain medium require different formatting for it's parts</strong>. Say, HTML formatting is useless for javascript embedded in HTML page. Or, string formatting is useless for the numbers in SQL query.</p> <p>As a matter of fact, such a &quot;sanitization as early as possible&quot;, as suggested in most upvoted answers, is just <strong>impossible</strong>. As one just cannot tell in which certain medium or medium part the data will be used. Say, we are preparing to defend from &quot;sql-injection&quot;, escaping everything that moves. But whoops! - some required fields weren't filled and we have to fill out data back into form instead of database... with all the slashes added.</p> <p>On the other hand, we diligently escaped all the &quot;user input&quot;... but in the sql query we have no quotes around it, as it is a number or identifier. And no &quot;sanitization&quot; ever helped us.</p> <p>On the third hand - okay, we did our best in sanitizing the terrible, untrustworthy and disdained &quot;user input&quot;... but in some inner process we used this very data without any formatting (as we did our best already!) - and whoops! have got second order injection in all its glory.</p> <p>So, from the real life usage point of view, the only proper way would be</p> <ul> <li>formatting, not whatever &quot;sanitization&quot;</li> <li>right before use</li> <li>according to the certain medium rules</li> <li>and even following sub-rules required for this medium's different parts.</li> </ul>
<p>I find that cleaning it immediately has two advantages. One, you can validate against it and provide feedback to the user. Two, you do not have to worry about consuming the data in other places.</p>
5,526
<p>I am starting to work on a hobby project with a <strong>Python</strong> codebase and I would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to <strong>CruiseControl</strong> or <strong>TeamCity</strong>.</p> <p>I realize I could do this with hooks in most <strong>VCSes</strong>, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a <strong>Python</strong> codebase?</p>
<p>We run <a href="http://buildbot.net/trac" rel="noreferrer">Buildbot - Trac</a> at work. I haven't used it too much since my codebase isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails — and it's written in Python.</p>
<p>We are using <a href="http://bitten.edgewall.org/" rel="noreferrer">Bitten</a> wich is integrated with trac. And it's python based.</p>
2,295
<p>Say we have the following method:</p> <pre><code>private MyObject foo = new MyObject(); // and later in the class public void PotentialMemoryLeaker(){ int firedCount = 0; foo.AnEvent += (o,e) =&gt; { firedCount++;Console.Write(firedCount);}; foo.MethodThatFiresAnEvent(); } </code></pre> <p>If the class with this method is instantiated and the <code>PotentialMemoryLeaker</code> method is called multiple times, do we leak memory?</p> <p>Is there any way to unhook that lambda event handler after we're done calling <code>MethodThatFiresAnEvent</code>? </p>
<p>Yes, save it to a variable and unhook it.</p> <pre><code>DelegateType evt = (o, e) =&gt; { firedCount++; Console.Write(firedCount); }; foo.AnEvent += evt; foo.MethodThatFiresAnEvent(); foo.AnEvent -= evt; </code></pre> <p>And yes, if you don't, you'll <em>leak</em> memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).</p>
<p>Yes in the same way that normal event handlers can cause leaks. Because the lambda is actually changed to:</p> <pre><code>someobject.SomeEvent += () =&gt; ...; someobject.SomeEvent += delegate () { ... }; // unhook Action del = () =&gt; ...; someobject.SomeEvent += del; someobject.SomeEvent -= del; </code></pre> <p>So basically it is just short hand for what we have been using in 2.0 all these years.</p>
3,720
<p>I'm setting up my first 3D Printer, a Prusa i3 MK2 clone. When I try to heat the bed, nothing happens. Then Marlin throws this error after a while: </p> <pre><code>Bed Heating Failed PRINTER HALTED Please reset </code></pre> <p>In Pronterface I see this in the console:</p> <pre><code>Error:Heating failed, system stopped! Heater_ID: bed [ERROR] Error:Heating failed, system stopped! Heater_ID: bed Error:Printer halted. kill() called! [ERROR] Error:Printer halted. kill() called! </code></pre> <p>There is 0 voltage across D8 on the Ramps board, where it is connected. When I heat up the hotend, on the other hand, which is connected to D10, I see 12V across the board's D10 terminals.</p> <p>The bed is MK42 type.</p> <p>My axes, extruder hotend and fans are working OK. </p> <p>I previously burned out the 5&nbsp;V regulator on my Arduino Mega by misconnecting one of the end stops. I replaced the regulator on the board and the 5&nbsp;V supply seems to be working OK again. However I wondered if I might have damaged the board in some other respect? Or is there a config setting in Marlin I should change?</p>
<p>If you are sure that PID is enabled (and not using bang-bang heating, as this gives a very similar heating profile) and did not fix the fluctuations, the best guess for this phenomenon is that the printer board has incorrect capacitors installed on the printer board. This is not very uncommon and can be found on the internet. You should at least show the graph to the vendor and ask for support.</p> <p>If incorrect or faulty capacitors are the cause it requires desoldering, and resoldering new ones. If this is out of your comfort zone, it is better to steer your communication with the vendor to replacing the board.</p>
<h1>Software</h1> <p>You might want to look at your firmware. When running a PID tune, the firmware decides on a smoothing.</p> <p>in Marlin, <code>configuration.h</code> contains a line that determines how much the machine shall try to work out the curves. For my ender 3 it reads:</p> <pre><code>#define PID_K1 0.95 // Smoothing factor within the PID </code></pre> <p>Playing with the value carefully might result in better calibration.</p> <h1>Hardware</h1> <p>A different trick to <em>widen</em> the waves might come from adjusting the physical properties of the printer:</p> <ul> <li>Make sure that no draft from the cool end fans runs over the heater block. If it does, a shroud or a little tinfoil can help to dampen the changes.</li> <li>e3D uses a silicon sock to isolate their heater blocks and prevent air drafting over them.</li> </ul>
1,131
<p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p> <p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p> <p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p> <p>Help, please.</p>
<p>With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.</p> <p>The code is placed in the main form. The copyToolStripMenuItem_Click method handles the Click event on the Copy menu item in the Edit menu.</p> <pre><code> /// &lt;summary&gt; /// Recursively traverse a tree of controls to find the control that has focus, if any /// &lt;/summary&gt; /// &lt;param name="c"&gt;The control to search, might be a control container&lt;/param&gt; /// &lt;returns&gt;The control that either has focus or contains the control that has focus&lt;/returns&gt; private Control FindFocus(Control c) { foreach (Control k in c.Controls) { if (k.Focused) { return k; } else if (k.ContainsFocus) { return FindFocus(k); } } return null; } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Form f = this.ActiveMdiChild; // Find the control that has focus Control focusedControl = FindFocus(f.ActiveControl); // See if focusedControl is of a type that can select text/data if (focusedControl is TextBox) { TextBox tb = focusedControl as TextBox; Clipboard.SetDataObject(tb.SelectedText); } else if (focusedControl is DataGridView) { DataGridView dgv = focusedControl as DataGridView; Clipboard.SetDataObject(dgv.GetClipboardContent()); } else if (...more?...) { } } </code></pre>
<p>It seems to me that you might be better off breaking this into smaller tasks/questions. You have a few issues you are stuck on from the way it sounds.</p> <p>You have multiple 'child' windows open. Is this an MDI application? When an action is performed on one of those child windows, it should fire an event in that window's event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionchanged.aspx" rel="nofollow noreferrer">DataGridView.SelectionChanged</a> event. Just throw in something like <code>MessageBox.Show("I copied your datas!");</code> for now.</p> <p>This should get you started where you will at least understand how this event will be raised to you.</p> <p>From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.</p>
8,826
<p>In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command <code>ALTER DATABASE &lt;database&gt; SET READ_COMMITTED_SNAPSHOT ON;</code>?</p> <p>I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.</p>
<pre><code>SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name= 'YourDatabase' </code></pre> <p>Return value:</p> <ul> <li><strong>1</strong>: <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>ON</strong>. Read operations under the <code>READ COMMITTED</code> isolation level are based on snapshot scans and do not acquire locks.</li> <li><strong>0</strong> (default): <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>OFF</strong>. Read operations under the <code>READ COMMITTED</code> isolation level use <a href="https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)" rel="noreferrer">Shared (S) locks</a>.</li> </ul>
<p>Neither on SQL2005 nor 2012 does <code>DBCC USEROPTIONS</code> show <code>is_read_committed_snapshot_on</code>:</p> <pre><code>Set Option Value textsize 2147483647 language us_english dateformat mdy datefirst 7 lock_timeout -1 quoted_identifier SET arithabort SET ansi_null_dflt_on SET ansi_warnings SET ansi_padding SET ansi_nulls SET concat_null_yields_null SET isolation level read committed </code></pre>
7,521
<p>What is the best way to include an html entity in XSLT?</p> <pre><code>&lt;xsl:template match="/a/node"&gt; &lt;xsl:value-of select="."/&gt; &lt;xsl:text&gt;&amp;nbsp;&lt;/xsl:text&gt; &lt;/xsl:template&gt; </code></pre> <p>this one returns a <strong>XsltParseError</strong></p>
<p>You can use CDATA section</p> <pre><code>&lt;xsl:text disable-output-escaping="yes"&gt;&lt;![CDATA[&amp;nbsp;]]&gt;&lt;/xsl:text&gt; </code></pre> <p>or you can describe &amp;nbsp in local DTD:</p> <pre><code>&lt;!DOCTYPE xsl:stylesheet [ &lt;!ENTITY nbsp "&amp;#160;"&gt; ]&gt; </code></pre> <p>or just use <code>&amp;#160;</code> instead of <code>&amp;nbsp;</code></p>
<p> </p> <p>One space character between text tags should be enough.</p>
5,180
<p>Using VB.NET, how do I toggle the state of Caps Lock? </p>
<p>From: <a href="http://www.vbforums.com/showthread.php?referrerid=61394&amp;t=537891" rel="noreferrer">http://www.vbforums.com/showthread.php?referrerid=61394&amp;t=537891</a></p> <pre><code>Imports System.Runtime.InteropServices Public Class Form2 Private Declare Sub keybd_event Lib "user32" ( _ ByVal bVk As Byte, _ ByVal bScan As Byte, _ ByVal dwFlags As Integer, _ ByVal dwExtraInfo As Integer _ ) Private Const VK_CAPITAL As Integer = &amp;H14 Private Const KEYEVENTF_EXTENDEDKEY As Integer = &amp;H1 Private Const KEYEVENTF_KEYUP As Integer = &amp;H2 Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs _ ) Handles Button1.Click ' Toggle CapsLock ' Simulate the Key Press keybd_event(VK_CAPITAL, &amp;H45, KEYEVENTF_EXTENDEDKEY Or 0, 0) ' Simulate the Key Release keybd_event(VK_CAPITAL, &amp;H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0) End Sub End Class </code></pre>
<p>I use this</p> <pre><code>Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer) Private Const KEYEVENTF_EXTENDEDKEY As Integer = &amp;H1 Private Const KEYEVENTF_KEYUP As Integer = &amp;H2 'put this where you want to turn caps lock on or off keybd_event(VK_NUMLOCK, &amp;H45, KEYEVENTF_EXTENDEDKEY Or 0, 0) keybd_event(VK_NUMLOCK, &amp;H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0) </code></pre>
8,339
<p>PERL? Perl? perl? What's good style?</p> <p>I know the answer&mdash;I just wanted to make sure the question was out there and questioners were aware that there is a correct form.</p>
<p>The correct casing is "Perl" for the language and "perl" for the executable. Using "PERL" flags you as someone who isn't particularly familiar with the language or community.</p> <p>See also <a href="http://perldoc.perl.org/perlfaq1.html#What%27s-the-difference-between-%22perl%22-and-%22Perl%22?" rel="noreferrer">What's the difference between "perl" and "Perl"?</a> in <a href="http://perldoc.perl.org/perlfaq1.html" rel="noreferrer">perlfaq1</a>.</p>
<p>perl or Perl is fine.</p>
9,796
<p>In <a href="https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/" rel="noreferrer">Kathleen Dollard's 2008 blog post</a>, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.</p>
<p>Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):</p> <pre><code>public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; } } </code></pre> <p>You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.</p> <p>If the TreeNode class was external, you would either have to make all the fields <code>public</code> or make a bunch of <code>get/set</code> methods to use it. The outside world would have another class polluting their intellisense.</p>
<p>As <a href="https://stackoverflow.com/a/16093091/199154">nawfal</a> mentioned implementation of Abstract Factory pattern, that code can be axtended to achieve <a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html" rel="nofollow noreferrer">Class Clusters pattern</a> which is based on Abstract Factory pattern.</p>
7,128
<p>There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&amp;SiteID=1" rel="nofollow noreferrer">detected by checking for keyboard and mouse events</a>. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.</p> <p>As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?</p>
<p>How about the Win32 <a href="http://www.codeproject.com/KB/cs/GetIdleTimeWithCS.aspx" rel="nofollow noreferrer">LASTINPUTINFO</a> function?</p> <pre><code>using System.Runtime.InteropServices; [DllImport("User32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } </code></pre>
<p>Thanks for the responses, I ended up going with the GetLastInputInfo function as it is pretty straight forward to implement in the application I'm working on.</p>
3,966
<p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
<p><a href="https://www.nuget.org/packages/Microsoft.Data.Sqlite" rel="nofollow noreferrer">Microsoft.Data.Sqlite</a> by Microsoft has over 9000 downloads every day, so I think you are safe using that one.</p> <p>Example usage from <a href="https://learn.microsoft.com/dotnet/standard/data/sqlite/" rel="nofollow noreferrer">the documentation</a>:</p> <pre><code>using (var connection = new SqliteConnection(&quot;Data Source=hello.db&quot;)) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = @&quot; SELECT name FROM user WHERE id = $id &quot;; command.Parameters.AddWithValue(&quot;$id&quot;, id); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var name = reader.GetString(0); Console.WriteLine($&quot;Hello, {name}!&quot;); } } } </code></pre>
<p>if you have any problem with the library you can use <code>Microsoft.Data.Sqlite;</code></p> <pre><code> public static DataTable GetData(string connectionString, string query) { DataTable dt = new DataTable(); Microsoft.Data.Sqlite.SqliteConnection connection; Microsoft.Data.Sqlite.SqliteCommand command; connection = new Microsoft.Data.Sqlite.SqliteConnection(&quot;Data Source= YOU_PATH_BD.sqlite&quot;); try { connection.Open(); command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection); dt.Load(command.ExecuteReader()); connection.Close(); } catch { } return dt; } </code></pre> <p>you can add NuGet Package Microsoft.Data.Sqlite</p>
4,560
<p>I need to know how the performance of different XML tools (parsers, validators, XPath expression evaluators, etc) is affected by the size and complexity of the input document. Are there resources out there that document how CPU time and memory usage are affected by... well, what? Document size in bytes? Number of nodes? And is the relationship linear, polynomial, or worse?</p> <p><strong>Update</strong></p> <p>In an article in IEEE Computer Magazine, vol 41 nr 9, sept 2008, the authors survey four popular XML parsing models (DOM, SAX, StAX and VTD). They run some very basic performance tests which show that a DOM-parser will have its throughput halved when the input file's size is increased from 1-15 KB to 1-15 MB, or about 1000x larger. The throughput of the other models is not significantly affected.</p> <p>Unfortunately they did not perform more detailed studies, such as of throughput/memory usage as a function of number of nodes/size.</p> <p>The article is <a href="https://www.computer.org/10.1109/MC.2008.403" rel="nofollow noreferrer">here.</a></p> <p><strong>Update</strong></p> <p>I was unable to find any formal treatment of this problem. For what it's worth, I have done some experiments measuring the number of nodes in an XML document as a function of the document's size in bytes. I'm working on a warehouse management system and the XML documents are typical warehouse documents, e.g. advanced shipping notice etc.</p> <p>The graph below shows the relationship between the size in bytes and the number of nodes (which should be proportional to the document's memory footprint under a DOM model). The different colors correspond to different kinds of documents. The scale is log/log. The black line is the best fit to the blue points. It's interesting to note that for all kinds of documents, the relationship between byte size and node size is linear, but that the coefficient of proportionality can be very different.</p> <p> <a href="http://www.flickr.com/photos/13583850@N00/3190749168/" rel="nofollow noreferrer" title="benchmarks-bytes_vs_nodes by david.lindelof, on Flickr"><img src="https://i.stack.imgur.com/D3yVS.jpg" width="500" height="351" alt="benchmarks-bytes_vs_nodes" /></a><br> <sub>(source: <a href="https://farm4.static.flickr.com/3470/3190749168_c999712308.jpg" rel="nofollow noreferrer">flickr.com</a>)</sub> </p> <p></p>
<p>If I was faced with that problem and couldn't find anything on google I would probably try to do it my self.</p> <p>Some "back-of-an-evelope" stuff to get a feel for where it is going. But it would kinda need me to have an idea of how to do a xml parser. For non algorithmical benchmarks take a look here:</p> <ul> <li><a href="http://www.xml.com/pub/a/Benchmark/exec.html" rel="nofollow noreferrer">http://www.xml.com/pub/a/Benchmark/exec.html</a></li> <li><a href="http://www.devx.com/xml/Article/16922" rel="nofollow noreferrer">http://www.devx.com/xml/Article/16922</a></li> <li><a href="http://xerces.apache.org/xerces2-j/faq-performance.html" rel="nofollow noreferrer">http://xerces.apache.org/xerces2-j/faq-performance.html</a></li> </ul>
<p>I was planning to load extremely large XML files in my application. I asked the question here on Stack Overflow: <a href="https://stackoverflow.com/questions/264020/fastest-possible-xml-handling-in-delphi-for-very-large-documents">Fastest Possible XML handling for very large documents</a>.</p> <p>And yes, it was the parsing part, that was the bottleneck. </p> <p>I ended up not using XML parsers at all. Instead, I parsed characters one by one as efficiently as possible optimizing for speed. This resulted in speeds of 40 MB per second on a 3 GHz Windows PC for the reading, parsing and loading of the internal data structure.</p> <p>I would be very interested in hearing how the various XML parsing modes compare to this.</p>
5,172
<p>Are there any extruders and printers that do a good job with ceramic clay?</p> <p>I assume the clay has to be fine grained and with enough water added to be able to be pushed out through the extruder's nozzle. I also assume the print speed would have to be arther low for the already printed layers to gain stability before printing the next layer. Perhaps some extra equipment on the printer to spped up this drying process?</p> <p>At the same time, the print speed can't be too low: if the bottom starts to dry enough to start shrinking, the object will crack.</p> <p>Also, some solutions I've seen tend to result in rather low resolution/thick layers, which is negative.</p> <p>So, what equipment is "out there"?</p>
<p>What you are looking for is the Frostruder style extruders.</p> <p>Here is a link to a <a href="http://www.thingiverse.com/thing:1143" rel="nofollow noreferrer">thingiverse file for it</a>.</p> <p>You honestly cannot expect fantastic results but it will get the job done! There are many other types. Quality will depend on the size of the point. However with something as high viscosity as clay I would not expect you to be able to push the quality very high.</p>
<p>I cant speak for the quality or type of clay, but there are several designs out there that print in clay. Here is the first one that popped up on my google search.</p> <p><a href="http://www.wasproject.it/w/en/wasp-launches-the-new-professional-clay-extruder/" rel="nofollow noreferrer">http://www.wasproject.it/w/en/wasp-launches-the-new-professional-clay-extruder/</a></p>
451
<p>Is it possible to use <a href="http://subversion.apache.org/" rel="noreferrer">Apache Subversion</a> (SVN) as general purpose backup tool? (As a kind of <a href="http://en.wikipedia.org/wiki/Rsync" rel="noreferrer">rsync</a> alternative.)</p>
<p>I found this article to be a pretty cool description of using svn to backup your home directory, and more:</p> <blockquote> <p>I use Subversion to backup my Linux boxes. With some minor creativity, it easily covers:</p> <ul> <li>Daily snapshots and offsite backup.</li> <li>Easy addition and removal of files and folders.</li> <li>Detailed tracking of file versions.</li> </ul> <p>It also allows for a few bonus features:</p> <ul> <li>Regular log emails to keep track of filesystem activity via Subversion's event hooks.</li> <li>Users may request a checkout of their home folders from any respository revision.</li> <li>New or replacement servers can be setup with a few svn checkout commands.</li> </ul> </blockquote> <p>Source: <a href="http://web.archive.org/web/20080824094836/http://www.mythago.net/svn_for_backup.html" rel="nofollow noreferrer">http://www.mythago.net/svn_for_backup.html</a></p> <p>Also found <a href="http://www.onlamp.com/pub/a/onlamp/2005/01/06/svn_homedir.html" rel="nofollow noreferrer">this article</a> which shows an example of versioning your home directory. This allows you to bring your environment with you by checking out your home directory into a new machine. I used to do something similar and found it very useful.</p>
<p>I've used CVS as a substitute for ghost so I don't see why not.</p> <p>I'ts nice as you can tag a baseline: you can change manage machines.</p> <p>This works better on unixes than windows, obviously.</p>
8,720
<p>How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic &amp; Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.</p> <p>How would you probe the file to determine its actual type (not merely based on the extension)?</p>
<p>In Java 7 you can now just use <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29" rel="noreferrer"><code>Files.probeContentType(path)</code></a>.</p>
<p>I did it with following code. </p> <pre><code>import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MimeFileType { public static void main(String args[]){ try{ URL url = new URL ("https://www.url.com.pdf"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); InputStream content = (InputStream)connection.getInputStream(); connection.getHeaderField("Content-Type"); System.out.println("Content-Type "+ connection.getHeaderField("Content-Type")); BufferedReader in = new BufferedReader (new InputStreamReader(content)); }catch (Exception e){ } } } </code></pre>
7,449
<p>I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a <code>List&lt;string&gt;</code>.</p>
<p>Iterate through and for each element make the probability of selection = (number needed)/(number left)</p> <p>So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that.</p> <p>This technique is called <a href="https://stackoverflow.com/questions/35065764/select-n-records-at-random-from-a-set-of-n">selection sampling</a>, a special case of <a href="https://en.wikipedia.org/wiki/Reservoir_sampling" rel="noreferrer">Reservoir Sampling</a>. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.</p>
<p>When N is very large, the normal method that randomly shuffles the N numbers and selects, say, first k numbers, can be prohibitive because of space complexity. The following algorithm requires only O(k) for both time and space complexities.</p> <p><a href="http://arxiv.org/abs/1512.00501" rel="nofollow">http://arxiv.org/abs/1512.00501</a></p> <pre><code>def random_selection_indices(num_samples, N): modified_entries = {} seq = [] for n in xrange(num_samples): i = N - n - 1 j = random.randrange(i) # swap a[j] and a[i] a_j = modified_entries[j] if j in modified_entries else j a_i = modified_entries[i] if i in modified_entries else i if a_i != j: modified_entries[j] = a_i elif j in modified_entries: # no need to store the modified value if it is the same as index modified_entries.pop(j) if a_j != i: modified_entries[i] = a_j elif i in modified_entries: # no need to store the modified value if it is the same as index modified_entries.pop(i) seq.append(a_j) return seq </code></pre>
7,044
<p>I’ve just brought my printer back out after a month and it’s first print created a solid block of resin about 1.5&nbsp;cm deep and the full width and length of the print bed. What could cause this?</p> <p>My only thought so far is that the FEP film / vat bed is looking a little cloudy even after cleaning. I wondered if this could have caused the light to diffuse across the whole bed?</p> <p><a href="https://i.stack.imgur.com/gucsU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gucsU.jpg" alt="enter image description here"></a></p>
<p>Is the laser (or whatever light source it uses) visible? The cloudy film sounds like a good candidate for light diffusion and thus solidifying the entire resin, but if there are visible components to the light source it may help narrow it down.</p> <p>If it uses a projector ("LCD") solutions, it may also be that the display that filters the light to certain regions of the resin to selectively solidify the print may be at fault, but that's rather unlikely.</p> <p>The first thing that, in my <em>opinion</em>, you should do is to check that the object you are printing does not have a corrupt model file. Assuming that you have spare, fresh resin (if your resin is old, that's actually the most likely issue...) and it wasn't too hard to pry out that block, you could try printing something else that worked in the past.</p> <p>While it's doing that, you may be able to see where/how it is printing. If the beam diffuses or lights up the whole area, you can tell if it's a printer issue (the film sounds like a good first thing to try replacing in that case). On the other hand, if the resin is old, it's probably just getting oversensitive and your printer is fine.</p> <p>The resin is very touchy with these things, and has a shelf life of a few weeks to a few months, and less if it's ever opened.</p>
<p>I had an issue with mine. I had a tiny hole that dripped some resin on the LCD screen. I scrapped it off as best I could but there were some serious printing problems on that side. I got a new LCD screen and replaced that and now print jobs that use to work are not printing solid blocks. I have no luck trying to repair it, so I sent support a question on how to fix it and what is causing it. I will update when I know more</p> <p>Update: LCD screen was replaced upside down making the ribbon cable go in backwards. I swapped/flipped it over and it works fine now. So if you are having a solid block issue. Replace the lcd but also be cautious of what side goes up. They don’t show you in the videos. </p>
1,535
<p>Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful.</p>
<p>Ok, Pablo has sparked my interest in saying that the scheduler is accessible via COM.</p> <p>In PowerShell you can do this:</p> <pre><code>$svc = new-object -com Schedule.Service </code></pre> <p>... and that gives you a handle to the task scheduler. You can see what members it has using:</p> <pre><code>$svc | get-member </code></pre> <p>One of its methods is NewTask, so I'd start there.</p> <p>Edit: Some more info <a href="http://msdn.microsoft.com/en-us/library/aa446862.aspx" rel="nofollow noreferrer">here</a>. It's a VBScript example but it'll give you the gist.</p>
<p>@slipsec: I don't have access to a 2003 server to try, but googling "2003 server" SCHTASKS there are links related to questions about it. Perhaps you misspell the command? Like Matt says, you also can use AT, but in this case you don't have access to the scheduled tasks via the Control Panel, only via the AT command.</p>
5,388
<p>How do I get it to work with my project?</p> <p><a href="http://ajax.asp.net/" rel="noreferrer">http://ajax.asp.net/</a></p> <p><a href="http://www.codeplex.com/AjaxControlToolkit/" rel="noreferrer">http://www.codeplex.com/AjaxControlToolkit/</a></p>
<p><strong>Install the ASP.NET AJAX Control Toolkit</strong></p> <ol> <li><p>Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the <a href="http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488" rel="noreferrer">ASP.NET AJAX Control Toolkit Releases</a> page of the CodePlex web site.</p></li> <li><p>Copy the contents of this zip file directly into the bin directory of your web site.</p></li> </ol> <p><strong>Update web.config</strong></p> <ol start="3"> <li><p>Put this in your web.config under the &lt;controls&gt; section:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; ... &lt;system.web&gt; ... &lt;pages&gt; ... &lt;controls&gt; ... &lt;add tagPrefix="ajaxtoolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolKit"/&gt; &lt;/controls&gt; &lt;/pages&gt; ... &lt;/system.web&gt; ... &lt;/configuration&gt; </code></pre></li> </ol> <p><strong>Setup Visual Studio</strong></p> <ol start="4"> <li><p>Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"</p></li> <li><p>Inside that tab, right-click on the Toolbox and select "Choose Items..."</p></li> <li><p>When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.</p></li> </ol> <p>You can now use the controls in your web sites!</p>
<p>you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.</p>
6,131
<p>How does one automatically find categories for text based on content?</p>
<ol> <li>Read <strong><a href="http://www.cs.waikato.ac.nz/~ml/weka/book.html" rel="nofollow noreferrer">Data Mining: Practical Machine Learning Tools and Techniques</a></strong> - Ian H. Witten, Eibe Frank</li> <li>Use <strong><a href="http://www.cs.waikato.ac.nz/~ml/weka/" rel="nofollow noreferrer">Weka</a></strong> or <strong><a href="http://www.ailab.si/orange/" rel="nofollow noreferrer">Orange</a></strong></li> </ol>
<p>There is a good paper written on this: <a href="http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html" rel="nofollow noreferrer">http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html</a></p>
9,122
<p>I need to 3D print several composites. The constituent materials are photopolymer resins. The composites are very similar to a Rubik's cube. Considering it that way, each voxel (every small piece of the Rubik's cube) is either entirely printed by material A or B.</p> <p>I have the binary files ready for the parts. More specifically speaking, I have 3D binary tensors corresponding to each composite topology. In my tensors, each of the elements represents a voxel, and their values (binary) indicate the material that should be assigned to that specific voxel. For instance, a 1 or 0 value located at the I, J, K position of the binary tensor simply means that in that composite, the voxel located at that I, J, K position should be printed with material A or B entirely.</p> <p>I believe for 3D printing these composites, the <a href="https://www.stratasys.com/3d-printers/objet-350-500-connex3" rel="nofollow noreferrer">Stratasys Objet500 Connex3 printer</a> would be a good choice. However, I have no idea how to prepare my files for 3D printing the structures. If it was a CAD file, I could use slicer software, but I do not know how I can print the structures using these binary tensors. I would appreciate any help regarding this matter.</p>
<p>It appears that your question is directed to solving the problem of converting your file of parameters to a 3D printable form. I'm far from an OpenSCAD wizard, but I suspect that your parameters file could be read into a properly coded OpenSCAD document to create the necessary STL to be printed.</p> <p>Your reference of I, J, K is better considered as X, Y, Z and requires an additional value to determine material A, B or nul. If your voxels are uniform size as I expect, the coding is likely not to be particularly complex (for more skilled individuals).</p> <p>pseudocode:</p> <pre><code>read entry translate by x, y, z check for print material a create voxel repeat to EOF export STL </code></pre> <p>repeat for material b</p> <p>It's important to note that a typical STL file requires the object to be a fully manifold creation. If the STL appears, for example, as a QR code, some of the voxels will be floating and may not produce. This is also dependent on the printer selected, as an SLS printer would be able to produce such a design, which would fall apart once removed from the print chamber. These are aspects not covered in the question.</p>
<p>Stratasys industrial machines generally use proprietary software to prepare the print files for printing and don't use common slicers like Ultimaker Cura or Prusa-slicer.</p> <p>The software that is suggested by the manufacturer for both arranging and preparing prints on their machines of the Objet type is <a href="https://grabcad.com/print" rel="nofollow noreferrer">GrabCAD</a>, a free software. The project is owned by Stratasys, so it is pretty much on point to all of Stratasys' machine's capabilities.</p>
2,087
<p>.NET Framework: 2.0 Preferred Language: C#</p> <p>I am new to TDD (Test Driven Development).</p> <p>First of all, is it even possible to unit test Windows Service?</p> <p>Windows service class is derived from ServiceBase, which has overridable methods, </p> <ol> <li>OnStart </li> <li>OnStop</li> </ol> <p>How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?</p> <p>At this point, am I even doing a Unit testing? or an Integration test?</p> <p>I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.</p>
<p>I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service.</p> <p>In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.</p>
<p>Guy's probably the best answer.</p> <p>Anyway, if you really want to, you could just invoke in the unit test these two method as described by <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28v=VS.90%29.aspx" rel="nofollow">MSDN documentation</a> but, since they are protected, you'll need to use Reflection.</p>
6,355
<p>I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a <a href="http://blog.gadodia.net/extension-methods-in-vbnet-and-c/" rel="noreferrer">point</a>).</p> <p>So, what do you think are the best practices for employing Extension Methods?</p> <p>Should development teams create a library of extension methods and deploy them across various projects?</p> <p>Should there be a collection of common extension methods in the form of an open source project?</p> <p><em>Update: have decided to create an organization wide extension methods library</em></p>
<p>The upcoming release of the Framework Design Guidelines, 2nd Edition will have some guidance for implementing extension methods, but in general:</p> <p>You should only define extension methods "where they make semantic sense" and are providing helper functionality relevant to every implementation.</p> <p>You also should avoid extending System.Object as not all .NET languages will be able to call the extension method as an extension. (VB.NET for instance would need to call it as a regular static method on the static extension class.)</p> <p>Don't define an extension method in the same namespace as the extended type unless you're extending an interface.</p> <p>Don't define an extension method with the same signature as a "real" method since it will never be called.</p>
<p>When I first found out about Extensions I really overused and abused them.</p> <p>For the most part I have started to get away from using any Extension Methods for a number of reasons.</p> <p>Some of the reasons I stopped using them are noted in Scott's blog link above, such as "Think twice before extending types you don't own". If you have no control over the source for the types you are extending, you may encounter issues/collisions in the future if the source type has some additions/changes, such as moving your project to a newer .NET version. If the newer .NET version includes a method on the type of the same name as your extension, someone is going to get clobbered.</p> <p>The main reason why I stopped using Extension Methods is that you can't quickly tell from reading the code where the source of the method is and who "owns" it.</p> <p>When just reading through the code you can't tell whether the method is an extension or just a standard NET API method on the type.</p> <p>The intellisense menu can get really messy really fast.</p>
2,531
<p>When the print head changes direction, the printer must accelerate and decelerate the print head. When calibrated correctly, the printer is able to do this quickly and without causing the printer to shake too much, without drastically slowing down the print process.</p> <p>If I set it too high, my printer shakes violently, especially during infill. If I set it too low, print times are doubled or tripled.</p> <p>What process can I follow to determine (or how can I calculate) the fastest acceleration value my printer can use without causing problems in my print?</p> <p>I'd prefer a process I can follow over a formula I can plug values into, especially if the formula includes magic numbers.</p>
<p>As Tom pointed out, binary search is the best way. In case that term isn't familiar to all readers, here's a little more detail:</p> <ol> <li><p>Establish an acceleration value that you're sure is too low (call it <span class="math-container">$L$</span>), and one that you're sure is too high (<span class="math-container">$H$</span>). It sounds like you know such values already from experience.</p></li> <li><p>Figure out the speed in the middle: <span class="math-container">$(L+H)/2$</span>. Call that <span class="math-container">$M$</span>.</p></li> <li><p>Try printing at speed <span class="math-container">$M$</span>. Something like a stepped calibration cube might be a good choice of object (plenty available on Thingiverse).</p></li> <li><p>If <span class="math-container">$M$</span> is still too fast, take <span class="math-container">$M$</span> as your new high-speed limit (that is, reset <span class="math-container">$H$</span> to the value of <span class="math-container">$M$</span>), and repeat from step #2.</p></li> <li><p>If it's slow enough to work, take <span class="math-container">$M$</span> as your new low-speed limit (<span class="math-container">$L$</span>), and repeat from step #2.</p></li> </ol> <p>Each repetition will cut the range in half. Keep repeating until <span class="math-container">$L$</span> and <span class="math-container">$H$</span> get as close as you want; say, within 5&nbsp;% of each other or so.</p> <p>I wouldn't bother trying to get super-close, because the workable value will vary somewhat over time (friction from dust getting on various parts; slight voltage differences; different mass and pulling tension for the filament roll, temperature of motors, complexity of the object you're printing, behavior of the slicing program you use, you name it).</p>
<p>Most printers use between 2000 and 5000 mm/s<sup>2</sup>.... extrusion moves are usually 2000 (on average, between different printers), travel is normally seen at 3000-5000, though for most lower end or duel direct drive extruder (heavy) printers, this value should be lower (some as low as 500-1000, some as high as 2000 for travel). Heavier extruders need lower values, as well a slower jerk values, to avoid the motors skipping. The jerk setting being set lower can actually be beneficial, as this makes for smoother extrusion after a corner or a hole (some people will see ripples near these areas as it accelerates out of the direction change - lower values make these ripples smaller, but slightly increase print time).</p> <p>I've just modified mine with a prototype carriage design that I'm working on. It's added about 100 grams to the stock weight. It was finely tuned before, so this extra weight set it over that pillow of 20-30% in the setting, and makes the X and Y skip as it jerks around the plate; especially in high resolution models, particularly high resolution circles with 200 faces on the vertical axis, because the printer tries to jerk after each node - normally that isn't an issue, but in heavy designs, the jerk setting needs to be lowered. I had my jerk at 20 for XY, and its now at 4, after having tested and failed 8 and 15 values. The acceleration was at 2000 for both extrusion and travel (some firmwares don't allow separate values for travel and extrusion moves, but if yours does, it's best to have travel value about double the print moves - when your travel is twice the speed of extrusion moves - so use that 1-1 formula in relation to speed, scale it for each desired speed set in the slicer). Mine has been tested at 2000, 1500, 1000, and 800, failing all of them, with jerk setting of 5. Now testing 500 for acceleration, and beginning to get a little confused as to why this is happening. </p> <p>Now I'm having second thoughts... After going as low as 800 from 2000, and still getting skipping (seemingly worse) am I getting this backwards here? Do I need a higher value if the motor is skipping on quick moves? My understanding is that lower is better for those problems, but perhaps I've confused myself. </p>
131
<p>I have a print I need to make holes in.<br> I have read some other threads where the answers was in short, "don't, print the holes", and "make sure to make the hole from the top or bottom".<br> The problem is I need the hole in the side of a print with about 1 mm walls. </p> <p>The holes I need is to run a USB cable in and a few to hold 3 mm LEDs.<br> One of the holes needs to be 10 mm. </p> <p>What is my best option?<br> I read that there is a risk it cracks, so I was thinking maybe I can use a soldering iron for the smaller holes?<br> That will melt the plastic and create nice smooth walls, right? Less risk of cracks?<br> The piece will not be loaded in any way, it's just holdin it's own weight. </p> <p>I never anticipated that it would be an issue to drill holes in prints. If I had known it I might have tried more to change the print before ordering it.<br> (I don't have a printer to make a new one with.)</p> <p><strong>Note:</strong> The part has <em>already</em> been printed. This is a question about post-printing processing, <em>not</em> modelling for a new print.</p>
<p>You're going to have to drill those holes. The plastic will melt if you drill too quickly. If at all possible, use a slow speed drill, a hand drill, or wrap a cloth around a drill bit and twist it with your hand. If you go too fast, the part will melt. If you press to hard the part will break.</p> <p>Once the hole has been drilled you will need to reinforce it with a metal/plastic tube of the required diameter. Press the tube into the hole. I don't know what your wall thickness is, but try to ensure the tube is the same length.</p> <p>If at all possible you should get flanged tubes like these from mc master car:</p> <p><a href="https://i.stack.imgur.com/zh0UT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zh0UT.png" alt="Flanged tube insert"></a></p> <p>The parts with the 1/2 inch inner diameter and 5/8 outer diameter should fit your 10 mm requirement. The rest is up to you. Go to mcmaster.com/inserts scroll down to "Other Inserts" then "Tube and tube fittings".</p>
<p>As a follow up on this I wanted to post some pictures of the result with only the soldering iron.<br> I was soldering some cables and when it was still hot I figured I could give it a go. </p> <p>The hole is on the underside and in a closed compartment so it's not visible.</p> <p>Anyways, about 3 mm hole at this point and quite pleased with the result.</p> <p><a href="https://i.stack.imgur.com/QXfa5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QXfa5.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/noyMb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/noyMb.jpg" alt="enter image description here"></a></p>
1,442
<p>You write a function and, looking at the resulting assembly, you see it can be improved.</p> <p>You would like to keep the function you wrote, for readability, but you would like to substitute your own assembly for the compiler's. Is there any way to establish a relationship between your high-livel language function and the new assembly?</p>
<p>If you are looking at the assembly, then its fair to assume that you have a good understanding about how code gets compiled down. If you have this knowledge, then its sometimes possible to 'reverse enginer' the changes back up into the original language but its often better not to bother. </p> <p>The optimisations that you make are likely to be very small in comparison to the time and effort required in first making these changes. I would suggest that you leave this kind of work to the compiler and go have a cup of tea. If the changes are significant, and the performance is critical, (as say in the embedded world) then you might want to mix the normal code with the assemblar in some fashion, however, on most computers and chips the performance is usually sufficient to avoid this headache. </p> <p>If you <em>really</em> need more performance, then optimise the code not the assembly.</p>
<p>It depends on the language you wrote your function in. Some languages like C are very low-level, translating each function call or statement to specific assembly statements. If you did use C, you can replace your function with inline assembly to improve performance.</p> <p>Other high-level languages may convert each statement into macro routines or other more complex calls on the assembly side. Certain optimizations (like tail recursion, loop unrolling, etc) can be implemented easily on the source side, but others (like making more efficient use of the register file) may be impossible (again, depending on the language and the compiler you're using).</p>
8,986
<p>Here's a perfect example of the problem: <a href="http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html" rel="nofollow noreferrer">Classifier gem breaks Rails</a>.</p> <p>** Original question: **</p> <p>One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby:</p> <pre><code>public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz ... end end end </code></pre> <p>It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call <code>freeze</code> on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not <strong>very</strong> careful about load order.</p> <p>Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions?</p> <p>(And no, core classes are not frozen by default in Ruby. See below:)</p> <pre><code>require 'md5' # =&gt; true MD5.frozen? # =&gt; false </code></pre>
<p>I don't think this is a concern.</p> <p>Yes, the mythical "somebody" can replace the implementation of MD5 with something insecure. But in order to do that, the mythical somebody must actually be able to get his code into the Ruby process. And if he can do that, then he presumably could also inject his code into a Java process and e.g. rewrite the bytecode for the MD5 operation. Or just intercept the keypresses and not actually bother with fiddling with the cryptography code at all.</p> <p>One of the typical concerns is: I'm writing this awesome library, which is supposed to be used like so:</p> <pre><code>require 'awesome' # Do something awesome. </code></pre> <p>But what if someone uses it like so:</p> <pre><code>require 'evil_cracker_lib_from_russian_pr0n_site' # Overrides crypto functions and sends all data to mafia require 'awesome' # Now everything is insecure because awesome lib uses # cracker lib instead of builtin </code></pre> <p>And the simple solution is: don't do that! Educate your users that they shouldn't run untrusted code they downloaded from obscure sources in their security critical applications. And if they do, they probably deserve it.</p> <p>To come back to your Java example: it's true that in Java you can make your crypto code <code>private</code> and <code>final</code> and what not. However, someone can <em>still</em> replace your crypto implementation! In fact, someone actually did: many open-source Java implementations use OpenSSL to implement their cryptographic routines. And, as you probably know, Debian shipped with a broken, insecure version of OpenSSL for years. So, all Java programs running on Debian for the past couple of years actually <em>did</em> run with insecure crypto!</p>
<p>If someone monkeypatched an object or a module, then you need to look at 2 cases: He added a new method. If he is the only one adding this meyhod (which is very likely), then no problems arise. If he is not the only one, you need to see if both methods do the same and tell the library developer about this severe problem.</p> <p>If they change a method, you should start to research why the method was changed. Did they change it due to some edge case behaviour or did they actually fix a bug? especially in the latter case, the monkeypatch is a god thing, because it fixes a bug in many places.</p> <p>Besides that, you are using a very dynamic language with the assumption that programmers use this freedom in a sane way. The only way to remove this assumption is not to use a dynamic language. </p>
5,223
<p>To make things easier when switching between machines (my workstation at the office and my personal laptop) I have thought about trying an external hard drive to store my working directory on. Specifically I am looking at Firewire 800 drives (most are 5400 rpm 8mb cache). What I am wondering is if anyone has experience with doing this with Visual Studio projects and what sort of performance hit they see.</p>
<p>It depends on the size of the project. The throughput is low and the latency is high, so you're going to get hit every which way, but due to the latency you'll be hit harder if you have a lot of little files rather than a few large ones.</p> <p>Have you considered simply carrying around a GIT or other distributed repository and updating the machine repositories as you move around? Then you can compile locally and treat the drive and a roving server. Since only changes will be moved across, it should be faster, and your code will be 'backed up' in more places.</p> <p>If you forget the drive, it breaks, or is lost/stolen, then you can still sit down at a PC and program with no code missing if you're at the last PC you used, or very little code missing (which will be updated later with a resync anyway).</p> <p>And it's just a hop skip and a jump away from simply using the network to move the changes between the systems if you don't want to carry the drive around later.</p>
<p>I use vmware and the virtual machines are on an external usb drive. Performance is fine. You might have some issues with the drive name changing - not an issue if you use virtual machines.</p>
8,263
<p>What techniques do you know\use to create user-friendly GUI ? </p> <p>I can name following techniques that I find especially useful: </p> <ul> <li>Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)</li> <li>Absence of "Save" button<br> MS OneNote as an example.<br> IM clients can save conversation history automatically</li> <li>Integrated search<br> Search not only through help files but rather make UI elements searchable.<br> Vista made a good step toward such GUI.<br> <a href="http://www.istartedsomething.com/20070124/scout-office-2007/" rel="nofollow noreferrer">Scout</a> addin Microsoft Office was a really great idea.</li> <li>Context oriented UI (Ribbon bar in MS Office 2007)</li> </ul> <p>Do you implement something like listed techniques in your software?</p> <p><strong>Edit:</strong><br> As <a href="https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843">Ryan P</a> mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.</p>
<p>If you do give the user a question, don't make it a yes/no question. Take the time to make a new form and put the verbs as choices like in mac. </p> <p>For example:</p> <pre><code> Would you like to save? Yes No </code></pre> <p>Should Be:</p> <pre><code> Would you like to save? Save Don't Save </code></pre> <p>There is a more detailed explanation <a href="http://www.usabilitypost.com/post/11-usability-tip-use-verbs-as-labels-on-buttons" rel="noreferrer">here.</a></p>
<p>The best technique I found is to put your self in the users shoes. What would you like to see from the GUI and put that in front. This also gives you the ability to prioritize as those things should be done first then work from there.</p> <p>To do this I try to find "layers of usefulness" and add / subtract from the layers until it seems clean. Basically to find the layers I make a list of all the functions the GUI needs to have, all the functions it should have, and all the functions it would be neat to have. Then I group those so that every thing has logical ordering and the groupings become the "layers". From the layers I then add the most important functionality (or what would be used for Day to Day operation) and that becomes the most prominent part, and I work things into the feature around those items.</p> <p>One of the toughest things is navigation as you have so much to give the use how do you make it helpful and this is where the layers really help. It makes it easy to see how to layout menus, how other pieces interact, what pieces can be hidden, etc. </p> <p>I have found the easiest way to do this is to start by see what and how your users function on a day to day basis this which will make it easier to get in their shoes (even better is to do their job for a few days). Then make some demonstrations and put them in front of users even if they are Paper Prototypes (there is a book on this process called Paper Prototyping by Carolyn Snyder). Then begin building it and put it in front of users as it is built <em>often</em>. </p> <p>I will also recommended the book Designing Interfaces by Jenifer Tidwell published by O'Reilly</p>
6,437
<p>I am trying to install VS2008 sp1 to my work machine - it has a pathetic 10Gb C drive. The SP1 bootstrapper doesn't give the option to install items to D, only C. It needs 3Gb free and the machine only has about 700Mb.</p> <p>VS allowed me to install to D originally why not the SP. The only thing I can think of that it requires system files installed in Windows etc, but I can't believe there are 3Gb worth of system files?</p>
<p>Worth a read:</p> <p><a href="http://blogs.msdn.com/heaths/archive/2008/07/24/why-windows-installer-may-require-so-much-disk-space.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/heaths/archive/2008/07/24/why-windows-installer-may-require-so-much-disk-space.aspx</a></p>
<p>You could also download the full VS2008 SP1 ISO image from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=27673c47-b3b5-4c67-bd99-84e525b5ce61&amp;displaylang=en" rel="nofollow noreferrer">here</a>.</p> <p>Then you can either burn it to DVD or use a tool such as <a href="http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe" rel="nofollow noreferrer">Virtual CD-ROM Control Panel from Microsoft</a> to mount the ISO as another drive.</p> <p>After mounting the ISO as a virtual drive, you can run the SP1 install from there.</p>
3,016