instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I'd like to take an existing application (written in OCaml) and create an Emacs "interface" for it (like, for example, the Emacs GDB mode). I would prefer to do this without writing a ton of Lisp code. In MVC terms, I'd like for the View to be Emacs, but for the Model and Controller to remain (primarily) OCaml.</p> <p>Does anybody know of a way to write Emacs extensions in a language other than Lisp? This could either take the form of bindings to the Emacs extension API in some other language (e.g., making OCaml a first-class Emacs extension language) or an Emacs interaction mode where, for example, the extension has a pipe into which it can write Emacs Lisp expressions and read out result values.</p>
<p><a href="http://www.emacswiki.org/cgi-bin/emacs-en?CategoryExtensionLanguage" rel="nofollow noreferrer">http://www.emacswiki.org/cgi-bin/emacs-en?CategoryExtensionLanguage</a> is a list of all non-Elisp extension languages you can use.</p> <p>It does appear to be dynamic language centric.</p> <p><a href="http://common-lisp.net/project/slime/" rel="nofollow noreferrer">http://common-lisp.net/project/slime/</a> is missing from that list, as it is not quite an extension language, but an Elisp-Common Lisp bridge. Its source code would show how to communicate back and forth over sockets.</p> <p>A similar IDE for Erlang is Distel, at <a href="http://fresh.homeunix.net/~luke/distel/" rel="nofollow noreferrer">http://fresh.homeunix.net/~luke/distel/</a> (currently down) and <a href="https://github.com/massemanet/distel" rel="nofollow noreferrer">https://github.com/massemanet/distel</a>.</p> <p>Good luck!</p>
<p>There is no "Extension API". Emacs Lisp is way in there, and it ain't moving.</p> <p>You can run Emacs commands from your other process. Have a look at Gnuserv.</p> <p>There are plenty of applications where Emacs is the View for a Model/Controller in a separate process. The Emacs GDB interface is a good example. I'm not sure of a simpler example, maybe sql-postgresql?</p>
3,597
<p>When you cut or break a PLA model (for example to remove support) it often leaves an ugly while mark where the removed piece was connected.</p> <p>Sanding also tend to leave dull white scratches on the sanded surface.</p> <p>What can I do to restore the white areas to the original filament color?</p>
<p>A quick blast from a heat gun will very slightly reflow the surface texture and eliminate white marks. </p> <p>However, it's important to avoid over-heating the perimeter layers or you'll see them soften and sag into the infill. So wait for the heat gun to get fully hot and then use a short duration of high heat. Let the part cool between attempts if you don't get it all the first time, or need to clean up a large area. </p> <p>Incidentally, the heat gun will also help clean up strings from travel moves.</p>
<p>Note that on lighter colours these light scratches can be hard to see. On white PLA they're almost invisible unless you hold it against the light at an angle and look at the specular reflection.</p> <p>I've had some luck on a flat surface (the face of a game tile I printed) by going through various grades of sand paper. 240, 600, 1000, 2000. Finally, finishing with a regular metal polisher like Brasso brings up a shine that doesn't seem to wash off, unlike vaseline/vegetable oil.</p> <p>It's quite a lot of work though, and even more work on curved surfaces. If heat treatment works for you, it may be preferable.</p>
202
<p>Is there a better way to flash a window in Java than this:</p> <pre><code>public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); } </code></pre> <p>I know that this code is scary...But it works alright. (I should implement a loop...)</p>
<p>There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying.</p> <p>See <a href="http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html" rel="nofollow noreferrer">documentation on the <code>TrayIcon</code> class</a>, particularly the <a href="http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html#displayMessage(java.lang.String,%20java.lang.String,%20java.awt.TrayIcon.MessageType)" rel="nofollow noreferrer"><code>displayMessage()</code></a> method.</p> <p>The following links may be of interest:</p> <ul> <li><a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/" rel="nofollow noreferrer">New System Tray Functionality in Java SE 6</a></li> <li><a href="http://forums.sun.com/thread.jspa?threadID=5130669&amp;messageID=9469354" rel="nofollow noreferrer">Java Programming - Iconified window blinking</a></li> <li><a href="https://jdic.dev.java.net/documentation/incubator/tray/" rel="nofollow noreferrer"><code>TrayIcon</code> for earlier versions of Java</a></li> </ul>
<p>Well, there are a few minor improvements we could make. ;)</p> <p>I would use a Timer to make sure callers don't have to wait for the method to return. And preventing more than one flashing operation at a time on a given window would be nice too.</p> <pre><code>import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import javax.swing.JFrame; public class WindowFlasher { private final Timer timer = new Timer(); private final Map&lt;JFrame, TimerTask&gt; flashing = new ConcurrentHashMap&lt;JFrame, TimerTask&gt;(); public void flashWindow(final JFrame window, final long period, final int blinks) { TimerTask newTask = new TimerTask() { private int remaining = blinks * 2; @Override public void run() { if (remaining-- &gt; 0) window.setVisible(!window.isVisible()); else { window.setVisible(true); cancel(); } } @Override public boolean cancel() { flashing.remove(this); return super.cancel(); } }; TimerTask oldTask = flashing.put(window, newTask); // if the window is already flashing, cancel the old task if (oldTask != null) oldTask.cancel(); timer.schedule(newTask, 0, period); } } </code></pre>
6,687
<p>In addition, are there any performance advantages to static methods over instance methods?</p> <p>I came across the following recently: <a href="http://www.cafeaulait.org/course/week4/22.html" rel="noreferrer">http://www.cafeaulait.org/course/week4/22.html</a> :</p> <blockquote> <p>When should a method be static?</p> <ol> <li>Neither reads from nor writes to instance fields</li> <li>Independent of the state of the object</li> <li>Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value</li> <li>Factory methods that serve in lieu of constructors</li> </ol> </blockquote> <p>I would be very interested in the feedback of the Stack Overflow community on this.</p>
<p>Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.</p> <p>You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.</p>
<p>Here is a related discussion as to <a href="https://stackoverflow.com/questions/23228/why-is-stringformat-static"><strong>why String.Format is static</strong></a> that will highlight some reasons.</p>
7,119
<p>If I have a table structure that is: </p> <pre><code>code, description, isdeleted </code></pre> <p>where <code>code</code> is the primary key.</p> <p>The user creates a record, then later on deletes it. Because I am using soft deletes the <code>isdeleted</code> will be set to true. Then in my queries I would be doing a select with the where clause <code>and not isdeleted</code></p> <p>Now if a user goes to create a new record they may see that code 'ABC' doesn't exist so they tried to recreate it. The select statement won't find it because of the where clause. But there will be a primary key index error.</p> <p>Should the user be allowed to re-use the record? I would think not since the idea of the soft delete is to keep the record for queries on older data so that joins to the 'deleted' record still work. If the user was allowed to re-use the code then they could change the description which might change the view of the historical data. But is it too harsh to stop them from using that code at all?</p> <p>Or should I be using a completely hidden primary key and then the 'code' field can be re-used?</p>
<p>I know many people have argued that the data should be natural, but you should be using a primary key that is completely separate from your data if you're going to be supporting soft deletes without the intention of always re-using the previous record when this situation arises.</p> <p>Having a divorced primary key will allow you to have multiple records with the same 'code' value, and it will allow you to "undelete" (otherwise, why bother with a soft delete?) a value without worrying about overwriting something else.</p> <p>Personally, I prefer the numeric auto-incremented style of ID, but there are many proponents of GUIDs.</p>
<p>When you select records (excluding soft-deletes) to display them in user interface/ output file, use where not isdeleted.</p> <p>But when the user requests an insert operation, perform two queries.</p> <ol> <li><p>Lookup all records (ignoring isdeleted value).</p></li> <li><p>Based on first query result, perform an UPDATE if it exists (and reverse isdeleted flag) or perform a true INSERT if it does not exist.</p></li> </ol> <p>The nuances of the business logic are up to you.</p>
9,552
<p>Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it?</p> <p>** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).</p> <p>** Rails signals registered. HUP => reload (without restart). It might not work well.</p>
<p>You can add the -c option if the config for your app's cluster is elsewhere:</p> <pre><code>mongrel_rails cluster::restart -c /path/to/config </code></pre>
<p>For example,</p> <pre><code>killall -USR2 mongrel_rails </code></pre>
9,990
<p>I find myself to be a visual person and sometimes it's easier to learn something if I can draw diagram/pictures out of it. My question is which tool do I use if I want to map a programming framework (for example .net) visually and see the relationship between all entities (such as classes and members).</p>
<p>You might try <a href="http://www.ndepend.com/" rel="nofollow noreferrer">NDepend</a>. The great <a href="http://www.hanselman.com/blog/ExitingTheZoneOfPainStaticAnalysisWithNDepend.aspx" rel="nofollow noreferrer">Scott Hanselman discusses it more here.</a> Tons of visual dependency formats too. It sounds like its only for .NET though.</p>
<p>A decent first-cut might be to write a simple PERL script to parse out dependencies and then pipe that data to <a href="http://www.graphviz.org/" rel="nofollow noreferrer" title="Graphviz">Graphviz</a> for visualization.</p>
6,837
<p>I am thinking about providing a version of say, the database schema and the <code>dlls</code> for business logic in the footer of my web application.</p> <p>Is this advised?</p> <p>Are there any pitfalls, or pointers of how to do this best?</p> <p>Usability concerns?</p> <p><strong>I already have a version scheme, for both schema and dlls, used in my CI solution.</strong></p>
<p>I quite like what is done e.g. <a href="http://episteme.arstechnica.com/" rel="noreferrer">here</a>. If you look towards the bottom of the page, there's a piece of text "powered by eve community". If you click that text you get a small chunk of technical information.</p> <p>To me, this is a nice tradeoff between having the (useful) information readily available (for bug reports, etc.) and having to have (unpleasant) technical jargon visible to users of the site.</p>
<p>IMO, the only reasons to show version numbers are:</p> <ul> <li>To show progress is being made</li> <li>To help bug reports be localized to the version they were discovered in</li> </ul> <p>So if these things are important for your bug reports, then expose them. If not, then don't.</p>
4,439
<p>I'm comparing between two techniques to create partitioned tables in SQL 2005.</p> <ul> <li>Use partitioned views with a standard version of SQL 2005 (described <a href="http://www.sqlservercentral.com/articles/SQL+Server+2005/61676/" rel="nofollow noreferrer">here</a>)</li> <li>Use the built in partition in the Enterprise edition of SQL 2005 (described <a href="http://www.sqlservercentral.com/articles/SQL+Server+2005/61765/" rel="nofollow noreferrer">here</a>)</li> </ul> <p>Given that the enterprise edition is much more expensive, I would like to know what are the main benefits of the newer enterprise built-in implementation. Is it just an time saver for the implementation itself. Or will I gain real performance on large DBs?</p> <p>I know i can adjust the constraints in the first option to keep a sliding window into the partitions. Can I do it with the built in version?</p>
<p>Yes and no. Cases can be linked to each other, but if you're looking for a tree of cases (prerequisites and such), you need FogBugz 7 or later.</p> <p>If you're using FogBugz 7.3 or greater, you can now use the <a href="http://www.fogcreek.com/fogbugz/plugins/plugin.aspx?ixPlugin=57" rel="nofollow noreferrer">Case Dependency Plugin</a>, which was released in April 2011.</p>
<p>FogBugz 7 now supports sub-cases. This may or may not solve your problem, depending on how you want to handle it.</p>
4,682
<p>I am creating an ZIP file with <code>ZipFile</code> in Python 2.5, it works OK so far:</p> <pre><code>import zipfile, os locfile = &quot;test.txt&quot; loczip = os.path.splitext (locfile)[0] + &quot;.zip&quot; zip = zipfile.ZipFile (loczip, &quot;w&quot;) zip.write (locfile) zip.close() </code></pre> <p>But I couldn't find how to encrypt the files in the ZIP file. I could use system and call <code>PKZIP -s</code>, but I suppose there must be a more &quot;Pythonic&quot; way. I'm looking for an open source solution.</p>
<p>I created a simple library to create a password encrypted zip file in python. - <a href="https://github.com/smihica/pyminizip" rel="noreferrer"><strong>here</strong></a></p> <pre><code>import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) </code></pre> <p><strong>The library requires zlib.</strong></p> <p>I have checked that the file can be extracted in WINDOWS/MAC.</p>
<p>You can use the <a href="http://www.chilkatsoft.com/python.asp" rel="nofollow noreferrer">Chilkat</a> library. It's commercial, but has a free evaluation and seems pretty nice.</p> <p>Here's an example I got from <a href="http://www.example-code.com/python/zip.asp" rel="nofollow noreferrer">here</a>:</p> <pre><code>import chilkat # Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip zip = chilkat.CkZip() zip.UnlockComponent("anything for 30-day trial") zip.NewZip("strongEncrypted.zip") # Set the Encryption property = 4, which indicates WinZip compatible AES encryption. zip.put_Encryption(4) # The key length can be 128, 192, or 256. zip.put_EncryptKeyLength(128) zip.SetPassword("secret") zip.AppendFiles("exampleData/*",True) zip.WriteZip() </code></pre>
3,794
<p>I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. </p>
<p>From my "Geometry" class:</p> <pre><code>public struct Line { public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } } } public struct Polygon: IEnumerable&lt;PointF&gt; { private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator&lt;PointF&gt; IEnumerable&lt;PointF&gt;.GetEnumerator() { return (IEnumerator&lt;PointF&gt;)points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); } } public enum Intersection { None, Tangent, Intersection, Containment } public static class Geometry { public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index &lt; polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X &amp;&amp; polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i &lt;= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y &gt; Math.Min(p1.Y, p2.Y)) { if (point.Y &lt;= Math.Max(p1.Y, p2.Y)) { if (point.X &lt;= Math.Max(p1.X, p2.X)) { if (p1.Y != p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X &lt;= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1) ? Intersection.Containment : Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y &gt;= bottomY &amp;&amp; point.Y &lt;= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 &amp;&amp; heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine &amp;&amp; heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } } </code></pre>
<p>I hate browsing the MSDN docs (they're awfully slow and weird :-s) but I think they should have something similar to <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/geom/Rectangle2D.html#intersectsLine%28double,%20double,%20double,%20double%29" rel="nofollow noreferrer">this Java method</a>... and if they haven't, bad for them! XD (btw, it works for segments, not lines).</p> <p>In any case, you can peek the open source Java SDK to see how is it implemented, maybe you'll learn some new trick (I'm always surprised when I look other people's code)</p>
4,995
<p>We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users.</p> <p>These templated cells need to handle custom databindings:</p> <pre><code>public class CustomColumnTemplate: ITemplate { public void InstantiateIn( Control container ) { //create a new label Label contentLabel = new Label(); //add a custom data binding contentLabel.DataBinding += ( sender, e ) =&gt; { //do custom stuff at databind time contentLabel.Text = //bound content }; //add the label to the cell container.Controls.Add( contentLabel ); } } ... myGridView.Columns.Add( new TemplateField { ItemTemplate = new CustomColumnTemplate(), HeaderText = "Custom column" } ); </code></pre> <p>Firstly this seems rather messy, but there is also a resource issue. The <code>Label</code> is generated, and can't be disposed in the <code>InstantiateIn</code> because then it wouldn't be there to databind.</p> <p>Is there a better pattern for these controls? </p> <p>Is there a way to make sure that the label is disposed after the databind and render?</p>
<p>I have worked extensively with templated control and I have not found a better solution.</p> <p>Why are you referencing the contentLable in the event handler?</p> <p>The sender is the label you can cast it to the label and have the reference to the label. Like below.</p> <pre><code> //add a custom data binding contentLabel.DataBinding += (object sender, EventArgs e ) =&gt; { //do custom stuff at databind time ((Label)sender).Text = //bound content }; </code></pre> <p>Then you should be able to dispose of the label reference in InstantiateIn.</p> <p>Please note I have not tested this.</p>
<p>One solution is to make your template <em>itself</em> implement <code>IDisposable</code>, and then dispose the controls in your template's <code>Dispose</code> method. Of course this means you need some sort of collection to keep track of the controls you've created. Here is one way to go about it:</p> <pre><code>public class CustomColumnTemplate : ITemplate, IDisposable { private readonly ICollection&lt;Control&gt; labels = new List&lt;Control&gt;(); public void Dispose() { foreach (Control label in this.labels) label.Dispose(); } public void InstantiateIn(Control container) { //create a new label Label contentLabel = new Label(); this.labels.Add(contentLabel); </code></pre> <p>...</p> <pre><code> //add the label to the cell container.Controls.Add( contentLabel ); } } </code></pre> <p>Now you are still faced with the problem of disposing the template. But at least your template will be a responsible memory consumer because when you call <code>Dispose</code> on the template all of its labels will be disposed with it.</p> <p><strong>UPDATE</strong></p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/c02bde1c-6fbd-4d25-8727-b52c2e6ceb88" rel="nofollow">This link on MSDN</a> suggests that perhaps it is not necessary for your template to implement <code>IDisposable</code> because the controls will be rooted in the page's control tree and automatically disposed by the framework!</p>
4,979
<p>All the recent VisualSVN Server posts made me want to check it out. I have SVN running right now through Apache, but I'd like to try out VisualSVN Server, mostly for the Active Directory integration. Their docs don't describe whether you can easily migrate an existing repository. </p> <p>Anyone done this before?</p>
<p><a href="http://www.visualsvn.com/server" rel="nofollow noreferrer">VisualSVN Server</a> will use your existing SVN repositories with no problems. I have successfully migrated repositories from SVN + Apache to VisualSVN Server on multiple occasions.</p>
<p>There is a VisualSVN Server Knowledge Base article about the case: </p> <p><a href="http://www.visualsvn.com/support/topic/00010/" rel="nofollow noreferrer"><strong>How can I import my existing repository into newly installed VisualSVN Server?</strong></a> </p> <p><img src="https://i.stack.imgur.com/GDcjy.png" width="562" /></p>
3,386
<p>Is it possible to get a breakdown of CPU utilization <strong>by database</strong>?</p> <p>I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like <code>taskmgr</code>) or each SPID (like <code>spwho2k5</code>), I want to view the total CPU utilization of each database. Assume a single SQL instance.</p> <p>I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the <code>sqlservr.exe</code> CPU load.</p>
<p>Sort of. Check this query out:</p> <pre><code>SELECT total_worker_time/execution_count AS AvgCPU , total_worker_time AS TotalCPU , total_elapsed_time/execution_count AS AvgDuration , total_elapsed_time AS TotalDuration , (total_logical_reads+total_physical_reads)/execution_count AS AvgReads , (total_logical_reads+total_physical_reads) AS TotalReads , execution_count , SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 , ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt , query_plan FROM sys.dm_exec_query_stats AS qs cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY 1 DESC </code></pre> <p>This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots.</p> <p>When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this:</p> <pre><code>USE msdb DECLARE @StringToExecute VARCHAR(1000) SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog' EXEC @StringToExecute </code></pre> <p>The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption?</p> <p>It gets worse when you:</p> <ul> <li>Join between multiple databases</li> <li>Run a transaction in multiple databases, and the locking effort spans multiple databases</li> <li>Run SQL Agent jobs in MSDB that "work" in MSDB, but back up individual databases</li> </ul> <p>It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level.</p> <p>In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though.</p> <p>For more of those, check out the <a href="http://www.toadworld.com/platforms/sql-server/w/wiki/10040.transact-sql-code-library.aspx" rel="noreferrer">T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia)</a>.</p> <p><em>Updated on 1/29 to include total numbers instead of just averages.</em></p>
<p>Take a look at <a href="http://www.sqlsentry.com/" rel="nofollow noreferrer">SQL Sentry</a>. It does all you need and more.</p> <p>Regards, Lieven</p>
4,862
<p>I need to make chocolate busts.</p> <p>Is it better to make silicon reverse of the bust and cast the bust or directly print it using chocolate printer (I prefer cost and process speed over quality)? I don't have chocolate printer so if this method will be better I will need to use some 3D printing service.</p> <p>I need to make quite a large amount of the busts.</p>
<p>For your application, you should 3d print a positive model, then make a silicone mould negative of that model. Then use the silicone mould to make the final chocolate. Clean the silicone thoroughly before initial use. Fill gaps in the 3d printed model with a light epoxy resin. Use mould release and ensure you wash and sterilize that silicon mould before using it with chocolate.</p> <p>An actual chocolate printer is not easy to come by, as a normal 3d printer converted to use chocolate is not able to be sterilized for food use. The video in the link illustrates one person's attempt at this process. <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/oRBxuDvS2gs?start=0"></iframe> </div></div></p>
<blockquote> <p>I prefer ... process speed</p> </blockquote> <p>Printing is unlikely to win that battle. You might print a plastic mold once you can use for casts, but if you do make sure you use a liner of some kind. 3d-printed plastics are not considered food-safe.</p>
1,720
<p>How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost.</p>
<p>Download this: <a href="http://www.cpuid.com/cpuz.php" rel="noreferrer">http://www.cpuid.com/cpuz.php</a></p> <p>Also check, <a href="http://en.wikipedia.org/wiki/X86_virtualization" rel="noreferrer">http://en.wikipedia.org/wiki/X86_virtualization</a></p> <p>Edit: Additional, I know it's for XEN but the instructions are the same for all VMs that want hardware support. <a href="http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors" rel="noreferrer">http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors</a></p> <p>I can't try it from work, but I'm sure it can identify whether you've got the Intel VT or AMD-V instructions. Intel will have a "vmx" instruction and AMD will have a "svm". </p> <p>On linux you can check /proc/cpuinfo, "egrep '(vmx|svm)' /proc/cpuinfo"</p>
<p>Try just turning the option on in VirtualPC. If it doesn't do anything (or the option isn't available), then your PC doesn't.</p>
4,097
<p>There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.</p> <p>This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:</p> <pre><code>... we hold these truths to be self evident, that &lt;/page&gt; &lt;page&gt;all men are created equal, and are ... </code></pre> <p>So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.</p> <p>Anybody have any thoughts on this?</p>
<p>In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is <a href="http://en.wikipedia.org/wiki/Inter-process_communication" rel="noreferrer">Inter-process Communication (IPC)</a>. There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, <a href="http://en.wikipedia.org/wiki/Remote_procedure_call" rel="noreferrer">remote procedure calls (RPC)</a> and shared memory. On Windows it's also common to use <a href="http://msdn.microsoft.com/en-us/library/aa931932.aspx" rel="noreferrer">window messages</a>.</p> <p>I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can <a href="http://msdn.microsoft.com/en-us/library/ms644990.aspx" rel="noreferrer">hook on to the message loop of external processes and "spy" on the messages they are sending</a>. If your program generates a message event when the desired function is called, this could be a way to detect it.</p> <p>If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network).</p>
<p>What's the nature of that OnEmailSent event from that third party application? I mean, how do you know the application is triggering such an event?</p> <p>If <em>you</em> are planning on doing interprocess communication, the first question you should ask yourself is: Is it really necessary?</p> <p>Without questioning your motives, if you really need to do interprocess communication, you will need some sort of mechanism. The list is long, very long. From simple WM_DATA messages to custom TCP protocols to very complex Web services requiring additional infrastructures.</p> <p>This brings the question, what is it you are trying to do exactly? What is this third party application you have no control over?</p> <p>Also, the debugger has a very invasive way of debugging processes. Don't expect that to be the standard interprocess mechanism used by all other applications. As a matter of fact, it isn't.</p>
3,848
<p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p> <p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p> <p>I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>
<p>I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):</p> <pre><code>(defun buildtree (wordlist) ...code to build tree recursively returns the tree...) (define lookup (tree word) ...code to look up word using tree, returns t or nil...) (defun lookupmany (tree querylist) (if (eq querylist nil) nil (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist)) ) ) (defun main (wordlist querylist) ; the main entry point (lookupmany (buildtree wordlist) querylist) ) </code></pre> <p>if this is what you mean, this is fairly straight-forward functional programming. Is it really stateless? That's a matter of debate. Some people would say some forms of functional programming store what we normally call "state" on the stack. Moreover, Common LISP even since the first edition of the Steele book has had iterative constructs, and LISP has had setq for a long, long time.</p> <p>But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here.</p> <p>I think the above is something like the arrangement you mean.</p>
<p>I imagine you'd want something like a tree with a list of children, as described <a href="http://csus.cs.mcgill.ca/wiki/COMP-302_(Panangaden%2C_Pientka%2C_Winter_06)_Lectures#Trees_with_a_list_of_children" rel="nofollow noreferrer">here</a>.</p>
6,911
<p>I am making a simple game in order to learn a new language. I am in the process of collecting some music for the game and would like to use the MIDI format so that I can control the flow of the track (i.e., I would like to have an introduction that only plays once and does not play again when the song loops.)</p> <p>I am having a tough time finding information on how to modify existing MIDI files so that they may send a control change signal to the synthesizer. Has anyone had experience with this?</p> <hr> <p>I think that I should have been more clear with my original question. I am using an existing game engine which takes care of playing the music. I am under the impression that this control change value must be embedded directly in the MIDI file itself as I have no control over the synthesizer. From the manual:</p> <blockquote> <p>MIDI files are played via the DirectMusic Synthesizer. If a BGM MIDI file contains the control change value 111, that value is recognized as where the song will start repeating after it reaches the end.</p> </blockquote> <p>I wish I could do it programmatically. I suppose what I am after here is some sort of editor which will allow me to modify the MIDI file that I already have. </p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=6E938A6E-B383-466B-A3EE-5A655BF5DB8C&amp;displaylang=en" rel="nofollow noreferrer">DirectMusicProducer</a> is probably your best free option if you are playing using DirectMusic. I don't believe the MIDI record feature will include control changes, but your engine may support playing segment files which are much more flexible.</p> <p>The only MIDI sequencer I use cost around $300 (USD) about 10 years ago (and no longer appears to exist), but I am not aware of any good quality free MIDI file sequencers. (Note that "MIDI editor" is probably different to "MIDI file editor" or "MIDI sequencer")</p>
<p>try looking in the <a href="http://www.midi.org/about-midi/specinfo.shtml" rel="nofollow noreferrer">Midi 1.0 spec</a></p> <p>Here's a table of the <a href="http://www.midi.org/about-midi/table3.shtml" rel="nofollow noreferrer">control change messages</a> though it looks like you're looking for a way to do this in software. yes?</p> <p>you could try just sending it as raw midi data (ie. the messages on that table)</p> <p>looking over your question again... my answer is not that useful...</p> <p>what I would do if I were you is separate the introduction into it's own file and then you have a file containing <strong>just</strong> what you want to loop.</p> <p>you could also look at the spec for the <A href="http://www.midi.org/about-midi/smf/index.shtml" rel="nofollow noreferrer">Standard Midi File format (SMF)</a></p>
5,420
<p>I need help with finding what properties or designs I need to look for. I know that I will need these characteristics to work with the material of my choice: </p> <ul> <li>Can reach 300&nbsp;°C or up</li> <li>Can handle nozzle size larger than 1&nbsp;mm</li> <li>Can be used with polycarbonate filament</li> </ul> <p>I plan to use it in a custom RAMPS 1.4 3D printer running the Marlin firmware, in case this changes something. </p>
<p>By interpreting your question as <em>&quot;Can most hotends print polycarbonate at 300°C+?&quot;</em>, and taking into consideration the answers to <a href="https://3dprinting.stackexchange.com/questions/4209/can-cheap-hotend-parts-sourced-from-china-actually-produce-good-prints">Can cheap hotend parts sourced from China actually produce good prints?</a><sup>1</sup>, then it would seem to be safe to assume<sup>2</sup> that most hotends can, given a few adjustments or considerations:</p> <ul> <li>Use of a PT100<sup>3</sup> or thermocouple, en lieu of a thermistor</li> <li>Use of PTFE tubing</li> </ul> <p>Taken directly from <a href="https://e3d-online.com/v6" rel="nofollow noreferrer">E3D's V6 product info</a>:</p> <blockquote> <p>The V6 can comfortably reach 285°C with the supplied thermistor. By swapping a thermistor for a thermocouple (may require additional electronics) or PT100 you can reach over 400°C. This not only allows you to print extremely high temperature materials like Polycarbonate and Nylons but also eliminates HotEnd meltdown failures associated with PEEK/PTFE designs. The PTFE filament guide inside the V6 HotEnd is never subjected to high temperatures, so there is no risk of damage through overheating.</p> </blockquote> <hr /> <h3>Footnotes</h3> <p><sup>1</sup> The materials used by cheaper clones of the higher quality, more expensive, branded hotends are <em>probably</em> the same as those used in the branded hotends, and indeed are probably produced using the same pirated patterns/molds/casts, but with less care and quality involved. They can even be produced in <em>the same factory</em>, but are items that have failed the QA tests, and as such are not deemed to be <em>brandable</em>.</p> <p><sup>2</sup> Although, to paraphrase a quote from a movie: Assumptions can be considered to be the mother of all <em>disasters</em>.</p> <p><sup>3</sup> A Pt100 or Pt1000 is a Platinum RTD (<a href="https://en.wikipedia.org/wiki/Resistance_thermometer" rel="nofollow noreferrer">Resistance Temperature Detector</a>) with a resistance of 100 ohms at 0°C which changes with temperature. From this manufacturer's <a href="https://www.processparameters.co.uk/platinum-resistance-thermometers-pt100-pt1000/" rel="nofollow noreferrer">website</a>:</p> <blockquote> <p>A Pt100 or Pt1000 is a Platinum RTD (Resistance Temperature Detector) with a resistance of 100 ohms at 0°C which changes with temperature. They are suitable for applications in the temperature range of -200°C to 600°C but are more commonly used in the range -50°C to +250°C. These temperature sensors are reliable and can offer a higher degree of accuracy.</p> </blockquote>
<p>By interpreting your question as <em>&quot;Can most hotends print polycarbonate at 300°C+?&quot;</em>, and taking into consideration the answers to <a href="https://3dprinting.stackexchange.com/questions/4209/can-cheap-hotend-parts-sourced-from-china-actually-produce-good-prints">Can cheap hotend parts sourced from China actually produce good prints?</a><sup>1</sup>, then it would seem to be safe to assume<sup>2</sup> that most hotends can, given a few adjustments or considerations:</p> <ul> <li>Use of a PT100<sup>3</sup> or thermocouple, en lieu of a thermistor</li> <li>Use of PTFE tubing</li> </ul> <p>Taken directly from <a href="https://e3d-online.com/v6" rel="nofollow noreferrer">E3D's V6 product info</a>:</p> <blockquote> <p>The V6 can comfortably reach 285°C with the supplied thermistor. By swapping a thermistor for a thermocouple (may require additional electronics) or PT100 you can reach over 400°C. This not only allows you to print extremely high temperature materials like Polycarbonate and Nylons but also eliminates HotEnd meltdown failures associated with PEEK/PTFE designs. The PTFE filament guide inside the V6 HotEnd is never subjected to high temperatures, so there is no risk of damage through overheating.</p> </blockquote> <hr /> <h3>Footnotes</h3> <p><sup>1</sup> The materials used by cheaper clones of the higher quality, more expensive, branded hotends are <em>probably</em> the same as those used in the branded hotends, and indeed are probably produced using the same pirated patterns/molds/casts, but with less care and quality involved. They can even be produced in <em>the same factory</em>, but are items that have failed the QA tests, and as such are not deemed to be <em>brandable</em>.</p> <p><sup>2</sup> Although, to paraphrase a quote from a movie: Assumptions can be considered to be the mother of all <em>disasters</em>.</p> <p><sup>3</sup> A Pt100 or Pt1000 is a Platinum RTD (<a href="https://en.wikipedia.org/wiki/Resistance_thermometer" rel="nofollow noreferrer">Resistance Temperature Detector</a>) with a resistance of 100 ohms at 0°C which changes with temperature. From this manufacturer's <a href="https://www.processparameters.co.uk/platinum-resistance-thermometers-pt100-pt1000/" rel="nofollow noreferrer">website</a>:</p> <blockquote> <p>A Pt100 or Pt1000 is a Platinum RTD (Resistance Temperature Detector) with a resistance of 100 ohms at 0°C which changes with temperature. They are suitable for applications in the temperature range of -200°C to 600°C but are more commonly used in the range -50°C to +250°C. These temperature sensors are reliable and can offer a higher degree of accuracy.</p> </blockquote>
1,025
<p>I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. </p> <p>I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages "easy" questions in the private beta.</p> <p>What can newbies like me do for the site at this stage besides voting questions and answers?</p>
<h1>Vote!</h1> <p>Private Betas love, love, <em>love</em> votes. Without votes, it's difficult to attain privileges, get rewards, and help push us out to public beta.</p> <h1>Ask Questions!</h1> <p>I know you said this:</p> <blockquote> <p>I thought about asking about how to get started with 3D printing but SE explicitly discourages "easy" questions in the private beta.</p> </blockquote> <p>But here's the catch. "Easy" isn't defined. If you have an "easy" question, but it is specific, high-quality, and to the point, and you can show some effort in it, then, please, go ahead and ask it!</p> <h1>Participate!</h1> <p>You have a voice in our meta discussions as well. You also have the authority to suggest edits, to posts, tag wikis, and tag excerpts. They also get you +2 rep for each that is approved, which can help bring you more afloat. You can also give your opinion in scope, by casting close and reopen votes as well :)</p>
<p>I would suggest doing a bit of basic research on 3D printing (including reading questions and answers). From these you will learn more about it and hopefull you will have new questions about 3D printing that can be asked. </p> <p>If you are looking at getting a 3D printer, you could ask about different features listed and why they make prints better.</p>
0
<p>Task: implement paging of database records suitable for different RDBMS. Method should work for mainstream engines - MSSQL2000+, Oracle, MySql, etc.</p> <p>Please don't post RDBMS specific solutions, I know how to implement this for most of the modern database engines. I'm looking for the universal solution. Only temporary tables based solutions come to my mind at the moment.</p> <p><strong>EDIT:</strong><br> I'm looking for SQL solution, not 3rd party library.</p>
<p>There would have been a universal solution if SQL specifications had included paging as a standard. The requirement for any RDBMS language to be called an RDBMS language does not include paging support as well. </p> <p>Many database products support SQL with proprietary extensions to the standard language. Some of them support paging like MySQL with the limit clause, Rowid with Oracle; each handled differently. Other DBMS's will need to add a field called rowid or something like that.</p> <p>I dont think you can have a universal solution (anyone is free to prove me wrong here;open to debate) unless it is built into the database system itself or unless there is a company say ABC that uses Oracle, MySQL, SQL Server and they decide to have all the various database systems provide their own implementation of paging by their database developers providing a universal interface for the code that uses it. </p>
<p>SubSonic can do this for you if you if you can tolerate Open Source... <a href="http://subsonicproject.com/querying/webcast-using-paging/" rel="nofollow noreferrer">http://subsonicproject.com/querying/webcast-using-paging/</a></p> <p>Other than that I know NHib does as well</p>
8,705
<p>I recently broke the cooling fan on my Voxelab Aquila while doing some maintenance, and I'm in the middle of a multi piece print that I would like to finish soon. I found the fan replacement I need, but it's not going to arrive for over a week. I was wondering if it would be ok to print a few things with the broken fan, or if that would be bad for the motor or anything else. <a href="https://i.stack.imgur.com/8wC69.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8wC69.jpg" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/C8Kvm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C8Kvm.jpg" alt="enter image description here" /></a></p>
<p>As long as your ambient temperature is not excessive and you're not using a very high bed temperature, you should be fine.</p> <p>With insufficient cooling, there is a risk of heat creep - that is, of the heat from the melt zone working its way up to the area where the filament is supposed to be solid, potentially causing jams if it deforms and catches in crevices there. However, the hotend is made to operate in temperatures far above normal room temperature, e.g. in non-air-conditioned spaces, in enclosed chambers for printing ABS, etc.</p> <p>Just keep the space you're printing in cool and go on printing while you wait for a new fan to arrive. Maybe reduce your bed temperature a bit if you usually use temperatures on the high end (over 50°C).</p>
<p>If the fan is the part cooling fan, you'll have reduced cooling on the part as it is printed. This isn't necessarily going to be a problem, although you may have irregularities in the print surface.</p> <p>If the fan is the heat sink cooling fan, reduced cooling will be problematic. This could result in heat creep and clogging of the hot end.</p>
2,142
<p>Ruby setters—whether created by <code>(c)attr_accessor</code> or manually—seem to be the only methods that need <code>self.</code> qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:</p> <ul> <li>All methods need <code>self</code>/<code>this</code> (like Perl, and I think Javascript)</li> <li>No methods require <code>self</code>/<code>this</code> is (C#, Java)</li> <li>Only setters need <code>self</code>/<code>this</code> (Ruby?)</li> </ul> <p>The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: <code>foo.x = y</code>, <code>y = foo.x</code> . C# calls them properties.</p> <p>Here's a simple example; the same program in Ruby then C#:</p> <pre><code>class A def qwerty; @q; end # manual getter def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same def asdf; self.qwerty = 4; end # "self." is necessary in ruby? def xxx; asdf; end # we can invoke nonsetters w/o "self." def dump; puts "qwerty = #{qwerty}"; end end a = A.new a.xxx a.dump </code></pre> <p>take away the <code>self.qwerty =()</code> and it fails (Ruby 1.8.6 on Linux &amp; OS X). Now C#:</p> <pre><code>using System; public class A { public A() {} int q; public int qwerty { get { return q; } set { q = value; } } public void asdf() { qwerty = 4; } // C# setters work w/o "this." public void xxx() { asdf(); } // are just like other methods public void dump() { Console.WriteLine("qwerty = {0}", qwerty); } } public class Test { public static void Main() { A a = new A(); a.xxx(); a.dump(); } } </code></pre> <p>Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method <em>cannot</em> be invoked <em>without</em> self?</p> <p>There are certainly lots of cases where self <em>becomes</em> necessary. This is not unique to Ruby, just to be clear:</p> <pre><code>using System; public class A { public A() {} public int test { get { return 4; }} public int useVariable() { int test = 5; return test; } public int useMethod() { int test = 5; return this.test; } } public class Test { public static void Main() { A a = new A(); Console.WriteLine("{0}", a.useVariable()); // prints 5 Console.WriteLine("{0}", a.useMethod()); // prints 4 } } </code></pre> <p>Same ambiguity is resolved in same way. But while subtle I'm asking about the case where </p> <ul> <li>A method <em>has</em> been defined, and</li> <li><em>No</em> local variable has been defined, and</li> </ul> <p>we encounter</p> <pre><code>qwerty = 4 </code></pre> <p>which is ambiguous—is this a method invocation or an new local variable assignment?</p> <hr> <p>@Mike Stone</p> <p>Hi! I understand and appreciate the points you've made and your example was great. Believe me when I say, if I had enough reputation, I'd vote up your response. Yet we still disagree: </p> <ul> <li>on a matter of semantics, and</li> <li>on a central point of fact</li> </ul> <p>First I claim, not without irony, we're having a semantic debate about the meaning of 'ambiguity'.</p> <p>When it comes to parsing and programming language semantics (the subject of this question), surely you would admit a broad spectrum of the notion 'ambiguity'. Let's just adopt some random notation: </p> <ol> <li>ambiguous: lexical ambiguity (lex must 'look ahead')</li> <li>Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)</li> <li>AMBIGUOUS: ambiguity knowing everything at the moment of execution</li> </ol> <p>(and there's junk between 2-3 too). All these categories are resolved by gathering more contextual info, looking more and more globally. So when you say,</p> <blockquote> <p>"qwerty = 4" is UNAMBIGUOUS in C# when there is no variable defined...</p> </blockquote> <p>I couldn't agree more. But by the same token, I'm saying </p> <blockquote> <p>"qwerty = 4" is un-Ambiguous in ruby (as it now exists)</p> <p>"qwerty = 4" is Ambiguous in C#</p> </blockquote> <p>And we're not yet contradicting each other. Finally, here's where we really disagree: Either ruby could or could not be implemented without any further language constructs such that,</p> <blockquote> <p>For "qwerty = 4," ruby UNAMBIGUOUSLY invokes an existing setter if there<br> is no local variable defined</p> </blockquote> <p>You say no. I say yes; another ruby could exist which behaves exactly like the current in every respect, <em>except</em> "qwerty = 4" defines a new variable when no setter and no local exists, it invokes the setter if one exists, and it assigns to the local if one exists. I fully accept that I could be wrong. In fact, a reason why I might be wrong would be interesting.</p> <p>Let me explain.</p> <p>Imagine you are writing a new OO language with accessor methods looking like instances vars (like ruby &amp; C#). You'd probably start with conceptual grammars something like:</p> <pre><code> var = expr // assignment method = expr // setter method invocation </code></pre> <p>But the parser-compiler (not even the runtime) will puke, because even after all the input is grokked there's no way to know which grammar is pertinent. You're faced which a classic choice. I can't be sure of the details, but basically ruby does this:</p> <pre><code> var = expr // assignment (new or existing) // method = expr, disallow setter method invocation without . </code></pre> <p>that is why it's un-Ambiguous, while and C# does this:</p> <pre><code> symbol = expr // push 'symbol=' onto parse tree and decide later // if local variable is def'd somewhere in scope: assignment // else if a setter is def'd in scope: invocation </code></pre> <p>For C#, 'later' is still at compile time.</p> <p>I'm sure ruby could do the same, but 'later' would have to be at runtime, because as ben points out you don't know until the statement is executed which case applies.</p> <p>My question was never intended to mean "do I really need the 'self.'?" or "what potential ambiguity is being avoided?" Rather I wanted to know why was this particular choice made? Maybe it's not performance. Maybe it just got the job done, or it was considered best to always allow a 1-liner local to override a method (a pretty rare case requirement) ...</p> <p>But I'm sort of suggesting that the most dynamical language might be the one which postpones this decision the longest, and chooses semantics based on the most contextual info: so if you have no local and you defined a setter, it would use the setter. Isn't this why we like ruby, smalltalk, objc, because method invocation is decided at runtime, offering maximum expressiveness?</p>
<p>Well, I think the reason this is the case is because <code>qwerty = 4</code> is ambiguous—are you defining a new variable called <code>qwerty</code> or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the <code>self.</code> is required.</p> <p>Here is another case where you need <code>self.</code>:</p> <pre><code>class A def test 4 end def use_variable test = 5 test end def use_method test = 5 self.test end end a = A.new a.use_variable # returns 5 a.use_method # returns 4 </code></pre> <p>As you can see, the access to <code>test</code> is ambiguous, so the <code>self.</code> is required.</p> <p>Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with <code>this.</code>, just like the Ruby case.</p>
<p>Because otherwise it would be impossible to set local variables at all inside of methods. <code>variable = some_value</code> is ambiguous. For example:</p> <pre><code>class ExampleClass attr_reader :last_set def method_missing(name, *args) if name.to_s =~ /=$/ @last_set = args.first else super end end def some_method some_variable = 5 # Set a local variable? Or call method_missing? puts some_variable end end </code></pre> <p>If <code>self</code> wasn't required for setters, <code>some_method</code> would raise <code>NameError: undefined local variable or method 'some_variable'</code>. As-is though, the method works as intended:</p> <pre><code>example = ExampleClass.new example.blah = 'Some text' example.last_set #=&gt; "Some text" example.some_method # prints "5" example.last_set #=&gt; "Some text" </code></pre>
6,646
<p>I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C?</p>
<p><a href="http://xmlsoft.org/" rel="nofollow noreferrer">libxml</a> is a heavily used and documented XML library for C, which provides a SAX API. <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">Expat</a> is another, but in my experience is not as well documented.</p>
<p>Expat does StAX</p> <p><pre><code> #include "expat.h"` VRM_parser = XML_ParserCreate("ISO-8859-1"); XML_SetElementHandler(VRM_parser, CbStartTagHandler, CbEndTagHandler); XML_Parse(VRM_parser, text, strlen(text), 0); // start of XML XML_Parse(VRM_parser, text, strlen(text), 0); // more XML XML_Parse(VRM_parser, text, strlen(text), 0); // more XML XML_Parse(VRM_parser, text, strlen(text), 0); // more XML XML_Parse(VRM_parser, "", 0, 1); // to finish parsing </pre></code></p>
5,812
<p>There is a lot of information out there on object-relational mappers and how to best avoid impedance mismatch, all of which seem to be moot points if one were to use an object database. My question is why isn't this used more frequently? Is it because of performance reasons or because object databases cause your data to become proprietary to your application or is it due to something else? </p>
<ul> <li><strong>Familiarity.</strong> The administrators of databases know relational concepts; object ones, not so much.</li> <li><strong>Performance.</strong> Relational databases have been proven to scale far better.</li> <li><strong>Maturity.</strong> SQL is a powerful, long-developed language.</li> <li><strong>Vendor support.</strong> You can pick between many more first-party (SQL servers) and third-party (administrative interfaces, mappings and other kinds of integration) tools than is the case with OODBMSs.</li> </ul> <p>Naturally, the object-oriented model is more familiar to the <em>developer</em>, and, as you point out, would spare one of ORM. But thus far, the relational model has proven to be the more workable option.</p> <p>See also the recent question, <a href="https://stackoverflow.com/questions/800/object-orientated-vs-relational-databases">Object Orientated vs Relational Databases</a>.</p>
<p>Sören</p> <p>All of the reasons you stated are valid, but I see the problem with OODBMS is the logical data model. The object-model (or rather the network model of the 70s) is not as simple as the relational one, and is therefore inferior.</p>
8,676
<p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p> <pre><code>%token &lt;int&gt; INT %token &lt;string&gt; ID %token MINUS %start expr %type &lt;expr&gt; expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; </code></pre> <p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>
<p>Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.</p> <ol> <li>split <code>expr</code> into <code>simple_expr</code> and <code>expr_with_prefix</code></li> <li>allow only <code>simple_expr</code> or <code>(expr_with_prefix)</code> in an APPLY</li> </ol> <p>The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.</p> <p>You're going to have the same problem with 'a b c': is it <code>a(b(c))</code> or <code>(a(b))(c)</code>? You'll need to also break off <code>applied_expression</code> and required <code>(applied_expression)</code> in the grammar.</p> <p>I think this will do it, but I'm not sure:</p> <pre><code>expr := INT | parenthesized_expr | expr MINUS expr parenthesized_expr := ( expr ) | ( applied_expr ) | ( expr_with_prefix ) applied_expr := expr expr expr_with_prefix := MINUS expr </code></pre>
<p>Well, this simplest answer is to just ignore it and let the default reduce/reduce resolution handle it -- reduce the rule that appears first in the grammar. In this case, that means reducing <code>expr MINUS expr</code> in preference to <code>MINUS expr</code>, which is exactly what you want. After seeing <code>a-b</code>, you want to parse it as a binary minus, rather than a unary minus and then an apply.</p>
4,413
<p>I'm comparing it Java where you can start your application server in debug mode, then attach your IDE to the server. And you can change your code "on the fly" without restarting the server. As long as your changes don't affect any method signatures or fields you can just hit recompile for a class and the application server (servlet container) will reload the class.</p> <p>I suppose this is impossible in ASP.NET since all classes are packed into assemblies and you cannot unload/reload assemblies, can you ?</p> <p>So when you have an .aspx page and an assembly deployed to GAC and your codebehind changes you have to redeploy the assembly and reset IIS. I'm talking about Sharepoint applications in particular and I'm not sure whether you have to do iisreset for private assemblies but I guess you have too.</p> <p>So the best way to debug aspx pages with code behind I guess would be to get rid of the codebehind for the time of active debugging and move into the page, then when it is more or less working move it back to codebehind. (This would be applicable only for application pages in Sharepoint, site pages don't allow inline code )</p> <p>How do you approach debugging of your ASP.NET applications to make it less time consuming?</p>
<p>From <a href="http://blog.mattsmith.co.nz/Lists/Posts/Post.aspx?ID=45" rel="noreferrer">Matt Smiths</a> blog on how to get F5 debugging with sharepoint. A very cool trick.</p> <ol> <li>Create a web application project in Visual Studio (File -> New -> Project -> ASP.Net Web Application, not File -> New -> Web Site). </li> <li>Move the .csproj and .csproj.user files, along with the Properties folder, into C:\inetpub\wwwroot\wss\virtualdirectories\, where is the name or number of the web application corresponding to the SharePoint site you'd like to debug on. </li> <li>Attach the project to an existing solution (e.g. STSDEV project). </li> <li>Set as startup project (right-click project name, "Set as Startup Project"). </li> <li>Access project properties (right-click project name, "Properties") and click </li> <li>Under the "Servers" setting, click "Use IIS web server", then enter the URL to the SharePoint web application you want to debug on, e.g. <a href="http://mymachine:99" rel="noreferrer">http://mymachine:99</a>. </li> </ol>
<blockquote> <p>And you can change your code "on the fly" without restarting the server</p> </blockquote> <p>You can accomplish this with ASP.net if you make a Web Site project (as opposed to a Web Application Project). Using a Web Site project, you can post changes to code-behinds without having to refresh anything on the server, and the server does the compile work for you on all code changes. See <a href="http://msdn.microsoft.com/en-us/library/aa730880(VS.80).aspx#wapp_topic5" rel="nofollow noreferrer">here</a> for more info on this.</p> <p>This should also solve your difficulties with deploying the assembly to the GAC. As the server handles all compilations for Web Site projects, you wont have to redeploy any assemblies when changing files.</p>
5,187
<p>I have a K280 3D printer with a MKS V1.5 and Repetier firmware.</p> <p><a href="https://i.stack.imgur.com/yCoXM.jpg" rel="nofollow noreferrer" title="Damaged transistor associated with E0 (3rd one on the right)"><img src="https://i.stack.imgur.com/yCoXM.jpg" alt="Damaged transistor associated with E0 (3rd one on the right)" title="Damaged transistor associated with E0 (3rd one on the right)"></a></p> <p>I’ve damaged the transistor associated with E0 (3rd one on the right) and so that means I need to avoid that. I’ve decided to switch to E1 for the extruder but I have a feeling I need to go in the firmware or Repetier host and manipulate that. </p> <p>I don’t know how and any help would be great. </p> <p>The only info I can access for the firmware is the EEPROM and it seems that I can’t edit the pins. Also, do I need to edit the pin for the sensor or just where the extruder goes?</p>
<p>If you go through the <a href="https://www.repetier.com/firmware/v100/index.php" rel="nofollow noreferrer">Repetier-Firmware configuration tool for version 1.0.2</a> you can select the E1 stepper for the E0 extruder (or whatever stepper you want to use for it) in the tools tab sheet. I'm not familiar with Repetier, but if that does not work you would have to switch pin numbers. </p> <p>If you already have a Configuration.h, you can use that one (by loading it into the configuration tool) and alter the E1 afterwards so that you do not have to enter all the other options by yourself.</p> <p><strong>Edit:</strong> After some investigation, you can find your configuration file <a href="https://www.facebook.com/groups/1787070361537465/" rel="nofollow noreferrer">here</a> as described <a href="http://he3d-delta-printer-owners.wikia.com/wiki/Configuring_the_Repetier_Software_for_the_first_time" rel="nofollow noreferrer">here</a>, so the only thing you would have to do is to load the file in the online tool and adjust the E1 stepper for E0 extruder.</p>
<p>You can try editing the gcodes by searching and replacing E0 for E1, so this way the extruder E1 will be enabled.</p> <p>Other way is setting the Slicer to use 2 extruders but everything for printing on E1 like: Perimeter, Infill, Solid, Support/raft/skirt, Support / raft interface.</p> <p>The third one, Switch the transistor from E1 to E0 (your Q2 for Q1) or Q3 if you are not using the FAN output.</p>
771
<p>If I start a process via Java's <a href="http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html" rel="noreferrer">ProcessBuilder</a> class, I have full access to that process's standard in, standard out, and standard error streams as Java <code>InputStreams</code> and <code>OutputStreams</code>. However, I can't find a way to seamlessly connect those streams to <code>System.in</code>, <code>System.out</code>, and <code>System.err</code>.</p> <p>It's possible to use <code>redirectErrorStream()</code> to get a single <code>InputStream</code> that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C <code>system()</code> call.</p> <p>This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of <a href="http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html" rel="noreferrer"><code>isatty()</code></a> in the child process carries through the redirection.</p>
<p>You will need to copy the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Process.html" rel="noreferrer">Process</a> out, err, and input streams to the System versions. The easiest way to do that is using the <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html" rel="noreferrer">IOUtils</a> class from the Commons IO package. The <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29" rel="noreferrer">copy method</a> looks to be what you need. The copy method invocations will need to be in separate threads. </p> <p>Here is the basic code:</p> <pre><code>// Assume you already have a processBuilder all configured and ready to go final Process process = processBuilder.start(); new Thread(new Runnable() {public void run() { IOUtils.copy(process.getOutputStream(), System.out); } } ).start(); new Thread(new Runnable() {public void run() { IOUtils.copy(process.getErrorStream(), System.err); } } ).start(); new Thread(new Runnable() {public void run() { IOUtils.copy(System.in, process.getInputStream()); } } ).start(); </code></pre>
<p>For <code>System.in</code> use the following <code>pipein()</code> instead of <code>pipe()</code></p> <pre><code>pipein(System.in, p.getOutputStream()); </code></pre> <p>Implementation:</p> <pre><code>private static void pipein(final InputStream src, final OutputStream dest) { new Thread(new Runnable() { public void run() { try { int ret = -1; while ((ret = System.in.read()) != -1) { dest.write(ret); dest.flush(); } } catch (IOException e) { // just exit } } }).start(); } </code></pre>
8,518
<p>I have a basic Creality Ender-3 with a black rough bed cover. I'm printing with PLA.</p> <p>After assembly, I printed 3 or 4 small toys sliced by Cura with basic settings. All were printed very well!</p> <p>However, after that, extruded filament would not stick to the bed. I tried the following:</p> <ul> <li>Bed calibration with A4 paper (each corner with a tight nozzle to paper and repeated calibration again)</li> <li>Once raised up the bed temperature from stock 50 to 60&nbsp;&deg;C</li> <li>Washed the bed with a soap and water (and dried)</li> <li>Sprayed with a hair spray</li> <li>Changed the filament</li> </ul> <p>Nothing helped so far.</p> <p>What else can I try?</p>
<p>I think you may have used the wrong substance to clean your bed. Try using Isopropyl Alcohol (IPA). You may have left some residue behind from the soap, which is now interfering with adhesion. When that is done, ensure you've gone through the steps for bed leveling again. It's amazing how much of a difference proper bed leveling makes in adhesion. If it still doesn't work, post some pictures up of your results, which will help tremendously in getting you a better answer.</p>
<p>Set the bed temperature to the glass transition temperature, around 80 °C for PLA:</p> <ul> <li><p>Filament is slippery and non-adhesive at room temperature</p> </li> <li><p>Filament becomes sticky when near its melting temperature</p> </li> <li><p>Printed items can pop off of the bed by themselves when cool. This shows that they become less sticky when cool</p> </li> </ul> <p>I was told about this and have been successfully printing PLA without rafts, brims, skirts, etc.</p> <p>Try a tiny print such as a small temperature tower to start.</p> <p>Note: I've only been using PETG recently and continue using 80 °C; perhaps a bit of 'elephant foot' occurs. However I'm primarily doing structural prints (tools, cord hangers, etc.) and strength and print reliability (tall prints not coming loose during printing) are my highest priorities.</p> <p>I appreciate the suggestion of dropping to 75 °C for later layers and will try that.</p>
1,502
<p>I have a strange issue with my heated bed. It has been working well for a long time, but recently it has developed an issue where the temperature reported by the thermistor will occasionally jump by around 10 degrees.</p> <p><a href="https://i.stack.imgur.com/aMRF7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aMRF7.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/7CMAV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7CMAV.png" alt="enter image description here"></a></p> <p>My setup is a 600W, 240V silicone heater mat, with integrated 100k thermistor, that is switched with a solid state relay. The mat is fixed to a 4mm thick aluminium plate. It seems unlikely that these fluctuations are due to bad PID tuning since the reported temperature changes much more quickly than is physically possible.</p> <p>I've checked the wiring, tried using a different thermistor port and making sure the connector was properly plugged in, but to no avail. The fluctuations are brief enough that they don't cause any problems when printing, but I'm worried about the issue getting worse.</p> <p>I have a RAMBo board 1.1b, and I've tried using both the integrated 5V SMPS supply and an external USB supply.</p> <p>The issue is not limited to the start of printing, the temperature reported can be stable for a long time before the issue pops up. The issue also occurs during cooldown (further confirming that PID has nothing to do with it):</p> <p><a href="https://i.stack.imgur.com/ilKXA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ilKXA.png" alt="enter image description here"></a></p> <p>In fact, the issue seems slightly more common during heat up and cool down, but is not limited to these times.</p> <p>I would like to know what might be causing this issue, and if there's a way to solve it without replacing the thermistor (which would be a pain, since it's integrated into the heater mat).</p>
<p>It really looks like either a bad thermistor or bad electrical joints. Are the connections to the thermistor itself crimped, or soldered? Are there connectors near the thermistor that can get heated up by the bed?</p> <p>Electrical connections that are mechanical in nature (such as crimped, or using a connector) can degrade quickly in heated situations, particularly when the heating is intermittent. Consider replacing crimped connections with soldered joints where possible, and where not possible use gold plated connectors and crimps to avoid oxidation issues. Oxidation and poor mechanical connections will change resistance based on movement, giving you apparent increases or decreases in sensor readings even when the sensor output is unchanged.</p> <p>Chances are good that the thermistor itself is fine, but that the connection nearest the thermistor, between the wires and the thermistor, is faulty. If it's crimped, you may be able to simply add flux, then solder it to increase the bonding between the wires and the thermistor and decrease future issues with oxidation.</p> <p>Note that soldering is really only useful for the thermistor on the bed. The head thermistor must be crimped, as the head temperatures can exceed solder temperatures depending on the target temperature and the solder alloy.</p>
<p>It really looks like either a bad thermistor or bad electrical joints. Are the connections to the thermistor itself crimped, or soldered? Are there connectors near the thermistor that can get heated up by the bed?</p> <p>Electrical connections that are mechanical in nature (such as crimped, or using a connector) can degrade quickly in heated situations, particularly when the heating is intermittent. Consider replacing crimped connections with soldered joints where possible, and where not possible use gold plated connectors and crimps to avoid oxidation issues. Oxidation and poor mechanical connections will change resistance based on movement, giving you apparent increases or decreases in sensor readings even when the sensor output is unchanged.</p> <p>Chances are good that the thermistor itself is fine, but that the connection nearest the thermistor, between the wires and the thermistor, is faulty. If it's crimped, you may be able to simply add flux, then solder it to increase the bonding between the wires and the thermistor and decrease future issues with oxidation.</p> <p>Note that soldering is really only useful for the thermistor on the bed. The head thermistor must be crimped, as the head temperatures can exceed solder temperatures depending on the target temperature and the solder alloy.</p>
138
<p>I would like to filter an array of items by using the <code>map()</code> function. Here is a code snippet:</p> <pre><code>var filteredItems = items.map(function(item) { if( ...some condition... ) { return item; } }); </code></pre> <p>The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.</p> <p>Any idea?</p> <p>EDIT: Thanks, I forgot about <code>filter()</code>, what I wanted is actually a <code>filter()</code> then a <code>map()</code>.</p> <p>EDIT2: Thanks for pointing that <code>map()</code> and <code>filter()</code> are not implemented in all browsers, although my specific code was not intended to run in a browser.</p>
<p>You should use the <code>filter</code> method rather than map unless you want to mutate the items in the array, in addition to filtering.</p> <p>eg.</p> <pre><code>var filteredItems = items.filter(function(item) { return ...some condition...; }); </code></pre> <p>[Edit: Of course you could always do <code>sourceArray.filter(...).map(...)</code> to both filter and mutate]</p>
<p>following statement cleans object using map function.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arraytoclean = [{v:65, toberemoved:"gronf"}, {v:12, toberemoved:null}, {v:4}]; arraytoclean.map((x,i)=&gt;x.toberemoved=undefined); console.dir(arraytoclean);</code></pre> </div> </div> </p>
3,070
<p>I have been a VB.net developer for a few years now but I am currently applying to a few companies that use C#. I have even been told that at least one of the companies doesn't want VB.net developers. </p> <p>I have been looking online trying to find real differences between the two and have asked on crackoverflow. The only major differences are a few syntax difference which are trivial to me because I am also a Java developer. </p> <p>What would be a good response to an interviewer when they tell me they are looking for a C# developer - or similar questions? </p>
<p>I've had to interview people for a few C# positions and this is my general advice for VB.Net developers interviewing for a C# position:</p> <ul> <li>Make sure you are clear that you have been working VB.Net. This seems obvious but is something that apparently isn't (in my experience).</li> <li>Try to give a code sample, if possible. I've seen some horrible VB.Net (and C#) written by VB programmers who didn't seem to learn much in the transition to .Net.</li> <li>Be able to write in C# during the interview, if asked. I know there aren't many real differences between the two, but I don't want to pay you to learn the new syntax.</li> </ul> <p>For your specific question: I've asked that type of question before and what I wanted to hear about was how the underlying system and framework were the same. If possible, talk about garbage collection, IDisposable, finalizers, the dangers of unsafe code blocks, stack vs heap, etc. All the kind of stuff to show that you really understand the intricacies of the .Net framework. Right or wrong, the heritage of VB brings with it an expectation of a lack of understand of lower level programming and windows in general (which, ironically enough, a c++ developer would have of a c# developer... and so on). </p> <p>Lastly, how you frame your experience can make a world of difference. If you position yourself as a .Net developer, rather than VB.Net or C#, the stupid, pseudo-religious, banter may not enter the conversation. This of course requires that you actually know both VB.Net and C# at the time of the interview, but that's a good policy regardless.</p> <p>The truth of the matter is that if you find that the person interviewing you writes you off simply because you've previously been developing in VB.Net, it's likely not going to be a place you want to work at anyway.</p>
<p>VB or C# both are syntax only diffrent but if you are applying way of logic is same.</p>
3,557
<p>I use <a href="http://www.thekelleys.org.uk/dnsmasq/doc.html" rel="nofollow noreferrer">dnsmasq</a> to resolve DNS queries on my home network. Unfortunately, if a domain name is not known, it will append my own domain name to the request which means that I always end up viewing my own site in a browser.</p> <p>For example, if I enter <a href="http://dlksfhoiahdsfiuhsdf.com" rel="nofollow noreferrer">http://dlksfhoiahdsfiuhsdf.com</a> in a browser, I end up viewing my own site with that URL. If I try something like:</p> <pre><code>host dlksfhoiahdsfiuhsdf.com </code></pre> <p>Instead of the expected:</p> <pre><code>Host dlksfhoiahdsfiuhsdf.com not found: 3(NXDOMAIN) </code></pre> <p>I get this:</p> <pre><code>dlksfhoiahdsfiuhsdf.com.mydomainname.com has address W.X.Y.Z. </code></pre> <p>Clearly, dnsmasq is appending my domain name to impossible name requests in an effort to resolve them, but I'd rather see the not found error instead.</p> <p>I've tried playing with the <em>expand-hosts</em> and <em>domain</em> configuration settings, but to no avail. Is there anything else I can try?</p>
<p>try querying with a trailing dot to explicitly set the root:</p> <pre><code>host dlksfhoiahdsfiuhsdf.com. </code></pre>
<p>I tried removing <em>domain-needed</em> from my own configuration to replicate your issue and it did not produce this behaviour. It's the only other parameter I could find that might be close to relevant.</p> <p>What does your hosts file look like? Maybe something weird is going on there that makes it think all weird domains are local to your network?</p>
2,773
<p>We all know how to use <code>&lt;ctrl&gt;-R</code> to reverse search through history, but did you know you can use <code>&lt;ctrl&gt;-S</code> to forward search if you set <code>stty stop ""</code>? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. </p> <p>What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash?</p>
<pre><code>cd - </code></pre> <p>It's the command-line equivalent of the back button (takes you to the previous directory you were in).</p>
<p>Some useful mencoder commands I found out about when looking for some audio and video editing tools:</p> <p>from .xxx to .avi</p> <pre><code>mencoder movie.wmv -o movie.avi -ovc lavc -oac lavc </code></pre> <p>Dump sound from a video:</p> <pre><code>mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile fileout.mp3 filein.avi </code></pre>
9,388
<p>Of all the forms of CAPTCHA available, which one is the "least crackable" while remaining fairly human readable?</p>
<p>I agree with Thomas. Captcha is on its way out. But if you must use it, <a href="http://www.recaptcha.net" rel="noreferrer">reCAPTCHA</a> is a pretty good provider with a simple API.</p>
<p>As far as I know, the Google's one is the best that there is. It hasn't been broken by computer programs yet. What I know that the crackers have been doing is to copy the image and then send it to many phishing websites where humans solve them to enter those websites.</p>
8,421
<p>I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.</p> <p>Here's an example of the equations:</p> <pre><code>-44.3940 = a * 50.0 + b * 37.0 + tx -45.3049 = a * 43.0 + b * 39.0 + tx -44.9594 = a * 52.0 + b * 41.0 + tx </code></pre> <p>From this, I'd like to get the best approximation for <code>a</code>, <code>b</code>, and <code>tx</code>.</p>
<p><a href="http://en.wikipedia.org/wiki/Cramers_rule" rel="noreferrer">Cramer's Rule</a> and <a href="http://en.wikipedia.org/wiki/Gaussian_elimination" rel="noreferrer">Gaussian Elimination</a> are two good, general-purpose algorithms (also see <a href="http://en.wikipedia.org/wiki/Simultaneous_linear_equations" rel="noreferrer">Simultaneous Linear Equations</a>). If you're looking for code, check out <a href="http://en.wikipedia.org/wiki/GiNaC" rel="noreferrer">GiNaC</a>, <a href="http://maxima.sourceforge.net/" rel="noreferrer">Maxima</a>, and <a href="http://issc.uj.ac.za/symbolic/symbolic.html" rel="noreferrer">SymbolicC++</a> (depending on your licensing requirements, of course).</p> <p>EDIT: I know you're working in C land, but I also have to put in a good word for <a href="http://code.google.com/p/sympy/" rel="noreferrer">SymPy</a> (a computer algebra system in Python). You can learn a lot from its algorithms (if you can read a bit of python). Also, it's under the new BSD license, while most of the free math packages are GPL.</p>
<p>For general cases, you could use python along with numpy for Gaussian elimination. And then plug in values and get the remaining values.</p>
2,320
<p>I'm looking for clamps to fix the glass on my heatbed. After some search I found that some people use clamps printed of PLA. Can I use PLA clamps for a heated heatbed (~60&nbsp;°C)? </p> <p>I also tried foldback clips but they block my nozzle. The Anet A8 starts in the front left corner. When I start to print, the nozzle moves a little bit up on z, then up on y and right on x. At this first move it moves into the fold back clip. I'm looking for a way to fix the corners and not to fix the edge in the middle.</p> <p>What other clamps or clips can I use to fix the glass (~3&nbsp;mm) on the heatbed (~2.5&nbsp;mm)? I don't want to use glue.</p> <p>My printer is an Anet A8.</p>
<p>How about the Ultimaker clips? Ultimaker uses 2&nbsp;mm heat bed and 4&nbsp;mm glass, that should be within reach by bending the clips a bit. They have quite a low profile/footprint.</p> <p><a href="https://i.stack.imgur.com/kdjTts.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kdjTts.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/mxLEss.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxLEss.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/vPkxUs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vPkxUs.jpg" alt="enter image description here"></a></p> <p>These clamps are very cheap and can be found on those typical auction or Chinese sites.</p> <p>Alternatively, you can also tape the glass to the aluminium bed using kapton tape if you are concerned about hitting the binder clips. </p> <p>Note that e.g. in Marlin firmware, you can define a Z-offset to prevent hitting the binder clips on movement.</p>
<p>Let's analyze the problem:</p> <ul> <li>We have a 5.5 mm total thickness.</li> <li>We want to (semi)permanently affix the two layers together mechanically.</li> <li>The clips shall not be higher than about 0.2 mm to allow the nozzle to pass over them.</li> </ul> <h1>(non)Solution attempt zero:</h1> <p>Let's look at the problem objectively... we can print something, can we? Well... 0.2 mm or below of PLA means 0.2mm of PLA that need to withstand the stress of trying to push the glass to the bed. PLA, just like any plastic, isn't super strong in thin layers, especially when heated to 60°C to get a good bed adhesion. And then you might want to print something like ABS, which demands an 80°C or higher bed temperature. The result will not be pretty: either the clip breaks after a very short time or it starts to bend. The result: no clip, bed slipping free.</p> <h1>Solution attempt one:</h1> <p>Let's look at old picture frames that consist of just a glass sheet and a paper/wood backing. A &quot;Frameless Picture Frame&quot; like <a href="https://www.picture-frames-warehouse.com/P-19784/Glass-Clip-Photo-Frame-Is-Frameless-With-A-Tempered-Glass-Overlay" rel="nofollow noreferrer">this one</a><sup>1</sup>. These clips do need some kind of mounting on the underside.</p> <p>Using this design as a base, you might either get these clips or make similar ones yourself. But how to mount them?</p> <p>Well, here comes the nice part: we got some options.</p> <ul> <li>Glue or solder the clips to the underside of the bed. Removing the sheet gets a PITA, but is still possible</li> <li>Cutting mounting slots for the clips. The sheet can be removed by removing the clips now. But the bed heating might not like us cutting slots into the aluminium.</li> <li>Adding a mounting point. Again, we can use glue or solder to add some kind of framework that we mount the clips to. Like a piece of aluminium U-profile with the opening to the centre of the bed, giving us mounting points for the clips.</li> </ul> <p><sup>1 - This was just the first one that I found that had the right setup. I am not affiliated with them and don't get money for this.</sup></p> <h1>Solution attempt two:</h1> <p>Take this idea up a notch and look for this same principle applied.</p> <p>There is the <a href="https://www.3dprintandstuff.co.uk/shop/glass-retaining-clips-swiss-made" rel="nofollow noreferrer">&quot;Swiss Made Glass Retaining Clip&quot;</a> <a href="https://3dprinting.stackexchange.com/a/6898/8884">Perplexed Dipole</a> mentioned. Good idea, and instead of having to cut a notch into the aluminium bed, a simple, small hole would be sufficient. About the same price than a frameless picture frame but less construction work!</p> <p>And then there is, of course, the option to look at the Ultimaker and its <a href="https://ultimaker.com/en/resources/19947-replacing-the-build-plate-clamps" rel="nofollow noreferrer">Build Plate Clamps</a> like <a href="https://3dprinting.stackexchange.com/a/6900/8884">0scar</a> mentioned. If you can get them (also in the same price range as the other options) you even might have an easy installation: they are supposed to be mounted in the corners of the build plate by being held by the springs. For the A8, you'll have to possibly adjust the mounting point some, maybe even give them a little nub to pivot around to secure them in place, but this clearly is a solution too.</p>
1,038
<p>I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?</p> <p>Is there one elegant solution that works for the majority of the cases? </p>
<p>You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a <code>media="print"</code> so that it only applies to print media (when it is printed)</p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="print" href="print.css" /&gt; </code></pre>
<p>I am a php user, but the point must be that the result no matter what is HTML and HTML is styled with CSS and there is an option for your style sheets for just using the style for printing. This should be the way to do it, imho. About big tables, there isnt really a magic "fix" for that. Page will break where it breaks, dont really understand the problem here either. </p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="print" href="print.css" /&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="screen.css" /&gt; </code></pre>
6,891
<p>When using host headers to host multiple websites on the same IP address in IIS, is there any way of accessing that website from a browser running on the local machine?</p> <p>This is normally required when a given web component only allows configuration from the local machine. It's also useful when things like ASP.Net's built in error handling isn't working and you can only view the error in the browser but don't want to allow remote users to see it. </p> <p>This has baffled me for a while and everytime I come across it I end up giving up in frustration and reconfigure stuff so I can accomplish such tasks remotely.</p> <p><strong>Added:</strong> @Ishmaeel - modifying hosts doesn't seem to help - you either get a 400 error (if all websites have host headers) or whichever site is configured without a host header.</p>
<p>Just an idea: Mapping the hostname to 127.0.0.1 in the hosts ($WINDOWS$\system32\drivers\etc) file may help. This way you should be able to pull up the local IIS site by typing the hostname as if it's a remote server</p>
<p>Maybe I am not understanding the question, but what's wrong with just typing in the URL for the website? If it's the matter of domain name resolution, you can point to the right DNS or put it in <a href="http://en.wikipedia.org/wiki/Hosts_file" rel="nofollow noreferrer">hosts</a> file.</p>
5,733
<p>I'm looking for a method, or a code snippet for converting std::string to LPCWSTR</p>
<p>The solution is actually a lot easier than any of the other suggestions:</p> <pre><code>std::wstring stemp = std::wstring(s.begin(), s.end()); LPCWSTR sw = stemp.c_str(); </code></pre> <p>Best of all, it's platform independent.</p>
<p>It's so easy, no need to apply any custom method. Try with this:</p> <pre><code>string s = &quot;So Easy Bro&quot; LPCWSTR wide_string; wide_string = CA2T(s.c_str()); </code></pre> <p>I think, it will works.</p>
4,684
<p>Lets say that you have websites www.xyz.com and www.abc.com.</p> <p>Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider. </p> <p>Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again.</p> <p>What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice.</p>
<p>Try using FormAuthentication by setting the web.config authentication section like so:</p> <pre><code>&lt;authentication mode="Forms"&gt; &lt;forms name=".ASPXAUTH" requireSSL="true" protection="All" enableCrossAppRedirects="true" /&gt; &lt;/authentication&gt; </code></pre> <p>Generate a machine key. Example: <a href="https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/" rel="nofollow noreferrer">Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS ...</a></p> <p>When posting to the other application the authentication ticket is passed as a hidden field. While reading the post from the first app, the second app will read the encrypted ticket and authenticate the user. Here's an example of the page that passes that posts the field:</p> <p>.aspx:</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;p&gt;&lt;asp:Button ID="btnTransfer" runat="server" Text="Go" PostBackUrl="http://otherapp/" /&gt;&lt;/p&gt; &lt;input id="hdnStreetCred" runat="server" type="hidden" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>code-behind:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { FormsIdentity cIdentity = Page.User.Identity as FormsIdentity; if (cIdentity != null) { this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName; this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket); } } </code></pre> <p>Also see the cross app form authentication section in Chapter 5 of this <a href="http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-2-0-Security-Membership-and-Role-Management.productCd-0764596985.html" rel="nofollow noreferrer">book</a> from Wrox. It recommends answers like the ones above in addition to providing a homebrew SSO solution. </p>
<p>Alternatively if you want to roll your own and the sites in question are not on the same servers or don't have access to a shared database (in which case see the above responses) then you could place a <a href="http://en.wikipedia.org/wiki/Web_beacon" rel="nofollow noreferrer">web beacon</a> on each of the sites which would refer back to the other site. </p> <p>Place a single pixel image (web beacon) on site A which would call site B passing through the users ID (encrypted &amp; time stamped). This would then create a new user session on site B for the user which would be set as logged in. Then when the user visited site B they would already be logged in.</p> <p>To minimise calls you could only place the web beacon on the home page and or log in confirmation pages. I've used this successfully in the past to pass information between partner sites. </p>
9,772
<p>I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:</p> <blockquote> <p>Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.</p> </blockquote> <p>So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:</p> <pre><code>Guid UploadID = Guid.NewGuid(); Application.Add(Guid.ToString(), User); </code></pre> <p>So, I'm creating a unique ID and using it as a key to store the <code>Page.User</code> object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:</p> <pre><code>IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]]; </code></pre> <p>This actually works, but it has two glaring drawbacks: </p> <ul> <li><p>If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.</p></li> <li><p>If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.</p></li> </ul> <p>Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?</p> <p>I know I can get the session ID through <code>Session.SessionID</code>, and I know how to use YUI to post it to the next page. What I don't know is how to use that <code>SessionID</code> to grab the session from the state server.</p> <p>Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.</p>
<p><a href="http://swfupload.org/forum/generaldiscussion/98" rel="noreferrer">Here</a> is a post from the maintainer of <a href="http://swfupload.org" rel="noreferrer">SWFUpload</a> which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component.</p> <p>Note the security disclaimers at the bottom of the post.</p> <hr> <blockquote> <p>By including a Global.asax file and the following code you can override the missing Session ID cookie:</p> </blockquote> <pre><code>using System; using System.Web; public class Global_asax : System.Web.HttpApplication { private void Application_BeginRequest(object sender, EventArgs e) { /* Fix for the Flash Player Cookie bug in Non-IE browsers. Since Flash Player always sends the IE cookies even in FireFox we have to bypass the cookies by sending the values as part of the POST or GET and overwrite the cookies with the passed in values. The theory is that at this point (BeginRequest) the cookies have not been ready by the Session and Authentication logic and if we update the cookies here we'll get our Session and Authentication restored correctly */ HttpRequest request = HttpContext.Current.Request; try { string sessionParamName = "ASPSESSID"; string sessionCookieName = "ASP.NET_SESSIONID"; string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName]; if (sessionValue != null) { UpdateCookie(sessionCookieName, sessionValue); } } catch (Exception ex) { // TODO: Add logging here. } try { string authParamName = "AUTHID"; string authCookieName = FormsAuthentication.FormsCookieName; string authValue = request.Form[authParamName] ?? request.QueryString[authParamName]; if (authValue != null) { UpdateCookie(authCookieName, authValue); } } catch (Exception ex) { // TODO: Add logging here. } } private void UpdateCookie(string cookieName, string cookieValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName); if (cookie == null) { HttpCookie newCookie = new HttpCookie(cookieName, cookieValue); Response.Cookies.Add(newCookie); } else { cookie.Value = cookieValue; HttpContext.Current.Request.Cookies.Set(cookie); } } } </code></pre> <blockquote> <p><strong>Security Warning:</strong> Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting.</p> </blockquote>
<p>The ASP.Net Session ID is stored in <code>Session.SessionID</code> so you could set that in a hidden field and then post it to the next page.</p> <p>I think, however, that if the application restarts, the sessionID will expire if you do not <a href="http://support.microsoft.com/kb/317604" rel="nofollow noreferrer">store your sessions in sql server</a>.</p>
6,495
<p>I have a bunch of files that I need to be able to <em>transport</em> and <em>install</em> quickly. My current method for doing so is moving a flash drive with a readme file of where stuff goes whenever I need to move stuff, which is rather inelegant and cumbersome.</p> <p>My idea for a solution would be to write up a quick script to move files around that I could just click on. I've done some <strong><em>bash</em></strong> scripting before but <strong><em>batch</em></strong> scripting is a little odd to me. Does anyone have a good online reference guide I could use?</p> <p>An alternative soulution I could accept would be a program that makes an installer for you, though I'm a bit against that as I would lose a lot of control. However, I'd be alright with it if it was extremely simple,</p>
<p>Sounds like <code>robocopy</code> tool is exactly what you need. Very <em>powerful</em> replication command-line tool.</p> <ul> <li><a href="http://technet.microsoft.com/en-us/library/cc733145" rel="nofollow noreferrer">MS TechNet reference</a>,</li> <li><a href="http://en.wikipedia.org/wiki/Robocopy" rel="nofollow noreferrer">Wikipedia article</a> about <code>robocopy</code>,</li> <li>Full command switch <a href="http://atlex.nl/tmp/robocopy_switches.txt" rel="nofollow noreferrer">guide</a>,</li> <li>Batch scripting <a href="http://www.tacktech.com/display.cfm?ttid=307" rel="nofollow noreferrer">guide</a>.</li> </ul>
<p>I like to use VBscript for this kind of thing. The VBS engine is on every recent windows machine and the language is a little more like real programming than a batch script.</p> <p>Also, if your installer grows to require WMI functions too, this becomes a piece of cake.</p>
3,709
<p>We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..." </p> <p>Any thoughts on how to do this? I was thinking it could be a compiled HTML website that would write a cookie and only play once. I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).</p> <p>I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.</p> <p>Any other ideas?</p>
<p>If the content is HTML and run inside a normal browser window, then a cookie may work but there are caveats:</p> <ul> <li>User runs the CD once when IE is the default browser. User runs at a later time, when Firefox is the default browser so cookie cannot be checked.</li> <li>The browser's security settings may be locked down to prevent use of script so the cookie cannot be set (more of an IE problem).</li> </ul> <p>An alternative might be Flash's equivalent of cookies, but if script was locked down then the same may be true for Flash.</p>
<p>Not quite what you're looking for, but you could put in on re-writable media and have an executable over-write itself (or part of itself).</p> <p>I don't know if a CD-RW could do that automatically, or if you would have to look at cheap USB sticks.</p>
6,366
<p>I've opened an old workspace that is a libray and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app.</p> <p>I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately I can't post the project as this is used in production code.</p> <p>The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However this is part of the standard template library - and is a header at that.</p> <p>The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use <code>std::string</code> directly, but does call a class that does: <code>Comms::Exception</code> accepts a <code>std::string</code> and the value of <code>GetLastError</code> or <code>WSAGetLastError</code>.</p> <p>The function mentioned in the error (<code>GetMessage</code>) is implemented, but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an Ansi version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However both projects to specify _MBCS in the compiler options.</p> <blockquote> <p>--------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj) : error LNK2001: unresolved external symbol "public: virtual class std::basic_string,class std::allocator > __thiscall Comms::Exception::GetMessageA(void)const " (?GetMessageA@ Exception@Comms@@UBE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) Debug/TestComms.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe.</p> <p>TestComms.exe - 2 error(s), 0 warning(s)</p> </blockquote> <p>Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too.</p>
<p>One possibility lies with Win32 ANSI/Unicode "name-mangling", which turns the symbol <code>GetMessage</code> into either <code>GetMessageA</code> or <code>GetMessageW</code>. There are three possibilities:</p> <ol> <li><p>Windows.h hasn't been loaded, so <code>GetMessage</code> stays <code>GetMessage</code></p></li> <li><p>Windows.h was loaded with symbols set for ANSI, so <code>GetMessage</code> becomes <code>GetMessageA</code> </p></li> <li><p>Windows.h was loaded with symbols set for Unicode, so <code>GetMessage</code> becomes <code>GetMessageW</code></p></li> </ol> <p>If you've compiled two different files in ways that trigger two different scenarios, you'll get a linker error. The error message indicates that the <code>Comms::Exception</code> class was an instance of #2, above -- perhaps it's used somewhere that windows.h hasn't been loaded?</p> <p>Other things I'd do in your place, just as a matter of routine:</p> <p>1) Ensure that my include and library paths don't contain anything that I'm not expecting.</p> <p>2) Do a "build clean" and then manually verify it, deleting any extra object files if necessary.</p> <p>3) Make sure there aren't any hardcoded paths in include statements that don't mean what they meant when the project was originally rebuilt.</p> <p>EDIT: Fighting with the formatting :(</p>
<p>windows.h is declared at the top of IOCompletionPort.h as an include - I was sick of seeing 7 lines just to include 1 file so I have wrapped it its own file and includes that itself. This also contains some additional #defines (i.e. ULONG_PTR) as our main app won't compile with the Platform SDK installed:-(</p> <ol> <li>That is confirmed. Nothing is out of place.</li> <li>I've done that - deleted the build directories</li> <li>I never use hard-coded paths.</li> </ol>
2,775
<p>Sending a message from the Unix command line using <code>mail TO_ADDR</code> results in an email from <code>$USER@$HOSTNAME</code>. Is there a way to change the "From:" address inserted by <code>mail</code>?</p> <p>For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL).</p> <p>[EDIT]</p> <pre> $ mail -s Testing chris@example.org Cc: From: foo@bar.org Testing . </pre> <p>yields</p> <pre> Subject: Testing To: &lt;chris@example.org&gt; X-Mailer: mail (GNU Mailutils 1.1) Message-Id: &lt;E1KdTJj-00025z-RK@localhost&gt; From: &lt;chris@localhost&gt; Date: Wed, 10 Sep 2008 13:17:23 -0400 From: foo@bar.org Testing </pre> <p>The "From: foo@bar.org" line is part of the message body, not part of the header.</p>
<p>In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses</p> <ul> <li>the <strong>-a</strong> switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header</li> <li>the <strong>$REPLYTO</strong> environment variable specifies a Reply-To: header</li> </ul> <p>so the following sequence</p> <pre><code>export REPLYTO=cms-replies@example.com mail -aFrom:cms-sends@example.com -s 'Testing' </code></pre> <p>The result, in my mail clients, is a mail from cms-sends@example.com, which any replies to will default to cms-replies@example.com</p> <p><em>NB:</em> Mac OS users: you don't have -a , but you do have <strong>$REPLYTO</strong></p> <p><em>NB(2):</em> CentOS users, many commenters have added that you need to use <code>-r</code> not <code>-a</code></p> <p><em>NB(3):</em> This answer is at least ten years old(1), please bear that in mind when you're coming in from Google. </p>
<p>The answers provided before didn't work for me on CentOS5. I installed mutt. It has a lot of options. With mutt you do this this way:</p> <pre><code>export EMAIL=myfrom@example.com export REPLYTO=myreplyto@example.com mutt -s Testing chris@example.org </code></pre>
7,832
<p>Any suggestions for tools to monitor page load times/errors and other performance metrics for a PHP application?</p> <p>I am aware of the FireBug and YSlow tools, but this is for more server monitoring.</p>
<p>There is the classic 'ab' (apachebench) program. More power comes from <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">JMmeter</a>. For server health, I recommend Munin, which can painlessly capture data from several systems and aggregate it on one page. </p>
<p>Try <a href="http://www.nagios.org/" rel="nofollow noreferrer">Nagios</a>, it's the default tool to monitor servers. You can write plugins to report just about any data. </p>
9,485
<p>I bought a 32 GB SDHC (Sandisk) I'd like to use for my Monoprice 3D printer.<br> I have downloaded Partition Wizard and partitioned a 2GB primary partition formatted as FAT and it still does not show any files. </p> <p>What am I doing wrong?</p>
<p>For an SD card to work with the printer firmware <a href="https://monopricesupport.kayako.com/article/59-why-is-my-printer-not-reading-my-sd-card" rel="noreferrer">Monoprice suggests to format the SD card to FAT32</a>.</p> <p>However, the Monoprice Select Mini V2 is not able to read SDHC memory cards, it is advised to use an SD card (smaller than 4&nbsp;GB) instead.</p> <p>According to the <a href="https://monopricesupport.kayako.com/" rel="noreferrer">Monoprice support website</a>: <a href="https://monopricesupport.kayako.com/article/59-why-is-my-printer-not-reading-my-sd-card" rel="noreferrer">"Why is my printer not reading my SD card?"</a>:</p> <blockquote> <p>If the SD card is not recognized on the printer or if the files are not reading, it could be an issue with the actual card itself. The first thing we recommend checking is that none of the print files on the SD card contain a space in their name. This shows in the printer as an unidentified character and can cause issues. If none of your prints contain spaces, we recommend reformatting your SD card.</p> <p>Note: If you choose to purchase an SD card, <strong><em>please make sure that it is not labeled HC (High Capacity)</em></strong> as it <strong><em>may not be compatible with the printer</em></strong>. This means that <strong><em>the card must be smaller than 4GB in size</em></strong>.</p> </blockquote> <p>The last part of the support page is probably applicable to your card.</p> <p>Some further information can be found in <a href="https://3dprinting.stackexchange.com/questions/5247/what-is-the-largest-microsd-card-that-a-monoprice-select-mini-can-read">What is the largest microSD card that a Monoprice Select Mini can read?</a>, specifically <a href="https://3dprinting.stackexchange.com/a/5311/5740">this answer</a>. From this latter answer, I quote:</p> <blockquote> <p>Cards between 2 GB and 32 GB <strong><em>might</em></strong> work, depending on the specifics of the card</p> </blockquote> <p>Basically there are no guarantees when using large cards.</p>
<p>I was having problems formatting micro SD cards for my Monoprice Mini v2. I have some 256 MB cards tried formatting them FAT FAT32 etc, no luck.</p> <p>Then I downloaded a program called <a href="https://www.sdcard.org/downloads/formatter/" rel="nofollow noreferrer">SD Memory Card Formatter</a> did the format on the card with this and the card is now readable in the printer.</p>
1,160
<p>This morning, I was reading <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">Steve Yegge's: When Polymorphism Fails</a>, when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.</p> <blockquote> <p>As an example of polymorphism in action, let's look at the classic "eval" interview question, which (as far as I know) was brought to Amazon by Ron Braunstein. The question is quite a rich one, as it manages to probe a wide variety of important skills: OOP design, recursion, binary trees, polymorphism and runtime typing, general coding skills, and (if you want to make it extra hard) parsing theory.</p> <p>At some point, the candidate hopefully realizes that you can represent an arithmetic expression as a binary tree, assuming you're only using binary operators such as "+", "-", "*", "/". The leaf nodes are all numbers, and the internal nodes are all operators. Evaluating the expression means walking the tree. If the candidate doesn't realize this, you can gently lead them to it, or if necessary, just tell them.</p> <p>Even if you tell them, it's still an interesting problem.</p> <p>The first half of the question, which some people (whose names I will protect to my dying breath, but their initials are Willie Lewis) feel is a Job Requirement If You Want To Call Yourself A Developer And Work At Amazon, is actually kinda hard. The question is: how do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree. We may have an ADJ challenge on this question at some point.</p> <p>The second half is: let's say this is a 2-person project, and your partner, who we'll call "Willie", is responsible for transforming the string expression into a tree. You get the easy part: you need to decide what classes Willie is to construct the tree with. You can do it in any language, but make sure you pick one, or Willie will hand you assembly language. If he's feeling ornery, it will be for a processor that is no longer manufactured in production.</p> <p>You'd be amazed at how many candidates boff this one.</p> <p>I won't give away the answer, but a Standard Bad Solution involves the use of a switch or case statment (or just good old-fashioned cascaded-ifs). A Slightly Better Solution involves using a table of function pointers, and the Probably Best Solution involves using polymorphism. I encourage you to work through it sometime. Fun stuff!</p> </blockquote> <p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p> <p>Feel free to tackle one, two, or all three.</p> <p>[update: title modified to better match what most of the answers have been.]</p>
<p><strong>Polymorphic Tree Walking</strong>, Python version</p> <pre><code>#!/usr/bin/python class Node: """base class, you should not process one of these""" def process(self): raise('you should not be processing a node') class BinaryNode(Node): """base class for binary nodes""" def __init__(self, _left, _right): self.left = _left self.right = _right def process(self): raise('you should not be processing a binarynode') class Plus(BinaryNode): def process(self): return self.left.process() + self.right.process() class Minus(BinaryNode): def process(self): return self.left.process() - self.right.process() class Mul(BinaryNode): def process(self): return self.left.process() * self.right.process() class Div(BinaryNode): def process(self): return self.left.process() / self.right.process() class Num(Node): def __init__(self, _value): self.value = _value def process(self): return self.value def demo(n): print n.process() demo(Num(2)) # 2 demo(Plus(Num(2),Num(5))) # 2 + 3 demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2) </code></pre> <p>The tests are just building up the binary trees by using constructors.</p> <p>program structure:</p> <p>abstract base class: Node</p> <ul> <li>all Nodes inherit from this class</li> </ul> <p>abstract base class: BinaryNode</p> <ul> <li>all binary operators inherit from this class</li> <li>process method does the work of evaluting the expression and returning the result</li> </ul> <p>binary operator classes: Plus,Minus,Mul,Div</p> <ul> <li>two child nodes, one each for left side and right side subexpressions</li> </ul> <p>number class: Num</p> <ul> <li>holds a leaf-node numeric value, e.g. 17 or 42</li> </ul>
<p>should use a functional language imo. Trees are harder to represent and manipulate in OO languages.</p>
3,354
<p>Right, initially ran:</p> <pre><code>c:\regsvr32 Amazing.dll </code></pre> <p>then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know <em>now</em> I should've run:</p> <pre><code>c:\regsvr32 /u Amazing.dll </code></pre> <p>beforehand - but hey! I forgot.</p> <p>To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running <code>regsvr32 /u</code> removes one of the references, the second time - does nothing...</p> <p>How do I get rid of these references? Am I looking at a regedit scenario? - If so - what <em>exactly</em> happens if I delete one of the keys???</p> <p>Cheers</p>
<p>Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry.</p> <p>Unless you added additional COM interfaces or objects to the project.</p> <p>In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually.</p>
<p>I've got myself into a horrible mess with COM before. I had to pick my way though the registry deleting each reference, unfortunately.</p>
4,010
<p>I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?</p>
<p>I figured out a better way of doing this, using the CellFormatting event:</p> <pre><code>Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting If uxContacts.CurrentCell IsNot Nothing Then If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then e.CellStyle.SelectionBackColor = Color.SteelBlue Else e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor End If End If End Sub </code></pre>
<p>You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and color in the cell you're interested in.</p> <p>An example is here at <a href="http://msdn.microsoft.com/en-us/library/85kxk29c.aspx" rel="nofollow noreferrer">MSDN</a></p>
9,913
<p>I have found a video about Invisalign. I saw a 3D printer in the video but I did not understand its type. Can you help me? Do you share a brief piece of information about its type?</p> <p>Below is the video on YouTube.</p> <p><div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/bKsGNrEKx9M?start=0"></iframe> </div></div></p>
<p>In the video, there is this still from <a href="https://youtu.be/bKsGNrEKx9M?t=32" rel="nofollow noreferrer">0:32</a>:</p> <p><a href="https://youtu.be/bKsGNrEKx9M?t=32" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jf2F8.png" alt="enter image description here" /></a></p> <p>The labeling is iPro 8000, which is a <a href="http://infocenter.3dsystems.com/product-library/sla/ipro-8000-9000" rel="nofollow noreferrer">3dSystems resin printer using SLA technology.</a></p>
<p>If you look at the video at 37 seconds, it appears to be SLA or DLP.</p> <p>Further reading: <a href="https://www.solidprint3d.co.uk/wp-content/uploads/2019/04/SLA_vs_DLP.pdf" rel="nofollow noreferrer">https://www.solidprint3d.co.uk/wp-content/uploads/2019/04/SLA_vs_DLP.pdf</a></p>
1,876
<p>Basically I want to get the number of lines-of-code in the repository after each commit.</p> <p>The only (really crappy) ways I have found is to use <code>git filter-branch</code> to run <code>wc -l *</code>, and a script that runs <code>git reset --hard</code> on each commit, then runs <code>wc -l</code></p> <p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):</p> <pre class="lang-none prettyprint-override"><code>me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 </code></pre> <p>I've played around with the ruby 'git' library, but the closest I found was using the <code>.lines()</code> method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)</p> <pre class="lang-rb prettyprint-override"><code>require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end </code></pre>
<p>You might also consider <a href="http://gitstats.sourceforge.net/" rel="noreferrer">gitstats</a>, which generates this graph as an html file. </p>
<p>The first thing that jumps to mind is the possibility of your git history having a nonlinear history. You might have difficulty determining a sensible sequence of commits.</p> <p>Having said that, it seems like you could keep a log of commit ids and the corresponding lines of code in that commit. In a post-commit hook, starting from the HEAD revision, work backwards (branching to multiple parents if necessary) until all paths reach a commit that you've already seen before. That should give you the total lines of code for each commit id.</p> <p>Does that help any? I have a feeling that I've misunderstood something about your question.</p>
4,370
<p>Code below does not run correctly and throws <code>InvalidOperationExcepiton</code>.</p> <pre><code>public void Foo() { DataContext context = new DataContext(); LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ; context.LinqEntities.Attach(item, true); } </code></pre>
<p>By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.</p> <p>This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.</p> <p>Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.</p> <pre><code>LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; context.LinqEntities.Attach(item); item.Name = "John"; item.Surname = "Doe"; context.SubmitChanges(); </code></pre>
<p>When using an ORM you typically select an object before updating it. </p> <p>You can use <code>DataContext.ExecuteCommand(...)</code> to bypass the ORM if you do not want to do a select. </p>
6,126
<p>I have a regex call that I need help with.</p> <p>I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.</p> <p>Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.</p> <pre><code>RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @"&lt;b&gt;${text}&lt;/b&gt;", regexOptions); </code></pre>
<p>Heres an implementation of this I've used to pick out special replace strings from content and localize them.</p> <pre><code> protected string FindAndTranslateIn(string content) { return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase); } public string TranslateHandler(Match m) { if (m.Success) { string key = m.Groups[1].Value; key = FindAndTranslateIn(key); string def = string.Empty; if (m.Groups.Count &gt; 2) { def = m.Groups[2].Value; if(def.Length &gt; 1) { def = FindAndTranslateIn(def); } } if (group == null) { return Translate(key, def); } else { return Translate(key, group, def); } } return string.Empty; } </code></pre> <p>From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs.</p> <p>This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.</p>
<p>If you do a Regex.Match, the resulting match objects group at the 0th index, is the subset of the intput that matched the regex.</p> <p>you can use this to stitch in the bold tags and encode it there.</p>
6,892
<p>Has anyone found a good compression format for MS Sqlserver databases? If so, what do you use and are you pleased with how it performs? </p> <p>My company frequently will compress a database snapshot from one of our clients and download it so we have a local copy for testing and dev purposes. We tried zip in the past, but once the database files crossed the 4Gb boundary we had to use rar (zip is 32-bit only). The problem is rar takes a lot of time to compress, and we don't know if it gives us the best compression ratio either.</p> <p>This isn't a question about the compression utility so much as the compression format. We use WinRar, but are considering 7zip, which supports a number of formats.</p>
<p>In sql 2008 you have native compression, if you have to do this a lot and don't have SQL server 2008 then take a look at something like <a href="http://www.quest.com/litespeed-for-sql-server/" rel="nofollow noreferrer">Quest LiteSpeed</a> which compreeses the backup automatically</p>
<p>In the no-cost category, newer versions of <a href="http://www.gzip.org/#faq10" rel="nofollow noreferrer">gzip</a> and <a href="http://www.bzip.org/" rel="nofollow noreferrer">bzip2</a> are supposed to include large file support (someone on the internet tells me that bzip2 1.0.1 and beyond is large file compatible thanks to Cyril Pilsko, while gzip 1.2 can be patched which the dowloadable binaries are, and the gzip 1.3 beta includes support). While I use 7zip on my windows pc for convenience, I tend to prefer bzip2 for speed vs compression.</p> <p>I have also heard of tricking the non-large-file versions by doing something like <code>cat file | gzip &gt; file.gz</code>. Generally you're trading off time with compression level, but one of bzip2's claims is that it uncompresses very quickly, which in a disaster recovery situation should be your most important metric. In that regard, I believe EMC's tape backup solution (ELM?) used to skip compression on DB partitions by default. Also If you're really serious about packing it into a tiny space, you might try something like <a href="http://rzip.samba.org/" rel="nofollow noreferrer">rzip</a>, but I've never known anyone to actually use it.</p>
4,334
<p>We've just started using LINQ to SQL at work for our DAL &amp; we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results?</p> <p>We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a <a href="https://stackoverflow.com/questions/tagged/subjective">subjective</a> question, but I still think the info would be valuable.</p> <p><strong>EDIT:</strong> To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.</p>
<p>My <a href="http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/" rel="noreferrer">LINQ query result cache</a> is probably just what you're looking for.</p> <pre><code>var q = from c in context.Customers where c.City == "London" select new { c.Name, c.Phone }; var result = q.Take(10).FromCache(); </code></pre> <p>Pete.</p>
<p>See the 'GetReferenceData' method in the 'ReferenceData' class in <a href="http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq/" rel="nofollow noreferrer">this article</a>: <a href="http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq/" rel="nofollow noreferrer">http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq/</a></p> <p>It uses the asp.net page cache for caching data retrieved using L2S.</p>
5,802
<p>I recently upgraded to Subversion 1.5, and now I cannot commit my code to the repository. I get an error message: "403 Forbidden in response to MKACTIVITY". I know the upgrade worked because my fellow developers are not getting this issue. What's going on?</p>
<p>Answering my own question:</p> <p>Apparently my SVN URL had the wrong case! A Google search turned up an article (no longer available online) that explained what was going on. My URL was of the form <a href="http://svn.foobar.com/foobar" rel="noreferrer">http://svn.foobar.com/foobar</a> but the actual repository was called <a href="http://svn.foobar.com/fooBar" rel="noreferrer">http://svn.foobar.com/fooBar</a>.</p> <p>I use TortoiseSVN, so the fix was to use the Relocate command to correct the path to the repository.</p> <p>Hopefully this will help someone else.</p>
<p>I think the thing here is that Subversion (regardless of OS platform its server is installed on) <strong>is</strong> case sensitive.</p> <p>However, clients' OS maybe not. And that might create a problem. </p> <p>In my company I have had this case and it took me about an hour to figure it out. So, one developer, who was working on mac, committed to svn file with the same name, but he changed couple of letters in its name to capital ones. For mac and subversion it is not a problem and file got in.</p> <p>Later another developer, who happened to work on windows laptop got an error and windows got completely confused and could not do anything.</p> <p>so, the solution was - I asked developers, which of two files I can delete. I did it on linux and everybody happy ever since.</p> <p>so, upper/low case spelling is not a subversion problem, but windows OS one.</p>
8,132
<p>I need to determine when my Qt 4.4.1 application receives focus.</p> <p>I have come up with 2 possible solutions, but they both don’t work exactly as I would like.</p> <p>In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below. </p> <p>In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’.</p> <p>In both of these solutions, the code is executed at times when I don’t want it to be.</p> <p>For example, I have this code that overrides the focusInEvent() routine:</p> <pre><code>void ApplicationWindow::focusInEvent( QFocusEvent* p_event ) { Qt::FocusReason reason = p_event-&gt;reason(); if( reason == Qt::ActiveWindowFocusReason &amp;&amp; hasNewUpstreamData() ) { switch( QMessageBox::warning( this, "New Upstream Data Found!", "New upstream data exists!\n" "Do you want to refresh this simulation?", "&amp;Yes", "&amp;No", 0, 0, 1 ) ) { case 0: // Yes refreshSimulation(); break; case 1: // No break; } } } </code></pre> <p>When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen.</p> <p>Likewise, if the user is using the application opening &amp; closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows &amp; dialogs, though it does happen at least for the one shown in the sample code.</p> <p>I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows.</p> <p>Is this possible? How can this be done?</p> <p>Thanks for any information, since this is very important for our application to do.</p> <p>Raymond.</p>
<p>I think you need to track the <a href="http://doc.qt.io/qt-4.8/qevent.html#Type-enum" rel="nofollow noreferrer">QEvent::ApplicationActivate</a> event.</p> <p>You can put an <a href="http://doc.qt.io/qt-4.8/qobject.html#eventFilter" rel="nofollow noreferrer">event filter</a> on your QApplication instance and then look for it.</p> <pre><code>bool ApplicationWindow::eventFilter( QObject * watched, QEvent * event ) { if ( watched != qApp ) goto finished; if ( event-&gt;type() != QEvent::ApplicationActivate ) goto finished; // Invariant: we are now looking at an application activate event for // the application object if ( !hasNewUpstreamData() ) goto finished; QMessageBox::StandardButton response = QMessageBox::warning( this, "New Upstream Data Found!", "New upstream data exists!\n" "Do you want to refresh this simulation?", QMessageBox::Yes | QMessageBox::No) ); if ( response == QMessageBox::Yes ) refreshSimulation(); finished: return &lt;The-Superclass-here&gt;::eventFilter( watched, event ); } ApplicationWindow::ApplicationWindow(...) { if (qApp) qApp-&gt;installEventFilter( this ); ... } </code></pre>
<p>Looking at the Qt docs it seems that focus events are created each time a widget gets the focus, so the sample code you posted won't work for the reasons you stated. </p> <p>I am guessing that QApplication::focusedChanged does not work the way you want because some widgets don't accept keyboard events so also return null as the "old" widget even when changing focus within the same app.</p> <p>I am wondering whether you can do anything with QApplication::activeWindow()</p> <blockquote> <p>Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. Note that there might be an activeWindow() even if there is no focusWidget(), for example if no widget in that window accepts key events.</p> </blockquote>
8,813
<p>I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.</p> <p>The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.</p> <p>This is the cron job:</p> <pre><code>PATH=/usr/bin 10 3 * * * ruby /home/deploy/bin/datadump.rb </code></pre> <p>This is datadump.rb:</p> <pre><code>#!/usr/bin/ruby require 'yaml' require 'logger' require 'rubygems' require 'net/ssh' require 'net/sftp' APP = '/home/deploy/apps/myapp/current' LOGFILE = '/home/deploy/log/data.log' TIMESTAMP = '%Y%m%d-%H%M' TABLES = 'table1 table2' log = Logger.new(LOGFILE, 5, 10 * 1024) dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz" ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml')) config = YAML::load(open(APP + '/config/database.yml'))['production'] cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 &gt; #{dump}" log.info 'Getting ready to create a backup' `#{cmd}` # Strongspace log.info 'Backup created, starting the transfer to Strongspace' Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh| ssh.sftp.connect do |sftp| sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle| sftp.write(handle, open("#{dump}").read) end end end log.info 'Finished transferring backup to Strongspace' log.info 'Removing local file' cmd = "rm -f #{dump}" log.debug "Executing: #{cmd}" `#{cmd}` log.info 'Local file removed' </code></pre> <p>I've checked and double-checked all the paths and they're correct. Both <strong>sftp.yml</strong> (SFTP credentials) and <strong>database.yml</strong> (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.</p> <p>What could be causing the cron job to fail?</p>
<p>Are you sure the temporary file is being created correctly when running as a cron job? The working directory for your script will either be specified in the HOME environment variable, or the /etc/passwd entry for the user that installed the cron job. If deploy does not have write permissions for the directory in which it is executing, then you could specify an absolute path for the dump file to fix the problem.</p>
<p>Is cron sending emails with logs?</p> <p>If not, pipe the output of cron to a log file.</p> <p>Make sure to redirect STDERR to the log.</p>
3,419
<p>I have a small diagnostic VB.Net application ( 2 forms, 20 subs &amp; functions) written using VB.Net 2008 that targets Framework 2.0 and higher, but now I realize I need to support Framework 1.1. I'm looking for the most efficient way to accomplish this given these constraints:</p> <ul> <li>I don't know which parts of the application are 2.0-specific. </li> <li>I could reconstruct the forms without too much trouble. </li> <li>I need to support SharpZipLib</li> </ul> <p>My current idea is to find and install VB.Net 2003, copy over my code and iteratively re-create the tool. Are there better options?</p>
<p>Your app sounds small enough that I would create a fresh project/solution in a separate folder for the 1.1 framework, copy over the necessary files, use the "Add Existing Item" option, and then build. All the problems will bubble up to the surface that way.</p> <p>A rather "ugly" approach, but it'll show you everything you need to fix up front.</p>
<p>Probably not. If you don't understand which bits are 2.0-specific, you're probably going to have to go the trial-and-error route. However, you can probably save yourself quite a bit of work if you go looking for generics beforehand. In my experience, those are the most numerous 1.1-incompatible bits that tend to make it into my code.</p>
8,956
<p>I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?</p>
<p>In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:</p> <pre><code>static string Truncate(string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) &lt;= maxLength) return s; var cs = s.ToCharArray(); int length = 0; int i = 0; while (i &lt; cs.Length){ int charSize = 1; if (i &lt; (cs.Length - 1) &amp;&amp; char.IsSurrogate(cs[i])) charSize = 2; int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) &lt;= maxLength){ i = i + charSize; length += byteSize; } else break; } return s.Substring(0, i); } </code></pre> <p>The returned string can then be safely transferred to a byte array of length maxLength.</p>
<p>Efficient way would be finding how much (pessimistically) bytes you will need per character with</p> <pre><code>Encoding.GetMaxByteCount(1); </code></pre> <p>then dividing your string size by the result, then converting that much characters with</p> <pre><code>public virtual int Encoding.GetBytes ( string s, int charIndex, int charCount, byte[] bytes, int byteIndex ) </code></pre> <p>If you want to use less memory use</p> <pre><code>Encoding.GetByteCount(string); </code></pre> <p>but that is a much slower method.</p>
5,461
<p>Are there any open source algorithms in c# that solve the problem of creating a difference between two text files?</p> <p>It would be super cool if it had some way of highlighting what exact areas where changed in the text document also.</p>
<p>There is <a href="http://www.menees.com/Diff.Net.htm" rel="nofollow noreferrer">Menees Diff</a> which will provide you with a C# diff implementation. The source code is included. I've used it in the past with good success wrapping it in my own implemenation.</p>
<p>Check out <a href="http://en.wikipedia.org/wiki/Diff" rel="noreferrer">diff</a>. Here it is <a href="http://www.gnu.org/software/diffutils/diffutils.html" rel="noreferrer">in the gnu project</a> (open source, of course), and many more links to implementations are found in the wikipedia article. A comparison of different such programs is found <a href="http://en.wikipedia.org/wiki/Comparison_of_file_comparison_tools" rel="noreferrer">here</a>.</p>
9,096
<p>I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.</p> <p>I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.</p> <p>I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?</p> <ul> <li><p>How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.</p></li> <li><p>Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?</p></li> </ul> <p>What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:</p> <pre><code>&lt;com|org|...&gt;.&lt;company&gt;.&lt;app&gt;.&lt;layer&gt;.&lt;function&gt;.ClassName </code></pre> <p>I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.</p>
<p>First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review.</p> <p>If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.</p> <p>In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having <i>any</i> standard is the key.</p>
<p>It obviously varies depending on languages and technologies. By the look of your example name space I am going to guess java, in which case <a href="http://java.sun.com/docs/codeconv/" rel="nofollow noreferrer">http://java.sun.com/docs/codeconv/</a> is a really good place to start. You might also want to look at something like maven's standard directory structure which will make all your projects look similar. </p>
6,991
<p>I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:</p> <blockquote> <p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan) </p> <hr> <p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles) </p> </blockquote> <p>The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.</p> <p>I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing?</p>
<p>You can use this:</p> <pre><code>super if defined?(super) </code></pre> <p>Here is an example:</p> <pre><code>class A end class B &lt; A def t super if defined?(super) puts "Hi from B" end end B.new.t </code></pre>
<p>Rather than checking if the super method exists, you can just define it</p> <pre><code>class ActiveRecord::Base def after_initialize end end </code></pre> <p>This works in my testing, and shouldn't break any of your existing code, because all your other classes which define it will just be silently overriding this method anyway</p>
3,197
<p>This site may attract questions such as</p> <ul> <li><p>Is it legal to sell 3D printed objects from a model repository?</p></li> <li><p>Are 3D printed guns legal in my jurisdiction?</p></li> <li><p>If my custom-built printer sets my house on fire, does the insurance cover it?</p></li> </ul> <p>Are such questions allowed on this site, or should they be redirected to a site dealing more commonly with laws?</p>
<p><strong>Yes - in some cases.</strong></p> <p>First, overlap between sites is fine. <em>It doesn't matter if a question is on topic somewhere else</em>; that's no reason to eliminate it from a different site's scope. There were some issues when HSM sprang up, because Mathematics, Physics, and other sites allowed history-related questions. I participated in several meta discussions on these sites. While Physics eventually decided to not allow history questions, Mathematics and other sites continued to allow them. So we should not make our decision based on Law.</p> <p>I do agree that, so far, the <a href="https://3dprinting.stackexchange.com/questions/tagged/legal" class="post-tag" title="show questions tagged &#39;legal&#39;" rel="tag">legal</a> questions have not been great. But in the future, they could be. I wrote in <a href="https://3dprinting.stackexchange.com/questions/103/is-it-legal-to-make-a-weapon-with-a-3d-printer#comment123_1030">a comment</a></p> <blockquote> <p>I agree with @TomvanderZanden; a good case could be made for keeping this here. Laws and regulations can be a huge influence on an industry; the allowance or ban of certain products of said industry would seem to be relevant here. Remember, questions can be on-topic on multiple sites.</p> </blockquote> <p>Regulatory measures can be extraordinarily important in a industry. If we had a site about making socks, should questions about whether or not is is legal to make socks with material X in the United States be off topic? I would argue no; this could be an important part of sock-making.</p> <p>We have the same situation here. Some <a href="https://3dprinting.stackexchange.com/questions/tagged/legal" class="post-tag" title="show questions tagged &#39;legal&#39;" rel="tag">legal</a> questions can be important; I would argue that questions regarding which materials and devices are legal should be ones we aim for. The legality of Filament A could be really important to a project.</p> <p>That's not to say that all <a href="https://3dprinting.stackexchange.com/questions/tagged/legal" class="post-tag" title="show questions tagged &#39;legal&#39;" rel="tag">legal</a> questions are fine. As has been said, some of the ones we've had so far haven't been great, and I would advocate sending them to Law. But I strongly disagree that just because of the examples we've seen we should not allow <a href="https://3dprinting.stackexchange.com/questions/tagged/legal" class="post-tag" title="show questions tagged &#39;legal&#39;" rel="tag">legal</a> questions. There are good ones out there; we haven't seen their full extent yet.</p>
<p>No, such questions should not be allowed. This site deals only with the practical issues of 3D printing. Questions about legal issues should be redirected to sites dealing specifically with those, since users of this site do not have the expertise to address legal issues. A 3D printing expert does not make a legal expert.</p>
10
<p>All the articles I've found via google are either obsolete or contradict one another.</p> <p>What's the easiest way to print a form or, say, a richtextbox in c#? I think it's using the <code>PrintDiaglog</code> class by setting the <code>Document</code>, but how does this get converted?</p>
<p>At least in VS 2008, its very easy. It took me about a couple of minutes to code the answer after reading your question. Here's where I borrowed it from:</p> <p><a href="http://msdn.microsoft.com/en-us/library/6he9hz8c.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/6he9hz8c.aspx</a></p> <p>I tested this, and it works.</p>
<p>Someone I know created a component that extends controls with a lot of properties that give you a lot of control over how the form prints. It's worth a look.</p> <p><a href="http://www.xtremevbtalk.com/showthread.php?t=279707" rel="nofollow noreferrer">MCL PrintForm Helper Component</a></p>
2,726
<p>I've done calibration test with "Concentric circle test" (<a href="https://www.thingiverse.com/thing:11895" rel="nofollow noreferrer">https://www.thingiverse.com/thing:11895</a>) and at specific points there are little bumped points on the print. Also Thingiverse page of the test mentions about these.</p> <p>How can I solve this problem?</p> <p>My printer is Creality Ender 3 Pro, I use Esun PLA+ with 210 celcius extruder and 60 celcius bed temperature.</p> <p>Here is the printed object, both are same print, just took photo on different base.</p> <p><a href="https://i.stack.imgur.com/53vd2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/53vd2.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/eqnA7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eqnA7.jpg" alt="enter image description here"></a></p>
<p>The 5V is derived from the 12V supply by a linear regulator (L7805CD, DPAK package with 100 C/W thermal resistance). The maximum you can draw from it (without overheating the regulator) is around 200mA. Considering the electronics on the board are already using some power, the maximum would be around a 150mA fan but this would have the regulator running near its maximum limits.</p>
<p>5 V and 3.3 V are both <a href="https://learn.sparkfun.com/tutorials/logic-levels/33-v-cmos-logic-levels" rel="nofollow noreferrer">logic "highs"</a> in computing and measured against GND. If the fan simply has to know the on stance and nothing more, then you could run a fan with the logic 5 V (and probably 3.3 V for about 50% spin speed).</p>
1,380
<p>I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?</p>
<p>Here is a code snippet that should help get the job done for you. You may need to do some additional validation to avoid any exceptions (ensuring the profile actually exists, ensuring the image URL actually exists, etc...):</p> <pre><code> //get current profile manager UserProfileManager objUserProfileManager = new UserProfileManager(PortalContext.Current); //get current users profile UserProfile profile = objUserProfileManager.GetUserProfile(true); //get user image URL string imageUrl = (string)profile[PropertyConstants.PictureUrl]; //do something here with imageUrl </code></pre>
<p>Ah, You have to use the UserProfileManager class. More information here: <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx</a></p> <p>Example use:</p> <pre><code>public override void ItemAdded(SPItemEventProperties properties) { // Get list item on which the event occurred. SPListItem item = properties.ListItem; // Set the Author Image field to the user's PictureURL if it exists. using (SPWeb web = properties.OpenWeb()) { // Author: {C32DB804-FF2D-4656-A38A-B0394BA5C931} SPFieldUserValue authorValue = new SPFieldUserValue(properties.OpenWeb(), item[new Guid("{C32DB804-FF2D-4656-A38A-B0394BA5C931}")].ToString()); UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(web.Site)); UserProfile profile = profileManager.GetUserProfile(authorValue.LookupId); UserProfileValueCollection values = profile[PropertyConstants.PictureUrl]; if (values.Count &gt; 0) { // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F} SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString()); item[new Guid("{37A5CA4C-7621-44d7-BF3B-583F742CE52F}")] = urlValue.Url; } } item.Update(); // News Text: {7F55A8F0-4555-46BC-B24C-222240B862AF} // // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F} // // Publish Date: {45E84B8B-E161-46C6-AD51-27A42E4992B5} // } </code></pre>
8,649
<p>Have you ever seen any of there error messages?</p> <blockquote> <p>-- SQL Server 2000</p> <p>Could not allocate ancillary table for view or function resolution.<br /> The maximum number of tables in a query (256) was exceeded.</p> <p>-- SQL Server 2005</p> <p>Too many table names in the query. The maximum allowable is 256.</p> </blockquote> <p>If yes, what have you done?</p> <p>Given up? Convinced the customer to simplify their demands? Denormalized the database?</p> <hr /> <p>@(everyone wanting me to post the query):</p> <ol> <li>I'm not sure if I can paste 70 kilobytes of code in the answer editing window.</li> <li>Even if I can this this won't help since this 70 kilobytes of code will reference 20 or 30 views that I would also have to post since otherwise the code will be meaningless.</li> </ol> <p>I don't want to sound like I am boasting here but the problem is not in the queries. The queries are optimal (or at least almost optimal). I have spent countless hours optimizing them, looking for every single column and every single table that can be removed. Imagine a report that has 200 or 300 columns that has to be filled with a single SELECT statement (because that's how it was designed a few years ago when it was still a small report).</p>
<p>For SQL Server 2005, I'd recommend using table variables and partially building the data as you go. </p> <p>To do this, create a table variable that represents your final result set you want to send to the user.</p> <p>Then find your primary table (say the orders table in your example above) and pull that data, plus a bit of supplementary data that is only say one join away (customer name, product name). You can do a SELECT INTO to put this straight into your table variable.</p> <p>From there, iterate through the table and for each row, do a bunch of small SELECT queries that retrieves all the supplemental data you need for your result set. Insert these into each column as you go.</p> <p>Once complete, you can then do a simple SELECT * from your table variable and return this result set to the user.</p> <p>I don't have any hard numbers for this, but there have been three distinct instances that I have worked on to date where doing these smaller queries has actually worked faster than doing one massive select query with a bunch of joins.</p>
<p>I'd like to see that query, but I imagine it's some problem with some sort of iterator, and while I can't think of any situations where its possible, I bet it's from a bad while/case/cursor or a ton of poorly implemented views.</p>
2,453
<p>When I try to print a Unicode string in a Windows console, I get an error .</p> <p><code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code></p> <p>I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p> <p><strong>Edit:</strong> I'm using Python 2.5.</p> <hr /> <p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p> <p><a href="https://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
<p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p> <hr> <p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p> <p><a href="http://wiki.python.org/moin/PrintFails" rel="noreferrer">PrintFails - Python Wiki</a></p> <p>Here's a code excerpt from that page:</p> <pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 &lt;type 'unicode'&gt; 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None &lt;type 'unicode'&gt; 2 Б Б </code></pre> <p>There's some more information on that page, well worth a read.</p>
<p>James Sulak asked,</p> <blockquote> <p>Is there any way I can make Python automatically print a ? instead of failing in this situation?</p> </blockquote> <p>Other solutions recommend we attempt to modify the Windows environment or replace Python's <code>print()</code> function. The answer below comes closer to fulfilling Sulak's request.</p> <p>Under Windows 7, Python 3.5 can be made to print Unicode without throwing a <code>UnicodeEncodeError</code> as follows:</p> <p>&nbsp; &nbsp; In place of: &nbsp; &nbsp;<code>print(text)</code><br> &nbsp; &nbsp; substitute: &nbsp; &nbsp; <code>print(str(text).encode('utf-8'))</code></p> <p>Instead of throwing an exception, Python now displays unprintable Unicode characters as <em>\xNN</em> hex codes, e.g.:</p> <p>&nbsp; <em>Halmalo n\xe2\x80\x99\xc3\xa9tait plus qu\xe2\x80\x99un point noir</em></p> <p>Instead of</p> <p>&nbsp; <em>Halmalo n’était plus qu’un point noir</em></p> <p>Granted, the latter is preferable <em>ceteris paribus</em>, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.</p> <p><strong>Note:</strong> The <code>str()</code> call above is needed because otherwise <code>encode()</code> causes Python to reject a Unicode character as a tuple of numbers.</p>
2,732
<p>I'm developing a compiler framework for .NET and want a flexible way of defining pipelines. I've considered the following options:</p> <ul> <li>WWF</li> <li>Custom XML pipeline description</li> <li>Custom pipeline description in code (using Nemerle's macros to define syntax for it)</li> <li>Other code-based description</li> </ul> <p>Requirements:</p> <ul> <li>Must not depend on functionality only in the later versions of .NET (3+) since it's intended to be cross-platform and be used on top of managed kernels, meaning semi-limited .NET functionality.</li> <li>Must allow conditional pipeline building, so you can specify that certain command line options will correspond to certain elements and orders.</li> </ul> <p>WWF would be nice, but doesn't meet the first requirement. The others would work but are less than optimal due to the work involved.</p> <p>Does anyone know of a solution that will meet these goals with little to no modification?</p>
<p>If you know Ruby then a solution is to write a simple internal DSL that can generate whatever pipeline data types and reader/writer code you need. Generating XML is a quick way to get started. You can always change the DSL to generate another format later if required.</p> <p>You may also want to look at the <a href="http://en.wikipedia.org/wiki/Phoenix_(compiler_framework)" rel="nofollow noreferrer">Microsoft Phoenix compiler</a> project for inspiration.</p>
<p>I know <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">Boo</a> let you have fun with the compiler, not sure if it does in the manner you want.</p>
8,746
<p>I was wondering if anybody knew of a method to configure apache to fall back to returning a static HTML page, should it (Apache) be able to determine that PHP has died? This would provide the developer with a elegant solution to displaying an error page and not (worst case scenario) the source code of the PHP page that should have been executed.</p> <p>Thanks.</p>
<p>The PHP source code is only displayed when apache is not configured correctly to handle php files. That is, when a proper handler has not been defined. </p> <p>On errors, what is shown can be configured on php.ini, mainly the display_errors variable. That should be set to off and log_errors to on on a production environment.</p> <p>If php actually dies, apache will return the appropriate HTTP status code (usually 500) with the page defined by the ErrorDocument directive. If it didn't die, but got stuck in a loop, there is not much you can do as far as I know.</p> <p>You can specify a different page for different error codes.</p>
<p>There are 2 ways to use PHP and Apache.</p> <pre><code>1. Install PHP as an Apache module: this way the PHP execution is a thread inside the apache process. So if PHP execution fails, then Apache process fails too. there is no fallback strategy. 2. Install PHP as a CGI script handler: this way Apache will start a new PHP process for each request. If the PHP execution fails, then Apache will know that, and there might be a way to handle the error. </code></pre> <p>regardless of the way you install PHP, when PHP execution fails you can handle errors in the <code>php.ini</code> file.</p>
8,734
<p>An OleDB provider is a binary implementing COM interfaces provided by Microsoft. From that it seems to be possible to create a provider using C#. Is that correct? Is there a sample demonstrating that? If not, would you discourage me from doing that? I see that there are multiple unmanaged samples but I can't find any managed.</p>
<p>The article is good, but doesn't actually answer the question. OLEDB is a set of COM interfaces that could in fact be implemented in .Net via COM Interop though I've never heard of such an implementation and probably isn't advisable.</p> <p>The set of OLEDB interfaces are documented by Microsoft <a href="http://msdn.microsoft.com/en-us/library/ms709709%28v=VS.85%29.aspx" rel="nofollow">here</a>. OLEDB is a complicated topic and not all interfaces are required to implement a functional provider. To make things worse, different OLEDB clients have the set of interfaces they require to be able to use the provider. For example, here is a <a href="http://msdn.microsoft.com/en-us/library/cwctxe7a%28v=vs.71%29.aspx" rel="nofollow">list of require interfaces</a> that must be implemented to use a provider from the .Net OLEDB client (System.Data.OleDb.*). Note: I didn't find such a link for the 2.0 Framework or later. Finally it's worth noting that it was so difficult to implement providers Microsoft later provided a set of ATL templates (C++) to help implementers do it correctly.</p> <p>To learn more about OLEDB I'd definitely recommend looking at the <a href="http://msdn.microsoft.com/en-us/library/aa968814%28v=VS.85%29.aspx" rel="nofollow">Windows Data Access SDK</a> on MSDN.</p>
<p>I am not sure I really understand your question?! There already <em>is</em> a managed OleDBProvider?!</p> <pre><code>using System.Data.OleDb; </code></pre> <p>I would certainly discourage writing a provider that exists and works absolutely fine! :)</p> <p>But in answer to your first question, you can of course create your own. The <a href="http://support.microsoft.com/kb/313480" rel="nofollow noreferrer">Data Provider Roadmap</a> may be a good place to start for an overview and links to samples etc.</p>
7,683
<p>I'm supposed to learn how to use <a href="http://www.ni.com/labview/" rel="nofollow noreferrer">LabVIEW</a> for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites.</p> <p>I'm a senior developer with lots of Java/C#/C++ experience.</p> <p>I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.</p>
<p><strong>It will take some <em>training</em> and some <em>time</em> to learn the style needed to develop maintainable code</strong>.</p> <p>Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls.</p> <p>For the basics, National Instruments offers <a href="http://www.ni.com/training/" rel="nofollow noreferrer">training courses</a>. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification.</p> <p>Get an <a href="http://www.ni.com/labview/try/daq.htm" rel="nofollow noreferrer">evaluation copy</a> of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly.</p> <p>LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function. </p> <p>The official NI support forums and knowledgebase are probably the best resources out there at the moment.</p> <p>Unofficial sites like <a href="http://www.cipce.rpi.edu/programs/remote_experiment/labview/" rel="nofollow noreferrer">Tutorials in G</a> have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck.</p> <p><strong>Edit:</strong> <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/2241" rel="nofollow noreferrer">Basics I/II</a> are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/12769" rel="nofollow noreferrer">Intermediate I/II</a>. NI has the course outlines available on their website as well, so you know what you're going to cover in each.</p>
<p>When I started with LabVIEW a few years ago I was given a link to the <a href="http://cnx.rice.edu/content/col10241/latest/" rel="nofollow noreferrer">LabVIEW Graphical Programming Course</a>. It covers the basics and having a sound knowledge of other programming languages I think helped me pick things up quickly.</p>
6,912
<p>The <a href="http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog" rel="nofollow noreferrer">demos</a> for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. </p> <p>Here is the js file:</p> <pre><code>topMenu = { init: function(){ $("#my_button").bind("click", function(){ $("#SERVICE03_DLG").dialog("open"); $("#something").focus(); }); $("#SERVICE03_DLG").dialog({ autoOpen: false, modal: true, resizable: false, title: "my title", overlay: { opacity: 0.5, background: "black" }, buttons: { "OK": function() { alert("hi!"); }, "cancel": function() { $(this).dialog("close"); } }, close: function(){ $("#something").val(""); } }); } } $(document).ready(topMenu.init); </code></pre> <p>Here is the html that uses the flora theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="flora/flora.all.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="flora"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the html that uses the downloaded themeroller theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="ui-dialog"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As you can see, only the referenced css file and class names are different. Anybody have a clue as to what could be wrong?</p> <p>@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:</p> <pre class="lang-none prettyprint-override"><code>style="z-index:5000" </code></pre> <p>and I've also tried it referencing an external css file:</p> <pre class="lang-none prettyprint-override"><code>#SERVICE03_DLG{z-index:5000;} </code></pre> <p>But neither of these work. Am I missing something in what you suggested?</p> <p><strong>Edit:</strong><br> Solve by brostbeef!<br> Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.</p>
<p>I think it is because you have the classes different.<br/> <code>&lt;div id="SERVICE03_DLG" class="flora"&gt;</code> (flora)<br/> <code>&lt;div id="SERVICE03_DLG" class="ui-dialog"&gt;</code> (custom)</p> <p>Even with the flora theme, you would still use the ui-dialog class to define it as a dialog.</p> <p>I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you.</p> <p>Try getting rid of the class attribute or using the "ui-dialog" class.</p>
<p>Man, this is a good one. I've tried doing a bunch of things on these two pages. Have you tried just leaving the CSS out altogether and trying both pages then? I used Firebug to remove the CSS from the header on both pages, and the input still worked on one and not on the other - but, I'm inclined to believe that Firebug doesn't completely remove the CSS from the rendering, and you'll get different results if you actually remove it from the code.</p> <p>I also found that you can paste text into the text box using the mouse - it just won't accept keyboard input. There doesn't seem to be any event handler on it that would interfere with this, though.</p>
6,752
<p>When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.</p> <p>Is there a way, in HTTP headers or equivalents, to change this behaviour?</p>
<pre><code>&lt;input autocomplete="off"&gt; </code></pre>
<p>I wonder, if you set the page not to be cached through meta tags, will that fix the problem? <a href="http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html" rel="nofollow noreferrer">http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html</a> If it does, it'll have the benefit of working on browser's with Javascript disabled.</p>
7,546
<p>What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? </p> <p>Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart?</p> <p>Note: For the purpose of this question ignore 'simple' design patterns like <em>Singleton</em>. I'm talking about designing your code so you can take advantage of <em>Model View Controller</em>, etc.</p>
<p>Any large program that is well written will use design patterns, even if they aren't named or recognized as such. That's what design patterns are, designs that repeatedly and <em>naturally</em> occur. If you're interfacing with an ugly API, you'll likely find yourself implementing a <code>Facade</code> to clean it up. If you've got messaging between components that you need to decouple, you may find yourself using <code>Observer</code>. If you've got several interchangeable algorithms, you might end up using <code>Strategy</code>.</p> <p>It's worth knowing the design patterns because you're more likely to recognize them and then converge on a clean solution more quickly. However, even if you don't know them at all, you'll end up creating them eventually (if you are a decent programmer).</p> <p>And of course, if you are using a modern language, you'll probably be forced to use them for some things, because they're baked into the standard libraries.</p>
<p>I absolutely use design patterns. At this point I take MVC for granted as a design pattern. My primary reason for using them is that I am humble enough to know that I am likely not the first person to encounter a particular problem. I rarely start a piece of code knowing which pattern I am going to use; I constantly watch the code to see if it naturally develops into an existing pattern. </p> <p>I am also very fond of <a href="http://martinfowler.com/" rel="nofollow noreferrer">Martin Fowler's</a> <a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="nofollow noreferrer" rel="nofollow noreferrer">Patterns of Enterprise Application Architecture</a>. When a problem or task presents itself, I flip to related section (it's mostly a reference book) and read a few overviews of the patterns. Once I have a better idea of the general problem and the existing solutions, I begin to see the long term path my code will likely take via the experience of others. I end up making much better decisions.</p> <p>Design patterns definitely play a big role in all of my "for the future" ideas. </p>
3,268
<p>How do I use Perl to create graphs?</p> <p>I'm running scheduled job that creates text reports. I'd like to move this to the next step (for the management) and also create some graphs that go along with this. Is this possible / feasible? It'd be great if I could do this using Office some how.</p> <h2>update: solutions i'm going to investigate in this order</h2> <ul> <li>Spreadsheet::WriteExcel (this seems to now have changed from the last time i investigated this .... wait, this was suggested by the author of the module. cool.)</li> <li>GD Graph - this is now available for ActivePerl(wasn't last time i looked)</li> <li>SVG</li> <li>Open Charts look interesting.</li> <li>Chartdirector</li> </ul>
<p>GD and GD::Graph are probably your best bets, you can use them to create images that you can then embed into whatever you need.</p>
<p><a href="http://search.cpan.org/dist/Spreadsheet-WriteExcel" rel="nofollow noreferrer">Spreadsheet::WriteExcel</a> will let you just get the data into Excel, then write Excel equations for the graphs.</p>
9,009
<p>Working on implementing TFS throughout our organization. It is easy to integrate with <code>.NET</code> projects and any platform that uses Eclipse or a derivative of Eclipse for editing.<br> What's the best way to use TFS version control with Xcode (now that I find out we need to write some iPhone apps)?</p>
<p>Xcode integration is something that we at <a href="http://www.teamprise.com" rel="noreferrer">Teamprise</a> have been looking into a lot. One of the main problems for us is that Apple does not provide a version control API that we can hook into to add a new version control system to Xcode - for integrated version control it is either the systems that Apple provide access to or nothing at the moment.</p> <p>That said, we do have a number of customers who develop in Xcode for TFS. They either use <a href="http://www.teamprise.com/products/explorer/" rel="noreferrer">Teamprise Explorer</a> (which is a standalone GUI client to TFS compiled as a Universal Binary) or they have macros inside Xcode that perform basic check-out and get operations in-conjunction with the <a href="http://www.teamprise.com/products/clc/" rel="noreferrer">TFS command line (tf)</a>. It's obviously not the ideal experience but acceptable for them. The stand-alone GUI has the advantage that you can do all the work item tracking stuff there as well and integrate this with your check-ins.</p> <p>Sorry if this is a very "marketing" type answer - just trying to let you know what our current customers do with Xcode. If you want more details around the macro approach then let me know.</p> <p>Hope that helps,</p> <p>Martin.</p>
<p>The biggest problem with this is that Xcode only runs on OS X and TFS client tools only run on Windows. If you're host operating system in OS X and you have a Windows virtual environment running locally (like Parallels or VMFusion) then you could use Team Explorer or the command-line tools to work with the repository.</p> <p>But this is a lot of work just to use a really dated version control system. If you don't have to use TFS I would probably use SVN or something else with native OS X support.</p>
9,567
<p>I use a MacBook, but I've got a usual keyboard attached to it.</p> <p>The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS. The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys.</p> <p>So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this?</p> <p>(I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models)</p> <p>Update: Thanks for the responses, I fixed this.</p> <p>To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems</p> <p>The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys, ...). I didn't try it yet, as the commands keys were my biggest gripe.</p>
<p>In OS X 10.5 they allow you to have different keyboard setups for different keyboards. This works most of the time. I've had issues with very old keyboards that are plugged in via a PS2 to USB but otherwise it works fine.</p>
<p>You could investigate DoubleCommand, it may do what you need.</p> <p>There's an experimental version that allows for different properties for different keyboards.</p>
8,050
<p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p> <pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; </code></pre> <p>Later on however the memory is freed using a <code>delete</code> call:</p> <pre class="lang-cpp prettyprint-override"><code>delete pStruct; </code></pre> <p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>
<p>Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.</p> <p>More importantly if <code>STRUCT</code> where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.</p> <p>Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:</p> <pre><code>delete [] (BYTE*) pStruct; </code></pre>
<p>Rob Walker <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163">reply</a> is good.</p> <p>Just small addition, if you don't have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.</p>
9,883
<p>If I create an HTTP <code>java.net.URL</code> and then call <code>openConnection()</code> on it, does it necessarily imply that an HTTP post is going to happen? I know that <code>openStream()</code> implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?</p>
<p>If you retrieve the <code>URLConnection</code> object using <code>openConnection()</code> it doesn't actually start communicating with the server. That doesn't happen until you get the stream from the <code>URLConnection()</code>. When you first get the connection you can add/change headers and other connection properties before actually opening it.</p> <p>URLConnection's life cycle is a bit odd. It doesn't send the headers to the server until you've gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you'll be writing data to it (You may need to call <code>setDoOutput(true)</code> for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server.</p> <p>For example, this should do a POST:</p> <pre><code>URL myURL = new URL("http://example.com/my/path"); URLConnection conn = myURL.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); OutputStream os = conn.getOutputStream(); os.write("Hi there!"); os.close(); InputStream is = conn.getInputStream(); // read stuff here </code></pre> <p>While this would do a GET:</p> <pre><code>URL myURL = new URL("http://example.com/my/path"); URLConnection conn = myURL.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); InputStream is = conn.getInputStream(); // read stuff here </code></pre> <p><code>URLConnection</code> will also do other weird things. If the server specifies a content length then <code>URLConnection</code> will keep the underlying input stream open until it receives that much data, <em>even if you explicitly close it</em>. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as the <code>URLConnection</code> would keep the network connection open. This probably probably exists even if you just use <code>getStream()</code> though.</p>
<p>No it does not. But if the protocol of the URL is HTTP, you'll get a <a href="http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html" rel="nofollow noreferrer"><code>HttpURLConnection</code></a> as a return object. This class has a <code>setRequestMethod</code> method to specify which HTTP method you want to use. </p> <p>If you want to do more sophisticated stuff you're probably better off using a library like <a href="http://hc.apache.org/httpclient-3.x/" rel="nofollow noreferrer">Jakarta HttpClient</a>.</p>
6,042
<p>I have a mesh of a bowl that has the perfect shape of half a sphere. I want to easily convert it to the containing sphere solid and a box solid that will be subtracted from it.</p> <p><a href="https://i.stack.imgur.com/FlT0X.png" rel="nofollow noreferrer" title="Conversion process"><img src="https://i.stack.imgur.com/FlT0X.png" alt="Conversion process" title="Conversion process"></a></p> <p>Googling mesh to solid shows that in various tools such as 3ds Max, Fusion, etc., manual approximation of where the sphere might go is created manually by visually comparing to the mesh or the cross section when creating the solid but I am looking for the minimum enclosing sphere and box to be generated/calculated by the software.</p> <p>Source file format is of course not an issue, it can be any known mesh file.</p>
<p>The answers by @markshancock and @fred-dot-u describe the process of creating a CAD primitive sphere and subtracting a cube; this is a trivial task in most any 3D CAD program. You could manually measure the mesh to determine its dimensions, and frankly, I would recommend this approach. (If you have a large task like converting 100,000 half-sphere meshes, I'd re-think the approach and go to the source that generated the meshes in the first place!)</p> <p>However, these don't address converting the mesh to a primitive, which is normally not possible for arbitrary meshes (therefore a CAD program will not have such a function), and much more difficult than simply measuring and re-creating.</p> <p>You assert that your mesh file "has the perfect shape of half a sphere". A mesh is basically on a collection of vertices, joined by edges and faces. The vertices are defined by numeric coordinates, and in a computer will always have some rounding errors, and the linear edges and planar faces are most definitely not round. Therefore, it may be incredibly close, but it will most definitely not be perfect.</p> <p>In this <em>very</em> particular case, the diameter of the sphere is the same as the diameter of the circular face of your half-sphere. You could plausibly write a simple program that would locate the maximum distance between any two vertices in your mesh and use that for the diameter. The midpoint of the line between those two points would be the center of the sphere. This should produce a good result but may not be "exact" depending on the details of the mesh.</p> <p>I won't try to explain how to create the actual program as that is not in the scope of 3D printing.</p>
<p>So it depends a lot on what you want to do.</p> <ol> <li><p>If you want to mathematically calculate what cube fits in what size sphere, that is straight forward. The <a href="http://mathcentral.uregina.ca/qq/database/qq.09.04/brett1.html" rel="nofollow noreferrer">diagonal for the cube</a> has to fit into the diameter of the shere. For a cube with edge 'l' and a shpere with diamamer 'd' then <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=4l%5Csqrt%7B3%7D" alt=""> &lt;= d.</p></li> <li><p>If you want to model a cube and a sphere in CAD (or one inside the other) you just do it. They are both primitives. Takes less than a minute.</p></li> </ol> <p><a href="https://i.stack.imgur.com/HFqUZm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HFqUZm.jpg" alt="enter image description here"></a></p> <ol start="3"> <li><p>You can use a mesh in a design too. I would assume if you are wanting to use a mesh, the mesh must contain something other than just a smooth bowl or what the point of the mesh? Fusion 360 allows you to import a mesh and play with it just like that and combine it with model objects (just like the box). </p></li> <li><p>You can actually convert a mesh into a solid model if you want to too. Fusion 360 CAD has ways to help you convert that mesh to a sculpt. First create a sculpt object that represents the shape of the mesh object (like a sphere or a quadraball). Next import the mesh then collapse the model over the mesh (using it like a model to form a mold). You can then delett the mesh and use the molded sculpt.</p></li> </ol>
663
<p>I have a large exiting C++ project involving:</p> <ul> <li>4 applications</li> <li>50+ libraries</li> <li>20+ third party libraries</li> </ul> <p>The project uses QMake (part of Trolltech's Qt) to build the production version on Linux, but I've been playing around at building it on MacOS.</p> <p>I can build in on MacOS using QMake just fine but I'm having trouble producing the final .app. It needs collecting all the third party frameworks and dynamic libraries, all the project's dynamic libraries and making sure the application finds them.</p> <p>I've read online about using install_name_tool but was wondering if there's a process to automate it.</p> <p>(Maybe the answer is to use XCode, see related question, but it would have issues with building uic and moc)</p> <p>Thanks </p>
<p>I'm sure this could be of some great help for you :</p> <p><a href="https://blog.qt.io/blog/2007/08/23/deploying-mac-applications-without-the-hassle/" rel="nofollow noreferrer">deployqt</a></p> <p>Hope this helps !</p>
<p>I side-stepped this problem completely by building my Qt app statically on OS X. That might not be practical for you though.</p>
4,658
<p>I'd like to print modifications for my bird feeder, both to patch over the hail damage from last summer and to try to deter the neighborhood squirrels. I have an FDM printer (and experience with nylon, ABS, and PLA, though don't restrict answers to those if there's something else that's better), what kind of filament would stand up best to daily exposure to sun, rain, snow, etc?</p>
<p>PET(G) is a strong contender. It is very strong and water-resistant, and as such is often used to make pop bottles.</p> <p>PLA has a reputation for being "biodegradable" and therefore it is often discouraged to use PLA outside and/or in contact with water. However, PLA only biodegrades under very specific conditions which it won't generally be exposed to so it can be used (though, as a harder and less flexible material it is more likely to be damaged by hail).</p> <p>ABS and Nylon are good choices as well. Basically, any plastic you have on hand will last for years, even in an outside application.</p>
<p>I think ABS would be your best bet. It's not biodegradable and realtivley easy to print.</p> <p>But you can use more or less any material if you use some form of coating on it. I would always go for coated PLA instead of other materials just because PLA is the easiest to print and it's nontoxic.</p>
88
<p>My company is using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_SourceSafe" rel="nofollow noreferrer">Visual SourceSafe</a> (VSS) and Visual Studio 2005 (soon 2008). They want to switch to <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a>, but the developers don't want to lose the integration we get with VSS and Visual Studio. </p> <p>I know there are CVS plugins, but what functionality, if any, is lost with CVS?</p>
<p>Screaming at VSS for lost source code, etc. Seriously though, it is a very different model (<a href="http://en.wikipedia.org/wiki/Optimistic_replication#Examples" rel="nofollow noreferrer">optimistic locking</a>), so you will probably lose some productivity for the first little while. I would probably look at using <a href="http://en.wikipedia.org/wiki/TortoiseCVS" rel="nofollow noreferrer">TortoiseCVS</a> and "Open Folder In Windows Explorer" right-click or the <a href="http://www.mindscape.co.nz/blog/?p=199" rel="nofollow noreferrer">Visual Studio Explorer</a> plug-in rather than a CVS plug-in if you are using Visual Studio 2008 (all of the CVS plug-ins I have tried have had either serious functionality issues, or serious stability issues). </p> <p>VSS is really a terrible source control system, and moving to a modern style (optimistic locking) source control system will be a huge boon in the long run. You might want to skip the 1990s all together though and move to <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow noreferrer">Subversion</a>/<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="nofollow noreferrer">Git</a>/<a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow noreferrer">Mercurial</a> and get into the 2000s. </p>
<p>My hack is as follows:</p> <p>I am mainly a Java developer and I use Eclipse/RAD. The support for CVS is great and is very easy to work with.</p> <p>For the C# work I do I tried to find a CVS plugin for Visual Studio but was unhappy with the one I found. In the end, I decided to use Eclipse to handle the versioning of my C# projects.</p> <p>The procedure:</p> <ol> <li>Create a simple project in Eclipse</li> <li>Open VS and save the project into the directory created by Eclipse</li> <li>Return to Eclipse, press <strong>F5</strong> to refresh the project</li> <li>Share the project (i.e. add to CVS)</li> <li>Add <strong>.sln</strong> to the list of externally handled files in the Eclipse settings</li> <li>VS can now be opened directly from Eclipse by clicking the .sln file, the project can be worked on within VS. Upon exit from VS the project must be refreshed in Eclipse and can be synchronised with CVS</li> </ol> <p>Although I have not yet used the Subversion plugin, I guess that would work in a similar way.</p> <p>This solution works well for me especially as I spend most my time in Eclipse anyway.</p> <p>I did try using TortoiseCVS but found it tricky to use. Eclipse is free and the CVS interface is very usable.</p>
7,570
<p>So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?</p> <pre><code>public class TokenTree { public TokenTree() { /* I must admit to not fully understanding this, * I got it from msdn. As far as I can tell, IDictionary is an * interface, and Dictionary is the default implementation of * that interface, right? */ SubPairs = new Dictionary&lt;string, string&gt;(); } public string Key; public string Value; public IDictionary&lt;string, string&gt; SubPairs; } </code></pre> <p>It's only really a simple shunt for passing around data.</p>
<p>There is an actual Data Type called KeyValuePair, use like this</p> <pre><code>KeyValuePair&lt;string, string&gt; myKeyValuePair = new KeyValuePair&lt;string,string&gt;("defaultkey", "defaultvalue"); </code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="nofollow noreferrer">Dictionary Class</a> is exactly what you want, correct.</p> <p>You can declare the field directly as Dictionary, instead of IDictionary, but that's up to you.</p>
3,030
<p>How can I get an image to stretch the height of a <code>DIV</code> class?</p> <p>Currently it looks like this:</p> <p><img src="https://i.stack.imgur.com/DcrXC.png" width="650" /></p> <p>However, I would like the <code>DIV</code> to be stretched so the <code>image</code> fits properly, but I do not want to resize the `image.</p> <p>Here is the CSS for the <code>DIV</code> (the grey box):</p> <pre class="lang-css prettyprint-override"><code>.product1 { width: 100%; padding: 5px; margin: 0px 0px 15px -5px; background: #ADA19A; color: #000000; min-height: 100px; } </code></pre> <p>The CSS being applied on the image:</p> <pre class="lang-css prettyprint-override"><code>.product{ display: inline; float: left; } </code></pre> <p>So, how can I fix this?</p>
<p>Add <code>overflow:auto;</code> to <code>.product1</code></p>
<pre><code>display:inline float:left </code></pre> <p>is your problem</p> <p>Floating makes the parents width not be stretched by the child, try placing the image without the float. If you take the float off, it should give you the desired effect.<br> Another approach would be to make sure you are clearing your floats at the end of the parent element so that they don't scope creep.</p> <p><strong>Update:</strong> After viewing your link Your height issue as displayed, is because the floats are not being cleared.</p>
6,248
<p>When I'm joining three or more tables together by a common column, I'd write my query like this:</p> <pre><code>SELECT * FROM a, b, c WHERE a.id = b.id AND b.id = c.id </code></pre> <p>a colleague recently asked my why I didn't do explicit <em>Join Transitive Closure</em> in my queries like this:</p> <pre><code>SELECT * FROM a, b, c WHERE a.id = b.id AND b.id = c.id AND c.id = a.id </code></pre> <p>are the really any advantages to this? Surely the optimiser can imply this for itself?</p> <p><em>edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @<a href="https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114">Stu</a> for cleaning it up</em></p>
<p>You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.</p> <p>These days that entire syntax is going out anyway.</p>
<p>That syntax has its uses though ... there are times when you find you need to join two tables on more than one field</p>
3,221
<p>The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as:</p> <pre><code>áéíóú </code></pre> <p>...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives:</p> <pre><code>áéíóú </code></pre> <p>Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for the property is UTF-8.</p> <p>So why does Tapestry appear to botch the encoding when setting the property?</p> <p>Relevant code follows:</p> <h2>Login.html</h2> <pre class="lang-html prettyprint-override"><code>&lt;html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...&gt; &lt;body jwcid="@Body"&gt; ... &lt;form jwcid="@Form" listener="listener:attemptLogin" ...&gt; ... &lt;input jwcid="password"/&gt; ... &lt;/form&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>Login.page</h2> <pre class="lang-jsp prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE page-specification PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN" "http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd"&gt; &lt;page-specification class="mycode.Login"&gt; ... &lt;property name="password" /&gt; ... &lt;component id="password" type="TextField"&gt; &lt;binding name="value" value="password"/&gt; &lt;binding name="hidden" value="true"/&gt; ... &lt;/component&gt; ... &lt;/page-specification&gt; </code></pre> <h2>Login.java</h2> <pre><code>... public abstract class Login extends BasePage { ... public abstract String getPassword(); ... public void attemptLogin() { // At this point, inspecting getPassword() returns // the incorrectly encoded String. } ... } </code></pre> <h2>Updates</h2> <p>@Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 <a href="http://tapestry.apache.org/tapestry4/UsersGuide/configuration.html#configuration.properties" rel="nofollow noreferrer">documentation</a> indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions.</p> <p>@myself: Solution found.</p>
<p>VPC to Hyper-V is one way.</p>
<p>You should review Windows 2008 R2 SP1 upgrade with RemoteFX, it comes with a new video driver for VM's that allow 3D, extended desktops and more. It will help resolve some of the issues you are seeing today.</p> <p>Both the Host server and VM need to be running SP1 of Windows 2008 R2.</p> <p><a href="http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx" rel="nofollow">http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx</a></p>
6,478
<p><strong>A Little Background Information</strong>:<br> I've been looking at a few PHP framework recently, and it came down to two. The Zend Framework or CodeIgniter. </p> <p>I prefer CodeIgniter, because of its simple design. It's very bare bone, and it is just kept simple. The thing I don't like though is the weak template system. The template system is important for me, because I will be working with another designer. Being able to give him a good template system is a big plus.</p> <p>Zend was the second choice, because of the better template system that is built in. Zend is a different beast though compared to CodeIgniter. It emphasis "loose coupling between modules", but is a bigger framework. I don't like to feel like I have many things running under the hood that I never use. That is unnecessary overhead in my opinion, so I thought about putting a template system into CodeIgniter: Smarty.</p> <p><strong>Question(s)</strong>: How easy/hard is the process to integrate Smarty into CodeIgniter? From my initial scan of the CodeIgniter documentation, I can see that the layout of the framework is easy enough to understand, and I anticipate no problems. I want to know if anyone has used it before, and therefore are aware of any "gotchas" you my have experienced that is going to make this harder than it should be or impossible to pull off. I also want to know if this is a good thing to do at all. Is the template system in CodeIgniter enough for normal use? Are there any other template modules that are good for CodeIgniter aside from Smarty? I better off with Zend Framework? Is any wheel being invented here?</p>
<p>Slightly OT, hope you don't mind...</p> <p>I'm a Zend Framework user and I think it's worth saying that the loose coupling means you don't need to include any files you're not actively using. Hopefully this negates your concern about unnecessary overhead.</p> <p>With the layouts stuff added in a recent release of ZF, its templating is really hard to fault... and it's completely pluggable as Favio mentions. The more I use ZF, the more I like it; they do things the way I would do them!</p>
<p>Check out this <a href="http://codeigniter.com/forums/viewthread/94035/" rel="nofollow noreferrer">custom CodeIgniter templating library</a>. I've already used it on several projects and it is easy to use. I know this post is late but it's worth checking out.</p>
6,229
<p>I'm looking for a way to extract the audio part of a FLV file. </p> <p>I'm recording from the user's microphone and the audio is encoded using the <a href="http://en.wikipedia.org/wiki/Nellymoser_Asao_Codec" rel="nofollow noreferrer">Nellymoser Asao Codec</a>. This is the default codec and there's no way to change this.</p>
<p><a href="http://ffmpeg.mplayerhq.hu/" rel="nofollow noreferrer">ffMpeg</a> is the way to go ! It worked for me with SVN Rev 14277.</p> <p>The command I used is : <code>ffmpeg -i source.flv -nv -f mp3 destination.mp3</code></p> <p><strong>GOTCHA</strong> :</p> <p>If you get this error message : <code>Unsupported audio codec (n)</code>, check the <a href="https://www.adobe.com/content/dam/Adobe/en/devnet/flv/pdfs/video_file_format_spec_v10.pdf" rel="nofollow noreferrer">FLV Spec</a> in the <strong>Audio Tags</strong> section. </p> <p>ffMpeg can decode n=6 (Nellymoser).<br/> But for n=4 (Nellymoser 8-kHz mono) and n=5 (Nellymoser 16-kHz mono) it doesn't work.</p> <p>To fix this <strong>use the default microphone rate</strong> when recording your streams, overwise ffMpeg is unable to decode them.</p> <p>Hope this helps !</p>
<p>I was going to recommend this: <a href="http://code.google.com/hosting/takenDown?project=nelly2pcm&amp;notice=7281" rel="nofollow noreferrer">http://code.google.com/hosting/takenDown?project=nelly2pcm&amp;notice=7281</a>.</p> <p>But its been taken down. Glad I got a copy first :-)</p>
9,320
<p>Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D.</p> <p>Despite the lack of known big users, D seems like a very promissing language to me, and according to <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="noreferrer">TIOBE</a>, it's fairly popular.</p>
<p>I'm using D for my research work in the area of computer graphics. I and others have had papers published in our fields based on work done using D. I think it's definitely ready for use on small to medium sized research projects where performance matters. It's a nice fit for research work because often you're starting from scratch anyway, so you don't have much legacy code to worry about integrating with.</p> <p>Another popular area for use seems to be web services. Hopefully someone else can comment who's in this space, but there too I think the idea is that performance often really matters so you want a compiled-to-the-metal language. Services are often fairly small, self-contained processes, so interop with large amounts of legacy C++ code is not really necessary or useful. Thus D can get its foot in the door.</p> <p>I think D will continue to gain grass-roots followers in this way -- on smaller projects that for whatever reason can afford to ditch the C++ legacy in order to gain a programming language that's much more enjoyable to use, and perhaps more productive too.</p> <p>But until there's a huge number of grass-roots users there won't be much in the way of big corporate users I suspect.</p>
<p>I started a ray-traced renderer in D with ldmd2.</p> <p><a href="http://palaes.rudanium.org/SubSpace/render.php" rel="nofollow">http://palaes.rudanium.org/SubSpace/render.php</a></p>
8,020
<p>On a number of occasions I've broken small plastic parts that are nearly impossible to replace but could easily be 3-D printed. The latest such mishap is the volume knob on the factory-installed radio on my car. </p> <p>I have little experience in 3D printing, and would like to be able to replace these parts with something very close to the original. Spending hours measuring and designing a replacement part that should be $5 isn't really an option. I need something to scan the broken pieces in 3D and somehow just seal up the seam where it's broken.</p> <p>Is there a scanning/printing/software system to do this that doesn't require a lot of 3D design experience?</p>
<p>The easiest way is as you currently do: model the pieces by hand, using (digital) calipers to measure them.</p> <p>Scanning technology isn't very good, and the models are not of printable quality. Usually, fixing a scan is more work than modeling an item from scratch.</p>
<p>There is scanning technology: either hardware or software (such software typically works from multiple 2D photographs). It has limitations, but is an active research area, and getting better all the time. "Autodesk 123D Catch" and "3-Sweep" are a couple examples.</p> <p>One tradeoff between automatic and manual is the complexity of the shape you need to duplicate. Sometimes you can make a much simpler shape that still works, and/or thicken the part so it doesn't break the next time. That can make manual design much more attractive.</p>
97
<p>Can I return it as an object if I am doing a </p> <pre><code>Select OneItem from Table Where OtherItem = "blah"? </code></pre> <p>Is there a better way to do this?</p> <p>I am building a constructor to return an object based on its name rather than its ID.</p>
<p><code>query.UniqueResult&lt;T&gt;()</code> returns just one <strong>T</strong></p>
<p>Or using LINQ you can have <code>query.First()</code>, <code>query.SingleOrDefault()</code>, <code>query.Min(predicate)</code> etc...</p>
7,571
<p>Can anyone tell me what is the <em>memory usage overhead associated with PHP opcode cache</em>? </p> <p>I've seen a lot of reviews of <code>opcode cache</code> but all of them only concentrate on the performance increase. I have a small entry level <em>VPS and memory limits</em> are a concern for me. </p>
<p>Most of the memory overhead will come from the opcode cache size. Each opcode cacher has their own default(e.g. 30MB for APC) which you can change through the config file.</p> <p>Other than the cache size, the actual memory overhead of the cacher itself is negligible.</p>
<p>In todays world: It's neglectible. I think memory consumption was about 50 MB bigger with eAccelerator then it was without when I did my <a href="http://blogs.interdose.com/dominik/2008/04/11/benchmarking-php-eaccelerator-und-andere-opcode-caches/" rel="nofollow noreferrer">benchmarks</a>.</p> <p>If you really need the speed but do have headaches that your RAM might be not enough: grab $40 and buy another GIG of RAM for your server ;)</p>
4,918
<p>Let's say you have a class called Customer, which contains the following fields:</p> <ul> <li>UserName</li> <li>Email</li> <li>First Name</li> <li>Last Name</li> </ul> <p>Let's also say that according to your business logic, all Customer objects must have these four properties defined.</p> <p>Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object. </p> <p>I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.</p> <p>Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?</p>
<p>Two design approaches to consider</p> <p>The <a href="http://www.hillside.net/plop/plop98/final_submissions/P10.pdf" rel="noreferrer">essence</a> pattern</p> <p>The <a href="https://martinfowler.com/bliki/FluentInterface.html" rel="noreferrer">fluent interface</a> pattern</p> <p>These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.</p> <p>An example of the fluent interface in action would be:</p> <pre class="lang-java prettyprint-override"><code>public class CustomerBuilder { String surname; String firstName; String ssn; public static CustomerBuilder customer() { return new CustomerBuilder(); } public CustomerBuilder withSurname(String surname) { this.surname = surname; return this; } public CustomerBuilder withFirstName(String firstName) { this.firstName = firstName; return this; } public CustomerBuilder withSsn(String ssn) { this.ssn = ssn; return this; } // client doesn't get to instantiate Customer directly public Customer build() { return new Customer(this); } } public class Customer { private final String firstName; private final String surname; private final String ssn; Customer(CustomerBuilder builder) { if (builder.firstName == null) throw new NullPointerException("firstName"); if (builder.surname == null) throw new NullPointerException("surname"); if (builder.ssn == null) throw new NullPointerException("ssn"); this.firstName = builder.firstName; this.surname = builder.surname; this.ssn = builder.ssn; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } public String getSsn() { return ssn; } } </code></pre> <pre class="lang-java prettyprint-override"><code>import static com.acme.CustomerBuilder.customer; public class Client { public void doSomething() { Customer customer = customer() .withSurname("Smith") .withFirstName("Fred") .withSsn("123XS1") .build(); } } </code></pre>
<p>Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to make sure the required parameters are there.</p>
6,148