instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I have a few controls that inherit from <code>ASP.NET buttons</code> and use <code>onserverclick</code>.</p> <p>If the user clicks twice, the button fires two server side events. How can I prevent this?</p> <p>I tried setting <code>this.disabled='true'</code> after the click (in the <code>onclick</code> attribute) via javascript, but that blocks the first postback as well.</p>
<p>See this example for disabling control on postback. It should help you do what you're trying to achieve.</p> <p><a href="http://encosia.com/2007/04/17/disable-a-button-control-during-postback/" rel="noreferrer">http://encosia.com/2007/04/17/disable-a-button-control-during-postback/</a></p>
<p>You can also try for example btnSave.Enable = false; when the button is hit and before the processing for the button is done in the Click Event routine. If you need it to be reset to allow it to be enabled have a separate button that resets the button for reuse. </p> <p>Another method is to set the button with verification so that the user is asked if they want to Save, it should pop up both times.</p> <p>Yet another method would be to flag the first occurrence then set a popup for the second to verify a second or subsequent usage.</p>
7,323
<p>I have an Ender 5 Pro with a flexible build plate (The factory default one).</p> <p>There are multiple extremely thin tracks of melted PLA all over it. Too thin to easily peal off when cooled. Thin enough that you can run your finger over them and barely know that they are there.</p> <p>What is the best way to clean them off other than simply brut forcing them with a scraper and risking damaging the surface.</p> <p>Rubbing with IPA and a cloth isn't enough.</p> <p>I have a plastic razor that's normally used for removing vinyl decal from vehicles without scratching the paint, would that be useful, or maybe just scrubbing for an hour with a nail brush?</p>
<h2>TL;DR:</h2> <p>Print more PLA on top of them, and pull it off together.</p> <h2>Preparation</h2> <p>First, of course, clean it well with IPA. This will both ensure there's no oil or other material on top of the PLA that will prevent it from bonding well with new PLA, and start to work underneath it to get it loose.</p> <h2>Printing</h2> <p>Then, print! Do a 2- or 3-layer square covering the whole buildplate if you need to, or just smaller ones in the affected areas. They should bond to whatever is there and pull it up when you peel them off.</p> <h2>Prevention</h2> <p>To avoid this happening in the future, <strong>fix your bed leveling</strong>. The type of tracks that are nearly impossible to remove by themselves normally come from printing with the nozzle so low that the material is forced entirely between the texture irregularities of the build surface, with no significant layer on top, and this means your bed is at least a whole layer-height too high relative to the nozzle.</p>
<p>If you can feel it with your finger, then you can scrape it off. Just be careful. Keep the scraper closer to horizontal and don't dig in. It doesn't really need much effort.</p> <p>If you can't feel it with your finger then it doesn't matter. Just clean as normal and carry on printing over it.</p>
2,116
<p>I currently use the following function to do a simple HTTP GET.</p> <pre><code>public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n &gt;= 0) { n = r.read(buffer, 0, buffer.length); if (n &gt; 0) { content.append(buffer, 0, n); } } } finally { //if (b != null) b.close(); if (r != null) r.close(); if (s != null) s.close(); } return content.toString(); } </code></pre> <p>I see no reason to use the <code>BufferedReader</code> since I am just going to download everything in sequence. Am I right in thinking there is no use for the <code>BufferedReader</code> in this case?</p>
<p>In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers).</p> <p>There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until <em>flush()</em> is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using <em>mark(int)</em> and <em>reset()</em>. For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to.</p> <p>Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks:</p> <pre><code> InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } </code></pre> <p>If you are opening multiple streams, nest try/finally blocks.</p> <p>Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).</p>
<p>My gut tells me that since you're already performing buffering by using the byte array, it's redundant to use the BufferedReader.</p>
5,131
<ul> <li>Plastic: Same Matterhacker PLA (filament I use every day)</li> <li>Printer: Anycubic i3 Mega (the one I use every day)</li> <li>Slicer: Ultimaker Cura 4.2.1</li> </ul> <p>I don't know what's causing it, I haven't changed any slicer settings to my knowledge, I haven't changed anything on the printers end, and I'm using the same filament I've always used. But for some reason, the first layer is simply not sticking. At first I noticed when doing a print the nozzle seemed a little higher than normal for the first layer, but then it started having problems where 0&nbsp;% of the filament would stick to the bed and it would all just come off and turn into a mess. I've checked and checked, but I see no reason the printer would just start doing this now all the sudden when it's worked perfectly for a year now.</p> <hr> <p>EDIT: Something I've noticed since posting this is that older sliced models seem to print just fine, which means there's something about the newser slicer settings that's causing it. I don't know what I would have changed though and/or how to restore to my original settings.</p>
<p>There are 3 general factors about print adhesion you always have to keep in mind:</p> <ul> <li>Have a sufficient surface for the print to stick. A pyramid printed on the tip can't print properly.</li> <li>Check the leveling of your bed occasionally and relevel the bed. By removing prints, one can easily unlevel it over time without noticing it.</li> <li>Clean your print bed from fingerprints and grease every so often. Fats are good separators between the print and the bed. Getting them off with Isopropyl alcohol or other solvents can restore print surfaces in an instant.</li> </ul> <p>In this specific case, there are some hints that make the general things less of an issue though: Old sliced items print fine, newer not. This hints that you changed something in the print settings. Among the settings that are good for adhesion, check your old G-code for the following three:</p> <ul> <li>Bed temperature. I use 60&nbsp;°C bed temperature for PLA and have good results on bed adhesion. Others print with 50&nbsp;°C. However, going too low can make the plastic not stick well anymore.</li> <li>Extrusion temperature. When the plastic extrudes, it has to be molten enough to push out enough and cold enough to solidify within moments and stick to the surface of the bed. If it is too hot, it would be dragged along, if it's too cold it doesn't get to stick either. I use 190-200&nbsp;°C for PLA.</li> <li>The <code>first layer height</code> might be different. I usually use 0.2&nbsp;mm for this setting, no matter what the actual layer height is, and get good adhesion and not too much trouble with tiny unevenness.</li> <li>The reason might be a mechanical issue, in that the <a href="https://drucktipps3d.de/wp-content/uploads/2017/11/anycubic_i3_mega_endstop-1024x768.jpg" rel="nofollow noreferrer">Z-endstops</a> (in an Anycubic i3, there are two, hidden in the frame sides) might have bent, moved or misaligned over time. Check its positioning. If the mount is broken, there are <a href="https://www.thingiverse.com/make:441224" rel="nofollow noreferrer">replacement part designs</a>.</li> </ul>
<p>This seems like a long-shot, but I've noticed at this time of year many 3D prints fail. We noticed 4 printers all went dead and had massive non-stick issues last year about this time. Turns out it was mostly around changes in temperature and humidity - the outside temperature changed inside AC settings/wind-flow, etc.</p> <p>So, you might think through some of the meta-causes of where the printer is, and if temp/air/humidity might be just enough chaos to not make the material stick. Right in September, I start putting a light layer of glue down on the glass bed under each print or increasing the use of rafts...</p>
1,463
<p>How do I calculate the distance between two points specified by latitude and longitude?</p> <p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>
<p>This <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="noreferrer">link</a> might be helpful to you, as it details the use of the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine formula</a> to calculate the distance.</p> <p>Excerpt:</p> <blockquote> <p>This script [in Javascript] calculates great-circle distances between the two points – that is, the shortest distance over the earth’s surface – using the ‘Haversine’ formula.</p> </blockquote> <pre class="lang-js prettyprint-override"><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(lat2-lat1); // deg2rad below var dLon = deg2rad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; // Distance in km return d; } function deg2rad(deg) { return deg * (Math.PI/180) } </code></pre>
<p>Here's a simple javascript function that may be useful from this <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow">link</a>.. somehow related but we're using google earth javascript plugin instead of maps</p> <pre><code>function getApproximateDistanceUnits(point1, point2) { var xs = 0; var ys = 0; xs = point2.getX() - point1.getX(); xs = xs * xs; ys = point2.getY() - point1.getY(); ys = ys * ys; return Math.sqrt(xs + ys); } </code></pre> <p>The units tho are not in distance but in terms of a ratio relative to your coordinates. There are other computations related you can substitute for the getApproximateDistanceUnits function <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow">link here</a></p> <p>Then I use this function to see if a latitude longitude is within the radius</p> <pre><code>function isMapPlacemarkInRadius(point1, point2, radi) { if (point1 &amp;&amp; point2) { return getApproximateDistanceUnits(point1, point2) &lt;= radi; } else { return 0; } } </code></pre> <p>point may be defined as</p> <pre><code> $$.getPoint = function(lati, longi) { var location = { x: 0, y: 0, getX: function() { return location.x; }, getY: function() { return location.y; } }; location.x = lati; location.y = longi; return location; }; </code></pre> <p>then you can do your thing to see if a point is within a region with a radius say:</p> <pre><code> //put it on the map if within the range of a specified radi assuming 100,000,000 units var iconpoint = Map.getPoint(pp.latitude, pp.longitude); var centerpoint = Map.getPoint(Settings.CenterLatitude, Settings.CenterLongitude); //approx ~200 units to show only half of the globe from the default center radius if (isMapPlacemarkInRadius(centerpoint, iconpoint, 120)) { addPlacemark(pp.latitude, pp.longitude, pp.name); } else { otherSidePlacemarks.push({ latitude: pp.latitude, longitude: pp.longitude, name: pp.name }); } </code></pre>
4,760
<p>Is it possible (in Vb.Net 2005), without manually parsing the dataset table properties, to create the table and add it to the database?</p> <p>We have old versions of our program on some machines, which obviously has our old database, and we are looking for a way to detect if there is a missing table and then generate the table based on the current status of the table in the dataset. We were re-scripting the table every time we released a new version (if new columns were added) but we would like to avoid this step if possible.</p>
<p>See this MSDN Forum Post: <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/4929a0a8-0137-45f6-86e8-d11e220048c3/" rel="nofollow noreferrer">Creating a new Table in SQL Server from ADO.net DataTable</a>. </p> <p>Here the poster seems to be trying to do the same thing as you, and provides code that generates a Create Table statement using the schema contained in a DataTable. </p> <p>Assuming this works as it should, you could then take that code, and submit it to the database through <code>SqlCommand.ExecuteNonQuery()</code> in order to create your table.</p>
<p>Here is the code: </p> <pre class="lang-cs prettyprint-override"><code>SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1"); con.Open(); string sql = "Create Table abcd ("; foreach (DataColumn column in dt.Columns) { sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ","; } sql = sql.TrimEnd(new char[] { ',' }) + ")"; SqlCommand cmd = new SqlCommand(sql, con); SqlDataAdapter da = new SqlDataAdapter(cmd); cmd.ExecuteNonQuery(); using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) using(var builder = new SqlCommandBuilder(adapter)) { adapter.InsertCommand = builder.GetInsertCommand(); adapter.Update(dt); } con.Close(); </code></pre> <p>I hope you got the problem solved.<br> Here <code>dt</code> is the name of the DataTable.<br> Alternatively you can replace: </p> <pre class="lang-cs prettyprint-override"><code>adapter.update(dt); </code></pre> <p>with</p> <pre class="lang-cs prettyprint-override"><code>//if you have a DataSet adapter.Update(ds.Tables[0]); </code></pre>
3,715
<p>I have an issue with my Anet A8 printer and how it interlocks with Ultimaker Cura. </p> <p>I want to print this file named <code>Loki_hörner_v2.stl</code>and Cura slices it fine, but when it comes to printing all the preheat happens, but then it stops, not going on at all. What might be wrong here?</p>
<p>Special characters like <code>Ä</code> <code>Ö</code> or <code>Ü</code> in the stl-filename resulted in Ultimaker Cura creating a comment of the filename in the g-code that read like </p> <pre><code>;MESH:Loki_hörner_v2.stl </code></pre> <p>This apparently could not be parsed by the Anet A8, leading to an error and halt.</p>
<h3>Avoid naming <code>.gcode</code> files with non-ASCII characters</h3> <em>(this includes <a href="https://en.wikipedia.org/wiki/Extended_ASCII" rel="nofollow noreferrer">EASCII</a>)</em> <p>I know of no firmware on a printer that can handle files that have characters not present in the set of 95 non-control <a href="https://www.w3schools.com/charsets/ref_html_ascii.asp" rel="nofollow noreferrer">American Standard Code for Information Interchange characters</a> by default. Marlin, for example, can't process the characters <code>ä</code> <code>ö</code> <code>ü</code> &amp; <code>€</code> as these all are missing in the ASCII.</p> <h3>Avoid having more than one <code>.</code></h3> <p>Nowadays the <code>.</code> is no longer a fully reserved character in file names, so a file can be named <code>0.5mm Gauge Block.stl</code> on Windows without problems.</p> <p>Ultimaker Cura will <strong>cut</strong> the name at the <code>.</code> before the extension when generating the <code>.gcode</code>. This is mainly done to prevent tons of errors that could crop up in firmware that might not be able to deal with it. Remember that this behavior can lead to overwriting files - our <code>0.5mm Gauge Block.stl</code> would generate <code>0.gcode</code>, as would <code>0.1.5 Penholder.stl</code> (that follows a version naming convention).</p> <h3>Avoid reserved characters</h3> <p>Also note that some characters are reserved in file naming and will lead to other errors (mainly when trying to create the files in the first place), including, but not limited to, <code>/</code> <code>\</code> <code>:</code> <code>?</code> <code>*</code>.</p>
1,230
<p>We are in the initial planning stages of building out a mobile site for one of our clients. This mobile site will be in addition to the main site that we have already built for them. We've determined that the content is going to be a small subsection of the main site and will target the main audience that is expected to use the site.</p> <p>While looking through some sample mobile sites we noticed that a lot of site that have WAP in the url are actually just simplified HTML files. <a href="http://wap.mlb.com" rel="nofollow noreferrer">http://wap.mlb.com</a> is not really WAP enabled but simple HTML.</p> <p>My question is WAP a think of the past? With smartphones and the iPhone having the ability to render sites as is do we need to worry about WML and WAP or will a stripped down html version be enough? </p> <p>Also can you recommend a blog or tutorial or answer below how best to check for mobile devices? Do we as the programmer need to know each variation of user agent in order to redirect them to our mobile site? </p> <p>Finally, would you program a mobile site for the iPhone/Touch Safari browser or just leave the site as is?</p>
<p>Newer phones come with WAP2 which uses HTML Mobile Profile (XHTML MP), which is quite similar to normal HTML. Older phones use Wireless Markup Language (WML). </p> <p>Depending on your audience I would consider making a mobile phone friendly version of the site using XHTML MP and drop WML completely. By mobile phone friendly I mean light graphics, little JavaScript and simple navigation.</p> <p>To check capabilities of different hand phones, take look at <a href="http://wurfl.sourceforge.net/" rel="nofollow noreferrer" title="Wireless Universal Resource File">WURFL</a>.</p> <p>Also, you might want to take a look at <a href="http://www.w3.org/TR/2008/REC-mobile-bp-20080729/" rel="nofollow noreferrer" title="Mobile Web Best Practices">Mobile Web Best Practices</a> from w3c.</p>
<p>I think the main difference with the 2.5G phones and the new 3G phones is that while 2.5G phones used their own browsers, browsers on 3G phones have become much more similar/accurate in their rendering capabilities.</p> <p>On the other hand, you can use CSS to render the same HTML in either a large screen format or a small mobile-optimized one, so I guess what has happened is that the "simple HTML" approach just appeared to be the least difficult path to take. Also, tableless layouts allow websites to scale better, making it easier to render a site in both large and small screen formats.</p> <p>So the end question will be that of a target market. Are you targeting a tech-savvy audience who will tend to have fully 3G-capable phones? Are you targeting people who might have 2.5G at the most?</p>
3,086
<p>How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?</p> <p>I know to do it using plan <code>String.Replace</code>, like:</p> <pre><code>myStr.Replace(&quot;\n&quot;, &quot;\r\n&quot;); myStr.Replace(&quot;\r\r\n&quot;, &quot;\r\n&quot;); </code></pre> <p>However, this is inelegant, and would destroy any &quot;\r+\r\n&quot; already in the text (although they are not likely to exist).</p>
<p>Will this do?</p> <pre><code>[^\r]\n </code></pre> <p>Basically it matches a '\n' that is preceded with a character that is not '\r'.</p> <p>If you want it to detect lines that start with just a single '\n' as well, then try</p> <pre><code>([^\r]|$)\n </code></pre> <p>Which says that it should match a '\n' but only those that is the first character of a line or those that are <em>not</em> preceded with '\r'</p> <p>There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.</p> <p><strong>EDIT:</strong> credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:</p> <pre><code>myStr = Regex.Replace(myStr, "(?&lt;!\r)\n", "\r\n"); </code></pre>
<pre><code>myStr.Replace("([^\r])\n", "$1\r\n"); </code></pre> <p>$ may need to be a \</p>
5,091
<p>Im currently writing my bachelor thesis with latex and using TexnicCenter. I want to be able to send my generated pdf file to people and they should be able to write comments. It seems like commenting is not allowed by default, how do I change this?</p> <p>I am using straight to PDF with pdflatex and acrobat reader 9 to read and comment on the files</p>
<p>I think your problem is that acrobat reader doesn't allow commenting on documents not produced by abode approved products, which I don't think pdflatex would be. </p> <p>You should look at the free <a href="http://www.docu-track.com/home/prod_user/PDF-XChange_Tools/pdfx_viewer" rel="noreferrer">PDF-XChange Viewer</a> which allows you to comment and annotate the text. Its a portable windows app (<a href="http://www.docu-track.com/PDFX_Vwr_Port.zip" rel="noreferrer">download</a>), so doesn't need to be installed on your (or the reviewers) machines.</p>
<p>I would definitely have a look at the <a href="https://rads.stackoverflow.com/amzn/click/com/0201433117" rel="nofollow noreferrer" rel="nofollow noreferrer">LaTeX Web Companion</a>. There is a whole section about generating PDF from LaTeX, including esoterica such as forms.</p>
4,708
<p>How do I load a Python module given its full path?</p> <p>Note that the file can be anywhere in the filesystem where the user has access rights.</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>
<p>For Python 3.5+ use (<a href="https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly" rel="noreferrer">docs</a>):</p> <pre><code>import importlib.util import sys spec = importlib.util.spec_from_file_location(&quot;module.name&quot;, &quot;/path/to/file.py&quot;) foo = importlib.util.module_from_spec(spec) sys.modules[&quot;module.name&quot;] = foo spec.loader.exec_module(foo) foo.MyClass() </code></pre> <p>For Python 3.3 and 3.4 use:</p> <pre><code>from importlib.machinery import SourceFileLoader foo = SourceFileLoader(&quot;module.name&quot;, &quot;/path/to/file.py&quot;).load_module() foo.MyClass() </code></pre> <p>(Although this has been deprecated in Python 3.4.)</p> <p>For Python 2 use:</p> <pre><code>import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() </code></pre> <p>There are equivalent convenience functions for compiled Python files and DLLs.</p> <p>See also <a href="http://bugs.python.org/issue21436" rel="noreferrer">http://bugs.python.org/issue21436</a>.</p>
<p>The best way, I think, is from the official documentation (<a href="https://docs.python.org/3.2/library/imp.html#examples" rel="nofollow">29.1. imp — Access the import internals</a>):</p> <pre><code>import imp import sys def __import__(name, globals=None, locals=None, fromlist=None): # Fast path: see if the module has already been imported. try: return sys.modules[name] except KeyError: pass # If any of the following calls raises an exception, # there's a problem we can't handle -- let the caller handle it. fp, pathname, description = imp.find_module(name) try: return imp.load_module(name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close() </code></pre>
9,318
<p>I have an actionscript file that defines a class that I would like to use inside a Flex application. </p> <p>I have defined some custom controls in a actionscript file and then import them via the application tag:</p> <pre> <code> &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:scorecard="com.apterasoftware.scorecard.controls.*" ... &lt;/mx:Application&gt; </code> </pre> <p>but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?</p>
<p>You'd need to import the class inside a script tag.</p> <pre><code>&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"&gt; &lt;mx:Script&gt; import com.apterasoftware.scorecard.controls.*; // Other imports go here // Functions and other code go here &lt;/mx:Script&gt; &lt;!-- Components and other MXML stuff go here --&gt; &lt;mx:VBox&gt; &lt;!-- Just a sample --&gt; &lt;/mx:VBox&gt; &lt;/mx:Application&gt; </code></pre> <p>Then you'll be able to reference that class anywhere else in your script tag. Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.</p> <p>Namespace declarations are only used to import other MXML components. AS classes are imported using the import statement either within a Script block or another AS file.</p>
<p>@Herms: To clarify a little, namespace declarations can be used to "import" AS classes as well, when you're going to instantiate them using MXML.</p> <p>For example, consider having a custom visual component you've written entirely in AS, let's say <code>com.apterasoftware.scorecard.controls.MathVisualizer</code>. To use it within MXML:</p> <pre><code>&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:aptera="com.apterasoftware.scorecard.controls.*"&gt; &lt;aptera:MathVisualizer width="400" height="300" /&gt; &lt;/mx:Application&gt; </code></pre>
6,101
<p>I've tried to write a string replace function in C, which works on a <code>char *</code>, which has been allocated using <code>malloc()</code>. It's a little different in that it will find and replace strings, rather than characters in the starting string.</p> <p>It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use <code>realloc()</code>, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using <code>realloc()</code>.</p> <p>Perhaps a little code will help:</p> <pre><code>void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input; while (find = strstr(find, search)) { if (delta &gt; 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); } memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } </code></pre> <p>The program works, until I try to <code>realloc()</code> in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result).</p> <p>If it helps, the calling code looks like:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; void strrep(char *input, char *search, char *replace); int main(void) { char *input = malloc(81); while ((fgets(input, 81, stdin)) != NULL) { strrep(input, "Noel", "Christmas"); } } </code></pre>
<p>As a general rule, you should <strong>never</strong> do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer.</p> <p>Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur.</p> <p>Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated.</p> <p>Resulting in:</p> <pre><code>void strrep(char *input, char *search, char *replace); char* strrepm(char *input, char *search, char *replace); void strrepmfree(char *input); </code></pre>
<p>My quick hints.</p> <p>Instead of:<br> <code>void strrep(char *input, char *search, char *replace)</code><br> try:<br> <code>void strrep(char *&amp;input, char *search, char *replace)</code></p> <p>and than in the body:<br> <code>input = realloc(input, strlen(input) + delta);</code></p> <p>Generally read about passing function arguments as values/reference and realloc() description :).</p>
2,356
<p>I have my Wordpress install and MediaWiki <a href="https://stackoverflow.com/questions/33745" title="Thanks ceejayoz">sharing the same login information</a>. Unfortunately, users need to log into both separately, but at least they use the same credentials. </p> <p>What I would like to do is cause a successful login on the Wordpress blog to also cause a login for MediaWiki (ideally both directions). There are two ways this could happen:</p> <ol> <li>Logging in causes a login on the other application (writes the cookie and creates the session in the DB)</li> <li>Accessing an application checks for the cookie of the other and then automatically logs in.</li> </ol> <p>Since the usernames are shared it seems like the latter should be pretty easy to do. Any tips would be great. </p>
<p>The primary problem you are going to run into is that you'll have two login forms, and two logout methods. What you need to do is pick one of the login forms as the default, and redirect the other one over to it.</p> <p>I've been able to <a href="http://www.howtogeek.com" rel="nofollow noreferrer">successfully integrate</a> bbPress + MediaWiki + WordPress + WordPress MU, but I wrote a lot of custom code to do it.</p> <p>I'm using the bbPress login page as the default (and .htaccess rewrite to /login/), and then I created my own MediaWiki authentication plugin (which looks a lot like the one you are using), except my plugin checks the WordPress/bbPress cookie for the login information and automatically logs the user in.</p> <p>I created a customized /logout/ link that runs the bbPress logout, and also kills the MediaWiki cookies at the same time.</p> <p>Then the last step was to redirect all of the other logout / login links for bbpress, mediawiki, etc, over to my consolidated one. I used .htaccess rewrites for this rather than mess with core code.</p> <p>Still a work in progress, but it works fairly well.</p>
<p>You could consider some kind of single-sign-on software. I am unaware of any that are free and I've only ever used <a href="http://ca.com/us/internet-access-control.aspx" rel="nofollow noreferrer">SiteMinder</a> which is neither free nor good. <a href="http://www.atlassian.com/software/crowd/default.jsp" rel="nofollow noreferrer">Crowd</a> may be better (but is again not <a href="http://www.atlassian.com/software/crowd/pricing.jsp" rel="nofollow noreferrer">free</a>).</p>
5,800
<p>I am going to design and build a 3D printer. I want the highest quality and accuracy so nothing except that is important for me. Which cartesian design has the highest quality and accuracy? CoreXY, Prusa, or Gantry (Ultimaker)?</p> <p>Also, is it better to have a nozzle that moves in just direction &quot;X&quot;, directions &quot;X and Y&quot;, or &quot;X, Y and Z&quot;?</p>
<p>The tradeoffs in these systems are all about quality achievable at particular speed and acceleration profiles. If you really don't care about speed at all and want maximum accuracy, you probably want some type of Cartesian setup with no belts, only rigid lead screws which you can take to as fine a pitch as you like, and you can make all the parts as rigid as you like because mass doesn't matter (since acceleration doesn't).</p> <p>Note however that extrusion accuracy is the limiting factor to quality and dimensional accuracy in even a half-decent printer. Rather than trying to design something with &quot;perfect&quot; spatial kinematics for quality from the outset, I think you should look at existing printers, figure out what about them isn't meeting your quality needs, and start from there to improve. You should also figure out what your speed constraints will be, even if they're only minimal.</p>
<p>The tradeoffs in these systems are all about quality achievable at particular speed and acceleration profiles. If you really don't care about speed at all and want maximum accuracy, you probably want some type of Cartesian setup with no belts, only rigid lead screws which you can take to as fine a pitch as you like, and you can make all the parts as rigid as you like because mass doesn't matter (since acceleration doesn't).</p> <p>Note however that extrusion accuracy is the limiting factor to quality and dimensional accuracy in even a half-decent printer. Rather than trying to design something with &quot;perfect&quot; spatial kinematics for quality from the outset, I think you should look at existing printers, figure out what about them isn't meeting your quality needs, and start from there to improve. You should also figure out what your speed constraints will be, even if they're only minimal.</p>
1,717
<p>I've seen these words a lot around Subversion (and I guess general repository) discussions.<br> I have been using <strong>SVN</strong> for my projects for the last few years, but I've never grasped the complete concept of these directories.</p> <p>What do they mean?</p>
<p>Hmm, not sure I agree with Nick re tag being similar to a branch. A tag is just a marker</p> <ul> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.tour.importing.html#svn.tour.importing.layout" rel="noreferrer"><strong>Trunk</strong></a> would be the main body of development, originating from the start of the project until the present.</p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.whatis.html" rel="noreferrer"><strong>Branch</strong></a> will be a copy of code derived from a certain point in the trunk that is used for applying major changes to the code while preserving the integrity of the code in the trunk. If the major changes work according to plan, they are usually merged back into the trunk. </p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.tags.html" rel="noreferrer"><strong>Tag</strong></a> will be a point in time on the trunk or a branch that you wish to preserve. The two main reasons for preservation would be that either this is a major release of the software, whether alpha, beta, RC or RTM, or this is the most stable point of the software before major revisions on the trunk were applied.</p></li> </ul> <p>In open source projects, major branches that are not accepted into the trunk by the project stakeholders can become the bases for <em>forks</em> -- e.g., totally separate projects that share a common origin with other source code.</p> <p>The branch and tag subtrees are distinguished from the trunk in the following ways:</p> <p>Subversion allows sysadmins to create <em>hook scripts</em> which are triggered for execution when certain events occur; for instance, committing a change to the repository. It is very common for a typical Subversion repository implementation to treat any path containing "/tag/" to be write-protected after creation; the net result is that tags, once created, are immutable (at least to "ordinary" users). This is done via the hook scripts, which enforce the immutability by preventing further changes if <strong>tag</strong> is a parent node of the changed object.</p> <p>Subversion also has added features, since version 1.5, relating to "branch merge tracking" so that changes committed to a <strong>branch</strong> can be merged back into the trunk with support for incremental, "smart" merging.</p>
<p><strong>Trunk</strong> : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.</p> <p><strong>Branches</strong> : All parallel developments codes for each ongoing sprint are kept in branches.</p> <p><strong>Tags</strong> : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.</p>
3,687
<p>Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account. </p> <p>I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.</p> <p>I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck.</p> <p>Can anyone shed some light on this?</p> <p>**Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.</p>
<p>This is probably a combination of impersonation and a mismatch of different authentication methods occurring.</p> <p>There are many pieces; I'll try to go over them one by one.</p> <p><strong>Impersonation</strong> is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it "reverts" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute.</p> <p>Now, by default ASP.NET runs a web site under a local account called <strong>ASPNET</strong>. Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle.</p> <p>Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config.</p> <pre><code>&lt;identity impersonate="true" /&gt; </code></pre> <p>If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion.</p> <p>There is one question left: when you use impersonation, <em>which account gets impersonated</em>?</p> <p>Unless you specify the account in the web.config (<a href="http://msdn.microsoft.com/en-us/library/72wdk8cc.aspx" rel="noreferrer">full syntax of the identity element here</a>), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece.</p> <p>The IUSR_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs <strong>if the user could not be authenticated</strong>. That is, the user comes in as an "anonymous".</p> <p>In summary, this is what is happening to you:</p> <p>Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR___ComputerName "guest" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder.</p> <p>Granting IUSR_ComputerName WRITE access to the folder makes your symptoms go away.</p> <p>But that just the symptoms. You need to review <strong>why is the person coming as "Anonymous/Guest"?</strong></p> <p>There are two likely scenarios:</p> <p>a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong.</p> <p>In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access.</p> <p>I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config. </p> <p>b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly)</p> <p>This case is a bit more complicated.</p> <p>You should go to IIS and disable all forms of authentication other than "Anonymous Access". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that.</p> <p>Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource).</p> <p>You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the "anonymous" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion.</p> <p>Good luck!</p>
<p>You can use <strong>Path.GetTempPath()</strong> to find out which directory to which it's trying to write.</p>
7,916
<p>A DB Audit Trail captures the User Last Modified, Modified Date, and Created Date.</p> <p>There are several possible implementations:</p> <ul> <li>SQL Server Triggers</li> <li>Add UserModified, ModifiedDate, CreatedDate columns to the database and include logic in Stored Procedures or Insert, Update statements accordingly.</li> </ul> <p>It would be nice if you include implementation (or link to) in your answer. </p>
<p>Depending on what you're doing, you might want to move the audit out of the data layer into the data access layer. It give you more control.</p> <p>I asked a similar question wrt NHibernate and SqlServer <a href="https://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver">here</a>.</p>
<p>Here is the implementation I use to audit tables: <a href="http://www.simple-talk.com/sql/database-administration/pop-rivetts-sql-server-faq-no.5-pop-on-the-audit-trail/" rel="nofollow noreferrer">Pop Rivett's SQL Server FAQ No.5: Pop on the Audit Trail</a></p>
8,601
<p>I have defined a Java function:</p> <pre><code>static &lt;T&gt; List&lt;T&gt; createEmptyList() { return new ArrayList&lt;T&gt;(); } </code></pre> <p>One way to call it is like so:</p> <pre><code>List&lt;Integer&gt; myList = createEmptyList(); // Compiles </code></pre> <p>Why can't I call it by explicitly passing the generic type argument? :</p> <pre><code>Object myObject = createEmtpyList&lt;Integer&gt;(); // Doesn't compile. Why? </code></pre> <p>I get the error <code>Illegal start of expression</code> from the compiler.</p>
<p>When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . &lt; Type > method();</p> <pre><code>Object list = Collections.&lt;String&gt; emptyList(); </code></pre>
<p>@pauldoo Yes, you are quite right. It is one of the weaknesses with the java generics imho.</p> <p>I response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractCollection.html" rel="nofollow noreferrer">AbstractCollection#toArray</a>(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity.</p> <p>Edit: Added link. Re-edit: Found a bug on SO :)</p> <hr> <p>Follow-up on Cheekysoft: Well, as it is a list of some type that should be returned the corresponding example should look something like:</p> <pre><code>static &lt;T&gt; List&lt;T&gt; createEmptyList( List&lt;T&gt; a ) { return new ArrayList&lt;T&gt;(); } </code></pre> <p>But yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).</p>
4,463
<p>Can the performance of this sequential search algorithm (taken from <a href="http://books.google.co.uk/books?id=to6M9_dbjosC&amp;dq=the+practice+of+programming&amp;pg=PP1&amp;ots=3YH6Ggq0_a&amp;sig=F2-ajdO37xA4iRec2sCyQF55Jjc&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result" rel="noreferrer">The Practice of Programming</a>) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?</p> <pre><code>int lookup(char *word, char*array[]) { int i for (i = 0; array[i] != NULL; i++) if (strcmp(word, array[i]) == 0) return i; return -1; } </code></pre>
<p>Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for example keeping the list sorted and doing a binary search).</p> <p>In general optimizing a given algorithm only gets you so far. Choosing a better algorithm (even if it's not completely optimized) can give you a considerable (order of magnitude) performance improvement.</p>
<pre><code>/* there is no more quick */ int lookup(char *word, char*array[]) { int i; for(i=0; *(array++) != NULL;i++) if (strcmp(word, *array) == 0) return i; return -1; } </code></pre>
3,665
<p>Most program languages have some kind of exception handling; some languages have return codes, others have try/catch, or rescue/retry, etc., each with its own pecularities in readability, robustness, and practical effectiveness in a large group development effort. Which one is the best and why ?</p>
<p>I would say that depends on the nature of your problem. Different problem domains could require almost arbitrary error messages, while other trivial tasks just can return NULL or -1 on error. </p> <p><em>The problem with error return codes is that you're polluting/masking the error since it can be ignored (sometimes without the API client not knowing they should check for the error code). It gives a (reasonably) valid output from the method at hand.</em> </p> <p>Imagine you have an API where you ask for a index key for some map, store it in a list, and then continue running. The API then at a later moment sends a callback, and that method might then traverse the table, using the key which might be -1 in this example (the error code). BOOM, the application crashes as you index to -1 in some array, and those kinds of problems can be very hard to nail down. This is still a trivial example, but it illustrates a problem with error codes. </p> <p>On the other hand, error codes are faster than throwing exceptions, and you might want to use them for frequently accessed method calls - if it is appropriate to return such an error code. I would say that trying to encapsulate these kinds of error codes within a private assembly would be quite OK since you're not exposing those error codes to the client of the API. Always remember to document these methods rigorously since these kinds of application nukes can linger around in an application for a long time since they were triggered before it goes off.</p> <p>Personally, I prefer a mix of them both to some extent. I use exceptions just for that - exceptions - when the program runs into a state which was not expected and needs to inform something has gone way out of plan. I am not a sucker of writing try/catch blocks all over my code, but it's all down to personal preference. </p>
<p>try/catch/finally does the job admirably. </p> <p>It allows the programmer to handle specific conditions as well as general failures gracefully.</p> <p>All said and done I'm sure that each is as good as any other.</p>
9,170
<p>I need to send and receive data over serial connections (RS-232 and RS-422).</p> <p>How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them?</p> <p>In particular I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.</p>
<p>Build a time machine and go back to 1987? Ho ho.</p> <p>Ok, no more snarky comments.</p> <blockquote> <p>How do I figure out what the configuration settings (e.g. baud rate) should be...</p> </blockquote> <p>Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure.</p> <p>Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out.</p> <blockquote> <p>one of the major Unix shells</p> </blockquote> <p>In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there.</p> <p>On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. </p> <p><strike>See: <a href="http://www.easysw.com/~mike/serial/serial.html#3_1" rel="noreferrer">http://www.easysw.com/~mike/serial/serial.html#3_1</a></strike> <strong>(NOT AVAILABLE ANYMORE)</strong></p> <blockquote> <p>but I also have some interest in serial programming using Windows/Hyperterminal.</p> </blockquote> <p>Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days.</p>
<p>I have been using purejavacomm: <a href="http://www.sparetimelabs.com/purejavacomm/index.html" rel="nofollow">It is an implementation of javax.comm written in pure java + JNA</a></p> <p>Unlike rxtx, you don't need to install a dll. It is written in pure Java + JNA, which solved the problem of portability between Windows and Linux for me. It should be easy to port to other OS-es that JNA supports, such as Solaris and FreeBSD, but I haven't tried it. </p> <p>You might expect a pure java library to lag behind a native implementation such as rxtx in performance, but with modern CPU's, the bottleneck is very likely to be the bitrate of your serial port, not CPU cycles. Also, it's much easier to debug than a mixed Java/Native library or pure compiled native code. </p>
2,519
<p>I have lots and lots of data in various structures. Are there any better platforms other than Excel charts which can help me. </p> <p>thanks</p>
<p>What about <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">google charts</a>?</p>
<p>Depends a bit what your objectives are and how technical you are willing to get.</p> <p><a href="http://incanter.org/" rel="nofollow">Incanter</a> is a great toolset that I can heartily recommend (I use it for visualisation in my own projects). It's a statistical computing and visualisation library for Clojure - which in turn is a very flexible and dynamic langauge, good for interactive experiements.</p> <p>I particularly like the DSL for creating charts, e.g. to create a histogram of 1000 samples from the normal distribution you can just do:</p> <pre><code>(view (histogram (sample-normal 1000))) </code></pre>
7,862
<p>I have a new Creality Ender 2 Pro with a Creality 4.2.3 mainboard. I'm attempting to compile Marlin to fix a bug. How can I tell what driver chips I have on this board?</p> <p>I've narrowed it down to likely <code>A4988</code> or <code>TMC2208_STANDALONE</code> or possibly the <code>TMC2225</code>. Strangely Creality only has documentation for the 4.2.2 and the 4.2.7 boards (not 4.2.3)</p> <p>4.2.2 =&gt; TMC2208<br /> 4.2.3 =&gt; ?<br /> 4.2.7 =&gt; TMC2225</p> <p>Some say you can tell the driver just by listening to the noise it makes. <a href="https://youtu.be/4hL-r02w6rM" rel="nofollow noreferrer">Here is a video of the printer running</a>. The motors are nearly silent to my ear.</p> <p><a href="https://i.stack.imgur.com/ALHyb.jpg" rel="nofollow noreferrer" title="Photo of Ender 2 Pro motherboard version 4.2.3"><img src="https://i.stack.imgur.com/ALHyb.jpg" alt="Photo of Ender 2 Pro motherboard version 4.2.3" title="Photo of Ender 2 Pro motherboard version 4.2.3" /></a></p> <p><a href="https://i.stack.imgur.com/xUdVU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xUdVU.jpg" alt="Top corner photo" /></a></p> <p>Resources</p> <ul> <li><a href="https://github.com/Creality3DPrinting/Ender-3/issues/58#issuecomment-842935869" rel="nofollow noreferrer">https://github.com/Creality3DPrinting/Ender-3/issues/58#issuecomment-842935869</a></li> <li>4.2.2 <a href="https://github-repository-files.githubusercontent.com/139231738/7626788?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20211215%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20211215T153407Z&amp;X-Amz-Expires=300&amp;X-Amz-Signature=43dfe1ff5518c5003cf55ade1554caeb5953c733a599db07fb153cc976cebb45&amp;X-Amz-SignedHeaders=host&amp;actor_id=0&amp;key_id=0&amp;repo_id=139231738&amp;response-content-disposition=attachment%3Bfilename%3D1623133432-Creality422-Schematic-2.pdf&amp;response-content-type=application%2Fpdf" rel="nofollow noreferrer">schematic</a></li> <li><a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382" rel="nofollow noreferrer">Marlin Config pull request</a></li> </ul>
<p>According to <a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382" rel="nofollow noreferrer">'The-EG' comment</a> in this GitHub issue, <a href="https://github.com/MarlinFirmware/Configurations/pull/633" rel="nofollow noreferrer">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p> <ol> <li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p> </li> <li><p>Look for a marking in Sharpie on the SD Card reader</p> <pre><code>C = HR4998 E = A4988 A = TMC2208 B = TMC2209 H = TMC2225 </code></pre> </li> <li><p>Remove the heat sync</p> <p><a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295" rel="nofollow noreferrer">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p> <p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p> <p><a href="https://i.stack.imgur.com/0o5mK.jpg" rel="nofollow noreferrer" title="Closeup of MS35775 on board"><img src="https://i.stack.imgur.com/0o5mK.jpg" alt="Closeup of MS35775 on board" title="Closeup of MS35775 on board" /></a></p> </li> </ol>
<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p> <ul> <li>2-Phase stepping motor peak current of 2A</li> <li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li> <li>Internal 256 micro steps</li> <li>Quiet mode</li> <li>Fast mode</li> <li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li> <li>Voltage range 4.75 ~ 36V</li> <li>When the motor is still, it will enter into the power saving mode automatically</li> <li>Internal resistor mode is optional (no need for external sense resistor)</li> <li>Single wire UART bus and OTP control</li> <li>QFN28 package</li> </ul>
2,071
<p>I think this is specific to IE 6.0 but...</p> <p>In JavaScript I add a <code>div</code> to the DOM. I assign an <code>id</code> attribute. When I later try to pick up the <code>div</code> by the <code>id</code> all I get is <code>null</code>.</p> <p>Any suggestions?</p> <p>Example:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>Alert prints <code>"::null"</code></p> <p>Seems to work fine in Firefox 2.0+</p>
<p>In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via <code>getElementById()</code>), you also need to use a lower-case attribute name in order for IE6 to recognize it as the <code>id</code>:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("id", "obj_1000"); document.body.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("id") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>...responds as expected:</p> <pre><code>Added:obj_1000:obj_1000:[object] </code></pre> <hr> <p>According to the <a href="http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx" rel="noreferrer">MSDN documentation</a> for <code>setAttribute()</code>, up to IE8 there is an optional <em>third parameter</em> that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is...</p>
<p>newDiv.setAttribute( "ID", "obj_1000" );</p> <p>should be</p> <p>newDiv.id = "obj_1000";</p>
7,609
<p>I was working with quality yesterday doing some formal testing. In their procedure they were verifying all files on the test machine were pulled from the release. The way they were verifying these files were the same was by checking the size and the date/time stamp windows put on them in Windows Explorer. These happened to be off for another reason which I was able to find out why. </p> <p>Is this a valid way to verify a file is the same? I didn't think so and started to argue, but I am younger here so thought I shouldn't push it too far. I wanted to argue they should do a binary compare on the file to verify its contents are exact. In my experience time/date stamps and size attributes don't always act as expected. Any thoughts???</p>
<p>The only 100% way to figure out if two files are equal is to do a binary comparison of the two.</p> <p>If you can live with the risk of false positives (ie. two files which aren't 100% identical but your code says they are), then the digest and checksum algorithms can be used to lessen the work, particularly if the files lives on two different machines with less than optimal bandwidth so that a binary comparison is infeasible.</p> <p>The digest and checksum algorithms all have chances of false positives, but the exact chance varies with the algorithm. General rule is that the more crypto-made it is, and the more bits it outputs, the less chance of a false positive.</p> <p>Even the CRC-32 algorithm is fairly good to use and it should be easy to find code examples on the internet that implements it.</p> <p>If you only do a size/timestamp comparison then I'm sorry to say that this is easy to circumvent and won't actually give you much of a certainty that the files are the same or different.</p> <p>It depends though, if you know that in your world, timestamps are kept, and only changed when the file is modified, then you can use it, otherwise it holds no guarantee.</p>
<p>You should do a CRC check on each file... from the wiki:</p> <p><a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check" rel="nofollow noreferrer">Cyclic redundancy check</a>, a type of hash function used to produce a checksum, in order to detect errors in transmission or storage.</p> <p>It produces an almost unique value based on the contents of the file.</p>
2,668
<p>In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 * 16), is a DWORD still 32-bit on 64-bit architectures?</p>
<p>Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.</p> <p>In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.</p> <p>You can find the official list here: <a href="http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx</a></p> <p>All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).</p>
<p>Windows API defines DWORD sizes as follows:</p> <ul> <li><strong>x86:</strong> sizeof(DWORD) = <strong>4</strong></li> <li><strong>x64:</strong> sizeof(DWORD) = <strong>4</strong></li> </ul>
6,047
<p>I have a friend that has a little bit of a holiday coming up and they want ideas on what they should do during the holiday, I plan to suggest programming to them, what are the pros and cons that I need to mention?</p> <p>I'll add to the list below as people reply, I apologise if I duplicate any entries.</p> <p><strong>Pros I have so far</strong></p> <ol> <li>Minimal money requirement (they already have a computer)</li> <li>Will help them to think in new ways</li> <li>(Rob Cooper) Great challenge, every day really is a fresh challenge in some way, shape or form. Not many jobs can truly offer that.</li> <li>(Rob Cooper) I like the way it makes me think.. I look at EVERYTHING more logically as my skills improve.. This helps with general living as well as programming.</li> <li>(Rob Cooper) Money is/can be pretty good.</li> <li>(Rob Cooper) Its a pretty portable trade.. With collaboration tech as it is, you can pretty much work anywhere in the world so long as you have an Internet connection.</li> <li>(Rob Cooper) It's an exciting industry to work in, theres massive amounts of tech to work and play with!</li> <li>(Quarrelsome) Jetpacks. Programming is Technology and the more time we spend with technology the closer we get to having Jetpacks. (<em>Teifion: This is a really cool analogy!</em>)</li> <li>(Saj) Profitable way of Exercising Brain Muscles.</li> <li>(Saj) It makes you look brilliant to some audience.</li> <li>(Saj) Makes you tech-smart.</li> <li>(Saj) Makes you eligible to the future world.</li> <li>(Saj) It's easy, fun, not in a math way..</li> <li>(kiwiBastard) If the person likes problem solving then programming is no better example.</li> <li>(kiwiBastard) Brilliant sense of achivement when you can interact with something you have designed and coded</li> <li>(kiwiBastard) Great way to meet chicks/chaps - erm, maybe not that one (<em>Teifion: I dunno where you do programming but I want to come visit some time</em>)</li> <li>(epatel) Learning how to program is like learning spell casting at Hogwarts . The computer will be your servant forever...</li> </ol> <p><strong>Cons I have so far</strong></p> <ol> <li>Can be frustrating when it's not working</li> <li>Not physical exercise</li> <li>(Rob Cooper) There are a lot of people doing it just for the money. They have no love for the craft and just appear lazy, annoying and sometimes it can really grind my gears seeing an industry and workforce I enjoy so much being diluted with crap. Which can often reflect badly on all of us.</li> <li>(Rob Cooper) Not so sure about the initial cost.. Yeah you can get started with Java or something at low cost, but for me, locally, the vast demand is for .NET developers, which can be costly getting up and running with. However, this is rapidly/has not becoming the case with the amount of work put in by MS with releasing pretty damn good Express editions of their main development product line.</li> <li>(Rob Cooper) Its a lifelong career.. I truly feel you never really become a "master" by nature of the industry, you stop for 1-2 years. You're behind the times.. Some people do not like the pace.</li> <li>(Rob Cooper) Some geeks can be hard to work with.. While I think the general geek movement is really changing for the better, you will always have the classic "I am more intelligent than you" geeks that can really just be a pain in the ass for all!</li> <li>(Saj) Can cause virtual damage.</li> <li>(Saj) Can make one throw their computer away.</li> <li>(Saj) Can make one only virtually available to the world.</li> </ol>
<h2>I do it for the ladies :D</h2> <p>Seriously though, for me</p> <h3>Pro's</h3> <ul> <li>Great challenge, every day really is a fresh challenge in some way, shape or form. Not many jobs can truly offer that.</li> <li>I like the way it makes me think.. I look at EVERYTHING more logically as my skills improve.. This helps with general living as well as programming.</li> <li>Money is/can be pretty good.</li> <li>Its a pretty portable trade.. With collaboration tech as it is, you can pretty much work anywhere in the world so long as you have an Internet connection.</li> <li>It's an exciting industry to work in, theres massive amounts of tech to work and play with!</li> </ul> <h3>Cons (some of these can easily be Pro's too)</h3> <ul> <li>There are a lot of people doing it <em>just</em> for the money. They have no love for the <strong>craft</strong> and just appear lazy, annoying and sometimes it can really grind my gears seeing an industry and workforce I enjoy so much being diluted with crap. Which can often reflect badly on all of us.</li> <li>Not so sure about the initial cost.. Yeah you can get started with Java or something at low cost, but for me, locally, the vast demand is for .NET developers, which can be costly getting up and running with. However, this is rapidly/has not becoming the case with the amount of work put in by MS with releasing pretty damn good Express editions of their main development product line.</li> <li>Its a lifelong career.. I truly feel you never really become a &quot;master&quot; by nature of the industry, you stop for 1-2 years. You're behind the times.. Some people do not like the pace.</li> <li>Some geeks can be hard to work with.. While I think the general geek movement is really changing for the better, you will <em>always</em> have the classic &quot;I am more intelligent than you&quot; geeks that can really just be a pain in the ass for all!</li> </ul>
<p>You could tell him how into programmers girls are.. you know, lie.</p>
3,205
<p>Every time I publish the application in <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?</p>
<p>We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's <code>AfterCompile</code> target to trigger the ClickOnce publish with our preferred version number:</p> <pre class="lang-xml prettyprint-override"><code>&lt;MSBuild Projects="$(SolutionRoot)\MyProject\Myproject.csproj" Properties="PublishDir=$(OutDir)\myProjectPublish\; ApplicationVersion=$(PublishApplicationVersion); Configuration=$(Configuration);Platform=$(Platform)" Targets="Publish" /&gt; </code></pre> <p>The <code>PublishApplicationVersion</code> variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use <a href="http://msdn.microsoft.com/en-us/library/t9883dzc.aspx" rel="nofollow noreferrer">your own custom task</a> or an <a href="http://msbuildtasks.tigris.org/" rel="nofollow noreferrer">existing solution</a> to get the version number from the AssemblyInfo file.</p> <p>This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine.</p> <p>I'm sure other <a href="http://en.wikipedia.org/wiki/Continuous_integration" rel="nofollow noreferrer">continuous integration</a> (CI) solutions can handle this similarly.</p> <hr> <p><strong>Edit:</strong> Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML.</p> <p>However, you may also consider changing your error reporting to include the ClickOnce publish version too:</p> <pre class="lang-cs prettyprint-override"><code>if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) { Debug.WriteLine(System.Deployment.Application.ApplicationDeployment. CurrentDeployment.CurrentVersion); } </code></pre>
<p>You'll probably need to create a piece of code that updates AssemblyInfo.cs according to the version number stored in the .csproj file. (The ClickOnce deploy version is stored inside an XML tag.)</p> <p>You'd then change your .csproj file to run this bit of code when Publish|Release build is performed. The MSBuild folks have blogged about how to perform custom actions during certain build types; check the <a href="http://blogs.msdn.com/msbuild/" rel="nofollow noreferrer">MSBuild team blog</a>.</p>
6,623
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
<p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.</p> <p>For example:</p> <pre><code>job={} job['jobid'], job['label'], job['username']=&lt;querycode&gt; </code></pre>
<p>How about this:</p> <pre><code>class TypedTuple: def __init__(self, fieldlist, items): self.fieldlist = fieldlist self.items = items def __getattr__(self, field): return self.items[self.fieldlist.index(field)] </code></pre> <p>You could then do:</p> <pre><code>j = TypedTuple(["jobid", "label", "username"], job) print j.jobid </code></pre> <p>It should be easy to swap <code>self.fieldlist.index(field)</code> with a dictionary lookup later on... just edit your <code>__init__</code> method! Something like Staale does.</p>
6,308
<p>What .NET namespace or class includes both Context.Handler and Server.Transfer?</p> <p>I think one may include both and my hunt on MSDN returned null. </p>
<p>System.Web.</p> <pre><code>HttpContext.Current.Handler HttpContext.Current.Request.Server.Transfer </code></pre>
<blockquote> <p>Hmmmm, I talking about them as they are implemented here:</p> <p><a href="http://blog.benday.com/archive/2008/03/31/23176.aspx" rel="nofollow noreferrer">http://blog.benday.com/archive/2008/03/31/23176.aspx</a></p> <p>(at least Context.Handler there)</p> <p>I am still having trouble in VS making that reference.</p> </blockquote> <p>Context.Handler is an instance of an HttpContext.</p> <p>HttpContext exposes the CURRENT instance for the request under the HttpContext.Current property, however the current context can also be passed in HTTPHandlers in the ProcessRequest method:</p> <pre><code>void ProcessRequest(HttpContext context) </code></pre>
6,083
<p>Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:</p> <pre><code>Typedef myGenDef = &lt; Object1, Object2 &gt;; HashMap&lt; myGenDef &gt; hm = new HashMap&lt; myGenDef &gt;(); for (Entry&lt; myGenDef &gt; ent : hm..entrySet()) { . . . } </code></pre>
<p>There's the <a href="http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html" rel="nofollow noreferrer">pseudo-typedef antipattern</a>... </p> <pre><code>class StringList extends ArrayList&lt;String&gt; { } </code></pre> <p>Good stuff, drink up! ;-)</p> <p>As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.</p>
<p>No. Though, groovy, a JVM language, is dynamically typed and would let you write:</p> <pre><code>def map = new HashMap&lt;complicated generic expression&gt;(); </code></pre>
5,900
<p>I have an MFC application compiled with /clr and I'm trying to implement a final handler for otherwise un-caught managed exceptions. For native exceptions, overriding <code>CWinApp::ProcessWndProcException</code> works.</p> <p>The two events suggested in Jeff's <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">CodeProject article</a>,<code>Application.ThreadException</code> and <code>AppDomain.CurrentDomain.UnhandledException</code>, are not raised.</p> <p>Can anyone suggest a way to provide a final managed exception handler for a mixed executable?</p> <hr> <p>Update:</p> <p>It appears that these exception handlers are only triggered downstream of <code>Application.Run</code> or similar (there's a worker thread flavor, can't remember the name.) If you want to truly globally catch a managed exception you do need to install an SEH filter. You're not going to get a <code>System.Exception</code> and if you want a callstack you're going to have to roll your own walker.</p> <p>In an MSDN forum question on this topic it was suggested to override a sufficiently low-level point of the main MFC thread in a <code>try ... catch (Exception^)</code>. For instance, <code>CWinApp::Run</code>. This may be a good solution but I haven't looked at any perf or stability implications. You'll get a chance to log with a call stack before you bail and you can avoid the default windows unahndled exception behavior.</p>
<p>Taking a look around the internets, you'll find that you need to install a filter to get the unmanaged exceptions passing the filters on their way to your AppDomain. From <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12/30/clr-and-unhandled-exception-filters.aspx" rel="nofollow noreferrer">CLR and Unhandled Exception Filters</a>:</p> <blockquote> <p>The CLR relies on the SEH unhandled exception filter mechanism to catch unhandled exceptions.</p> </blockquote>
<p>Using those two exception handlers should work. Are you sure you've added them in a place where they're going to be called and properly set (ie, in your application's <em>managed</em> entry point -- you did put one in, right?)</p>
3,019
<p>How does the comma operator work in C++?</p> <p>For instance, if I do:</p> <pre><code>a = b, c; </code></pre> <p>Does a end up equaling b or c? </p> <p>(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)</p> <p><strong>Update:</strong> This question has exposed a nuance when using the comma operator. Just to document this:</p> <pre><code>a = b, c; // a is set to the value of b! a = (b, c); // a is set to the value of c! </code></pre> <p>This question was actually inspired by a typo in code. What was intended to be</p> <pre><code>a = b; c = d; </code></pre> <p>Turned into</p> <pre><code>a = b, // &lt;- Note comma typo! c = d; </code></pre>
<p>It would be equal to <code>b</code>.</p> <p>The comma operator has a lower precedence than assignment.</p>
<p><strong>First things first:</strong> Comma is actually not an operator, for the compiler it is just a token which gets a meaning <em>in context</em> with other tokens.</p> <h2>What does this mean and why bother?</h2> <p><strong>Example 1:</strong></p> <p>To understand the difference between the meaning of the same token in a different context we take a look at this example:</p> <pre><code>class Example { Foo&lt;int, char*&gt; ContentA; } </code></pre> <p>Usually a C++ beginner would think that this expression could/would compare things but it is absolutly wrong, the meaning of the <code>&lt;</code>, <code>&gt;</code> and <code>,</code> tokens depent on the context of use.</p> <p>The correct interpretation of the example above is of course that it is an instatiation of a template.</p> <p><strong>Example 2:</strong></p> <p>When we write a typically for loop with more than one initialisation variable and/or more than one expressions that should be done after each iteration of the loop we use comma too:</p> <pre><code>for(a=5,b=0;a&lt;42;a++,b--) ... </code></pre> <p>The meaning of the comma depends on the context of use, here it is the context of the <code>for</code> construction.</p> <h2>What does a comma in context actually mean?</h2> <p>To complicate it even more (as always in C++) the comma operator can itself be overloaded (thanks to <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> for pointing that out).</p> <p>To come back to the question, the Code</p> <pre><code>a = b, c; </code></pre> <p>means for the compiler something like</p> <pre><code>(a = b), c; </code></pre> <p>because the <a href="http://en.cppreference.com/w/cpp/language/operator_precedence" rel="nofollow noreferrer">priority</a> of the <code>=</code> token/operator is higher than the priority of the <code>,</code> token.</p> <p>and this is interpreted in context like</p> <pre><code>a = b; c; </code></pre> <p>(note that the interpretation depend on context, here it it neither a function/method call or a template instatiation.)</p>
7,774
<p>Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests.</p> <p>Server Side, you still kept all the individual .js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc.</p> <p>In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please?</p>
<p>It's called <a href="http://msdn.microsoft.com/en-us/library/cc837190.aspx" rel="noreferrer">Script Combining</a>. There is a video example from asp.net explaining it <a href="http://www.asp.net/Learn/3.5-SP1/video-296.aspx" rel="noreferrer">here</a>.</p>
<p>you can find <a href="http://www.codeproject.com/KB/aspnet/HttpCombine.aspx" rel="nofollow noreferrer">here</a> an usefull article for it</p>
7,027
<p>I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.</p> <p>I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it <em>does</em> show the symbol.</p> <p>I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.</p> <p>What else could it be, and how can I try to fix?</p> <p>Here's the excerpt from running make test:</p> <pre><code>PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/01basic...........1/4 # Failed test 'use SGML::Parser::OpenSP;' # at t/01basic.t line 14. # Tried to use 'SGML::Parser::OpenSP'. # Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication # Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle # Expected in: dynamic lookup # at (eval 3) line 2 # Compilation failed in require at (eval 3) line 2. # BEGIN failed--compilation aborted at (eval 3) line 2. </code></pre>
<p>If you use the Settings for the project, you can mark each setting as either application or user.</p> <p>If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user.</p> <p>Code project has a really detailed <a href="http://www.codeproject.com/KB/dotnet/user_settings.aspx" rel="nofollow noreferrer">article</a> on saving all types of settings.</p>
<p>app.config isn't what you want to use for user-tweakable data, as it'll be stored somewhere in Program Files (which the user shouldn't have write permissions to). Instead, settings marked with <code>a UserScopedSettingAttribute</code> will end up in a user-scoped .config file somewhere in %LocalAppData%.</p> <p>I found the best way to learn this stuff was to mess with the Visual Studio "Settings" tab (on your project's property pages), then look at the code that it generates and look in %LocalAppData% to see the file that it generates.</p>
5,699
<p>I took the plunge and bought a resin printer. I was wondering if I could use full strength home-brew vodka at 90 % instead of using isopropyl alcohol before anything is added to clean prints with?</p> <p>I cannot seem to find anywhere or anyone that has tried this.</p>
<p>Isopropyl-Alcohol - Propan-2-ol - and Ethyl alcohol - Ethan-1-ol - are different chemically. As a secondary alcohol, Propan-2-ol has quite different solubility of different materials than ethyl-alcohol.</p> <p>Now, let's look at home made alcoholic destillate. That stuff is, if done in one refraction and without tossing the first low temperature part, some percentages Metanol, Ethyl alcohol and maybe some water. That has not the same solvent properties as Propan-2-ol.</p> <p>While it <em>might</em> work, nobody will sign a guarantee that it doesn't negatively impact your print.</p>
<p>Some manufacturers do recommend ethanol and not isopropanol. The problem would be getting relatively pure ethanol through distillation. When distilling you will get different fractions which may be full of methanol or water. You will probably need to do multiple runs. You could just buy some 95% ethanol and distill it once it gets dirty or leave it in the sun to cure the resin and filter it out.</p>
1,746
<p>Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time. </p> <p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p>
<p>There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.</p> <p>In Java you could use the <code>inDaylightTime</code> method of the <a href="http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html" rel="nofollow noreferrer">TimeZone</a> class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use <a href="http://joda-time.sourceforge.net/" rel="nofollow noreferrer">Joda Time</a>. I can't see a clean way of finding this out using just the standard libraries.</p> <p>The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)</p> <pre><code>import org.joda.time.DateTime; import org.joda.time.DateTimeZone; public class App { public static void main(String[] args) { DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam"); System.out.println(startDST(dtz, 2008)); System.out.println(endDST(dtz, 2008)); } public static DateTime startDST(DateTimeZone zone, int year) { return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis())); } public static DateTime endDST(DateTimeZone zone, int year) { return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis())); } } </code></pre>
<p>The <a href="https://stackoverflow.com/a/154765/642706">Answer by Richters</a> is correct and should be accepted.</p> <p>As Richters noted, there is no logic to <a href="https://en.wikipedia.org/wiki/Daylight_saving_time" rel="nofollow noreferrer">Daylight Saving Time (DST)</a> or other anomalies. Politicians arbitrarily redefine the <a href="https://en.wikipedia.org/wiki/UTC_offset" rel="nofollow noreferrer">offset-from-UTC</a> used in their <a href="https://en.wikipedia.org/wiki/Time_zone" rel="nofollow noreferrer">time zones</a>. They make these changes often with little forewarning, or even no warning at all as <a href="http://www.bbc.com/news/world-asia-44010705" rel="nofollow noreferrer">North Korea did</a> a few weeks ago.</p> <h1>java.time</h1> <p>Here are some further thoughts, and example code using the modern <em>java.time</em> classes that succeeded the Joda-Time classes shown in his Answer.</p> <p>These changes are tracked in a list maintained by <a href="https://en.wikipedia.org/wiki/ICANN" rel="nofollow noreferrer">ICANN</a>, known as <a href="https://en.wikipedia.org/wiki/Tz_database" rel="nofollow noreferrer"><em>tzdata</em></a>, formerly known as the Olson Database. Your Java implementation, host operating system, and database system likely all have their own copies of this data which must be replaced as needed when changes are mode to zones you care about. There is no logic to these changes, so there is no way to predict the changes programmatically. Your code must call upon a fresh copy of <em>tzdata</em>.</p> <blockquote> <p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p> </blockquote> <p>Actually, you need not determine the point of the cut-over. A good date-time library handles that for you automatically. </p> <p>Java has the best such library, the industry-leading <em>java.time</em> classes. When you ask for a time-of-day on a certain date in a certain region (time zone), if that time-of-day is no valid an adjustment is made automatically. Read the documentation for the <code>ZonedDateTime</code> to understand the algorithm used in that adjustment.</p> <pre><code>ZoneId z = ZoneId.of( "America/Montreal" ); LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 11 ); // 2018-03-11. LocalTime lt = LocalTime.of( 2 , 0 ); // 2 AM. ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ); </code></pre> <p>Notice the result is 3 AM rather than the 2 AM requested. There was no 2 AM on that date in that zone. So java.time adjusted to 3 AM as the clock “Springs ahead” an hour.</p> <blockquote> <p>zdt.toString(): 2018-03-11T03:00-04:00[America/Montreal]</p> </blockquote> <p>If you feel the need to investigate the rules defined for a time zone, use the <a href="https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneRules.html" rel="nofollow noreferrer"><code>ZoneRules</code></a> class.</p> <p>Get the amount of DST shift used in the present moment.</p> <pre><code>Duration d = z.getRules().getDaylightSavings​( Instant.now() ) ; </code></pre> <p>Get the next planned change, represented as a <a href="https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneOffsetTransition.html" rel="nofollow noreferrer"><code>ZoneOffsetTransition</code></a> object.</p> <pre><code>ZoneId z = ZoneId.of( "America/Montreal" ); ZoneOffsetTransition t = z.getRules().nextTransition( Instant.now() ); String output = "For zone: " + z + ", on " + t.getDateTimeBefore() + " duration change: " + t.getDuration() + " to " + t.getDateTimeAfter(); </code></pre> <blockquote> <p>For zone: America/Montreal, on 2018-11-04T02:00 duration change: PT-1H to 2018-11-04T01:00</p> </blockquote> <p>Specify a <a href="https://en.wikipedia.org/wiki/List_of_tz_zones_by_name" rel="nofollow noreferrer">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href="https://en.wikipedia.org/wiki/America/Montreal" rel="nofollow noreferrer"><code>America/Montreal</code></a>, <a href="https://en.wikipedia.org/wiki/Africa/Casablanca" rel="nofollow noreferrer"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p> <hr> <h1>About <em>java.time</em></h1> <p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="nofollow noreferrer"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href="https://en.wikipedia.org/wiki/Legacy_system" rel="nofollow noreferrer">legacy</a> date-time classes such as <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Date.html" rel="nofollow noreferrer"><code>java.util.Date</code></a>, <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html" rel="nofollow noreferrer"><code>Calendar</code></a>, &amp; <a href="http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html" rel="nofollow noreferrer"><code>SimpleDateFormat</code></a>.</p> <p>The <a href="http://www.joda.org/joda-time/" rel="nofollow noreferrer"><em>Joda-Time</em></a> project, now in <a href="https://en.wikipedia.org/wiki/Maintenance_mode" rel="nofollow noreferrer">maintenance mode</a>, advises migration to the <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="nofollow noreferrer">java.time</a> classes.</p> <p>To learn more, see the <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="nofollow noreferrer"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow noreferrer">JSR 310</a>.</p> <p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="nofollow noreferrer">JDBC driver</a> compliant with <a href="http://openjdk.java.net/jeps/170" rel="nofollow noreferrer">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p> <p>Where to obtain the java.time classes? </p> <ul> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="nofollow noreferrer"><strong>Java SE 8</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9" rel="nofollow noreferrer"><strong>Java SE 9</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10" rel="nofollow noreferrer"><strong>Java SE 10</strong></a>, and later <ul> <li>Built-in. </li> <li>Part of the standard Java API with a bundled implementation.</li> <li>Java 9 adds some minor features and fixes.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6" rel="nofollow noreferrer"><strong>Java SE 6</strong></a> and <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7" rel="nofollow noreferrer"><strong>Java SE 7</strong></a> <ul> <li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href="http://www.threeten.org/threetenbp/" rel="nofollow noreferrer"><strong><em>ThreeTen-Backport</em></strong></a>.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="nofollow noreferrer"><strong>Android</strong></a> <ul> <li>Later versions of Android bundle implementations of the java.time classes.</li> <li>For earlier Android (&lt;26), the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="nofollow noreferrer"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href="http://www.threeten.org/threetenbp/" rel="nofollow noreferrer"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href="http://stackoverflow.com/q/38922754/642706"><em>How to use ThreeTenABP…</em></a>.</li> </ul></li> </ul> <p>The <a href="http://www.threeten.org/threeten-extra/" rel="nofollow noreferrer"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="nofollow noreferrer"><code>Interval</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="nofollow noreferrer"><code>YearWeek</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html" rel="nofollow noreferrer"><code>YearQuarter</code></a>, and <a href="http://www.threeten.org/threeten-extra/apidocs/index.html" rel="nofollow noreferrer">more</a>.</p>
9,640
<p>I'm working on a visual studio 2005 vb.net windows forms project that's been around for several years. It's full of default textboxes, labels, dropdowns, datagrids, datetime pickers -- all the standard stuff. The end result is a very gray, old-looking project.</p> <p>What would be the best approach to making this project look fresh and snazzy? I'd rather not rewrite the entire solution with all brand new forms objects, but would that be avoidable?</p>
<p>I was actually just sprucing up a dialog today. A lot of it depends on what kind of application you have, and what OS it is running on. A couple of these tips will certainly go a long way to jazzing things up.</p> <ol> <li><p>Ensure adequate spacing between controls — don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space.</p></li> <li><p>Put in some new 3D and glossy images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are <a href="http://www.glyfx.com/" rel="noreferrer">GlyFX</a> and <a href="http://www.iconexperience.com/" rel="noreferrer">IconExperience</a>. You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy.</p></li> <li><p>Try a different font. Tahoma is a good one. Often times the default font is MS Sans Serif. You can do better. Avoid Times New Roman and Comic Sans though. Also avoid large blocks of bold — use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart. </p></li> <li><p>Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slope. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors.</p></li> <li><p>Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface Design. I actually have a video of it and might be able to post it online with a little clean-up.</p></li> <li><p>Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from <a href="http://www.devexpress.com/" rel="noreferrer">DevExpress</a> or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden! </p></li> <li><p>You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI.</p></li> <li><p>Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency.</p></li> </ol> <p>Some apps lend themselves to full blown skinning, while others don't. Generally you don't want anything flashy that gets used a lot.</p>
<p>This depends on how the existing "gray old looking" project is structured in terms of code. For example, is data access code separated from the UI in a Data Access Layer, is the business logic in a Business Logic Layer? If yes, then cleaning the UI for a snazzy look should be relatively simple.</p> <p>If everything is all there in the "Button Click" event, then a rewrite is the only way in my humble opinion as otherwise it will just be too time consuming trying to work with the existing code base.</p> <p>Cheers</p>
5,376
<p>Do you use ILMerge? Do you use ILMerge to merge multiple assemblies to ease deployment of dll's? Have you found problems with deployment/versioning in production after ILMerging assemblies together?</p> <p>I'm looking for some advice in regards to using ILMerge to reduce deployment friction, if that is even possible.</p>
<p>I use ILMerge for almost all of my different applications. I have it integrated right into the release build process so what I end up with is one exe per application with no extra dll's. </p> <p>You can't ILMerge any C++ assemblies that have native code. You also can't ILMerge any assemblies that contain XAML for WPF (at least I haven't had any success with that). It complains at runtime that the resources cannot be located.</p> <p>I did write a wrapper executable for ILMerge where I pass in the startup exe name for the project I want to merge, and an output exe name, and then it reflects the dependent assemblies and calls ILMerge with the appropriate command line parameters. It is much easier now when I add new assemblies to the project, I don't have to remember to update the build script.</p>
<p>It seems to me like the #1 ILMerge Best Practice is Don't Use ILMerge. Instead, use <a href="http://www.red-gate.com/products/smartassembly/index.htm" rel="nofollow noreferrer">SmartAssembly</a>. One reason for this is that the #2 ILMerge Best Practice is to always run PEVerify after you do an ILMerge, because ILMerge does not guarantee it will correctly merge assemblies into a valid executable.</p> <p>Other ILMerge disadvantages:</p> <ul> <li>when merging, it strips XML Comments (if I cared about this, I would use an obfuscation tool)</li> <li>it doesn't correctly handle creating a corresponding .pdb file</li> </ul> <p>Another tool worth paying attention to is Mono.Cecil and the Mono.Linker [2] tool.</p> <p>[2]: http:// www.mono-project.com/Linker</p>
3,080
<p>This came to my mind after I learned the following from <a href="http://www.stackoverflow.com/questions/8941/generic-type-checking">this question</a>:</p> <pre><code>where T : struct </code></pre> <p>We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.</p> <p>Some of us even mastered the stuff like <a href="http://msdn.microsoft.com/en-us/library/512aeb7t.aspx" rel="nofollow noreferrer">Generics</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer">anonymous types</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambdas</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397676.aspx" rel="nofollow noreferrer">LINQ</a>, ...</p> <p>But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?</p> <h1>Here are the revealed features so far:</h1> <p><br /></p> <h2>Keywords</h2> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer"><code>yield</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li> <li><code>var</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li> <li><code>using()</code> statement by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li> <li><code>readonly</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li> <li><code>as</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041">Mike Stone</a></li> <li><code>as</code> / <code>is</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070">Ed Swangren</a></li> <li><code>as</code> / <code>is</code> (improved) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092">Rocketpants</a></li> <li><code>default</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639">deathofrats</a></li> <li><code>global::</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152">pzycoman</a></li> <li><code>using()</code> blocks by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316">AlexCuse</a></li> <li><code>volatile</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691">Jakub Šturc</a></li> <li><code>extern alias</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926">Jakub Šturc</a></li> </ul> <h2>Attributes</h2> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer"><code>DefaultValueAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer"><code>ObsoleteAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" rel="nofollow noreferrer"><code>DebuggerDisplayAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048">Stu</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer"><code>DebuggerBrowsable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer"><code>DebuggerStepThrough</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474">bdukes</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx" rel="nofollow noreferrer"><code>ThreadStaticAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer"><code>FlagsAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752">Martin Clarke</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/4xssyw96.aspx" rel="nofollow noreferrer"><code>ConditionalAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342">AndrewBurns</a></li> </ul> <h2>Syntax</h2> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer"><code>??</code></a> (coalesce nulls) operator by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li> <li>Number flaggings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038">Nick Berardi</a></li> <li><code>where T:new</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067">Lars Mæhlum</a></li> <li>Implicit generics by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li> <li>One-parameter lambdas by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li> <li>Auto properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li> <li>Namespace aliases by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li> <li>Verbatim string literals with @ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114">Patrick</a></li> <li><code>enum</code> values by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738">lfoust</a></li> <li>@variablenames by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088">marxidad</a></li> <li><code>event</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277">marxidad</a></li> <li>Format string brackets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321">Portman</a></li> <li>Property accessor accessibility modifiers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715">xanadont</a></li> <li>Conditional (ternary) operator (<code>?:</code>) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450">JasonS</a></li> <li><code>checked</code> and <code>unchecked</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991">Binoj Antony</a></li> <li><code>implicit and explicit</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470">Flory</a></li> </ul> <h2>Language Features</h2> <ul> <li>Nullable types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055">Brad Barker</a></li> <li>Anonymous types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li> <li><code>__makeref __reftype __refvalue</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125">Judah Himango</a></li> <li>Object initializers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547">lomaxx</a></li> <li>Format strings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207">David in Dakota</a></li> <li>Extension Methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li> <li><code>partial</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395">Jon Erickson</a></li> <li>Preprocessor directives by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482">John Asbeck</a></li> <li><code>DEBUG</code> pre-processor directive by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081">Robert Durgin</a></li> <li>Operator overloading by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914">SefBkn</a></li> <li>Type inferrence by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811">chakrit</a></li> <li>Boolean operators <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">taken to next level</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148">Rob Gough</a></li> <li>Pass value-type variable as interface without boxing by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538">Roman Boiko</a></li> <li>Programmatically determine declared variable type by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985">Roman Boiko</a></li> <li>Static Constructors by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321">Chris</a></li> <li>Easier-on-the-eyes / condensed ORM-mapping using LINQ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781">roosteronacid</a></li> <li><code>__arglist</code> by <a href="https://stackoverflow.com/a/1836944/171819">Zac Bowling</a></li> </ul> <h2>Visual Studio Features</h2> <ul> <li>Select block of text in editor by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477" title="block text selecting with alt key">Himadri</a></li> <li>Snippets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a> </li> </ul> <h2>Framework</h2> <ul> <li><code>TransactionScope</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li> <li><code>DependantTransaction</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li> <li><code>Nullable&lt;T&gt;</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118">IainMH</a></li> <li><code>Mutex</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181">Diago</a></li> <li><code>System.IO.Path</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401">ageektrapped</a></li> <li><code>WeakReference</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723">Juan Manuel</a></li> </ul> <h2>Methods and Properties</h2> <ul> <li><code>String.IsNullOrEmpty()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li> <li><code>List.ForEach()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li> <li><code>BeginInvoke()</code>, <code>EndInvoke()</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581">Will Dean</a></li> <li><code>Nullable&lt;T&gt;.HasValue</code> and <code>Nullable&lt;T&gt;.Value</code> properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393">Rismo</a></li> <li><code>GetValueOrDefault</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158">John Sheehan</a></li> </ul> <h2>Tips &amp; Tricks</h2> <ul> <li>Nice method for event handlers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282">Andreas H.R. Nilsson</a></li> <li>Uppercase comparisons by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137">John</a></li> <li>Access anonymous types without reflection by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441">dp</a></li> <li>A quick way to lazily instantiate collection properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945">Will</a></li> <li>JavaScript-like anonymous inline-functions by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130">roosteronacid</a></li> </ul> <h2>Other</h2> <ul> <li>netmodules by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a> </li> <li><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886">Duncan Smart</a> </li> <li><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293">Joel Coehoorn</a></li> </ul>
<p>This isn't C# per se, but I haven't seen anyone who really uses <code>System.IO.Path.Combine()</code> to the extent that they should. In fact, the whole Path class is really useful, but <strong>no one uses it!</strong></p> <p>I'm willing to bet that every production app has the following code, even though it shouldn't:</p> <pre><code>string path = dir + "\\" + fileName; </code></pre>
<p>I don't know if this is a hidden feature (""). Any string function.</p>
3,052
<p>I am currently in the process of restructuring my local Subversion repository by adding some new projects and merging legacy code and data from a couple of older repositories into it. </p> <p>When I have done this in the past I have usually put the legacy code in a dedicated "legacy" folder, as not to "disturb" the new and "well-structured" code tree. However, in the spirit of refactoring I feel this is somewhat wrong. In theory, the legacy code will be refactored over time and moved to its new location, but in practice this rarely happens.</p> <p>How do you treat your legacy code? As much as I feel tempted to tuck away old sins in the "legacy" folder, never to look at it again, on some level I hope that by forcing it to live among the more "healthy" inhabitants in the repository, maybe the legacy code will have a better chance of getting well some day?</p> <p>(Yeah, we all know <a href="http://www.joelonsoftware.com/articles/fog0000000069.html" rel="nofollow noreferrer">we shouldn't rewrite stuff</a>, but this is my "fun" repository, not my business projects...)</p> <p><strong>Update</strong></p> <p>I am not worried about the technical aspects of keeping track of various versions. I know how to use tags and branches for that. This is more of a psychological aspect, as I prefer to have a "neat" structure in the repository, which makes navigating it much easier&mdash;for humans.</p>
<p>All code becomes 'legacy' one day, why seperate it at all? Source control is by project/branch or project/platform/branch and that type of hierarchy. Who cares how long in the tooth it is?</p>
<p>Use <em>Externals Definitions</em> (<a href="http://svnbook.red-bean.com/en/1.7/svn.advanced.externals.html" rel="nofollow noreferrer">svn:externals</a> property) to reference your legacy code as you would a third-party repository. </p> <p>Then you can separate your refactoring work from your dependent projects and (using fixed revision references i.e. -r1234) be very explicit about which revision of the legacy code the dependent project depends on.</p>
7,463
<p>Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages.</p>
<p>Apache Config file is: /private/etc/apache2/httpd.conf</p> <p>Default DocumentRoot is: /Library/Webserver/Documents/</p> <p>To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line:</p> <pre><code>#LoadModule php5_module libexec/apache2/libphp5.so </code></pre> <p>Remove the pound sign to uncomment the line so now it looks like this:</p> <pre><code>LoadModule php5_module libexec/apache2/libphp5.so </code></pre> <p>Restart Apache: System Preferences -> Sharing -> Un-check "Web Sharing" and re-check it. <strong>OR</strong> </p> <pre><code>$ sudo apachectl restart </code></pre>
<p>httpd.conf is in /private/etc/apache2</p> <p>Enable PHP by uncommenting line:</p> <pre><code> LoadModule php5_module libexec/apache2/libphp5.so </code></pre>
9,518
<p>Is there a way to call out from a TSQL stored procedure or function to a webservice?</p>
<p>Yes , you can create like this</p> <pre><code>CREATE PROCEDURE CALLWEBSERVICE(@Para1 ,@Para2) AS BEGIN Declare @Object as Int; Declare @ResponseText as Varchar(8000); Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; Exec sp_OAMethod @Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false' Exec sp_OAMethod @Object, 'send' Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT Select @ResponseText Exec sp_OADestroy @Object END </code></pre>
<p>If you're working with sql 2000 compatibility levels and cannot do clr integration, see <a href="http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx" rel="nofollow noreferrer">http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx</a></p>
5,348
<p><em>Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.</em></p> <p>I am used to create my properties in C# using a private and a public field:</p> <pre><code>private string title; public string Title { get { return title; } set { title = value; } } </code></pre> <p>Now, with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 3.0, we got auto-properties:</p> <pre><code>public string Title { get; set; } </code></pre> <p>I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.</p> <p>In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.</p> <p>I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.</p> <p>So, what am I missing here? Why would anyone actually want to use auto-properties?</p>
<p>We use them all the time in Stack Overflow.</p> <p>You may also be interested in a discussion of <a href="http://blog.codinghorror.com/properties-vs-public-variables/" rel="noreferrer">Properties vs. Public Variables</a>. IMHO that's really what this is a reaction to, and for that purpose, it's great.</p>
<p>I use CodeRush, it's faster than auto-properties.</p> <p>To do this:</p> <pre><code> private string title; public string Title { get { return title; } set { title = value; } } </code></pre> <p>Requires eight keystrokes total.</p>
3,073
<p>Assemblies A and B are privately deployed and strongly named. Assembly A contains references to Assembly B. There are two versions of Assembly B: B1 and B2. I want to be able to indicate for Assembly A that it may bind to either B1 or B2 -- ideally, by incorporating this information into the assembly itself. What are my options?</p> <p>I'm somewhat familiar with versioning policy and the way it applies to the GAC, but I don't want to be dependent on these assemblies being in the GAC.</p>
<p>There are several places you can indicate to the .Net Framework that a specific version of a strongly typed library should be preferred over another. These are:</p> <ul> <li>Publisher Policy file</li> <li>machine.config file</li> <li>app.config file</li> </ul> <p>All these methods utilise the <a href="http://msdn.microsoft.com/en-us/library/eftw1fys.aspx" rel="nofollow noreferrer" title=".NET Framework General Reference - &lt;bindingRedirect&gt; Element">"&lt;bindingRedirect&gt;"</a> element which can instruct the .Net Framework to bind a version or range of versions of an assembly to a specific version.</p> <p>Here is a short example of the tag in use to bind all versions of an assembly up until version 2.0 to version 2.5:</p> <pre><code>&lt;assemblyBinding&gt; &lt;dependantAssembly&gt; &lt;assemblyIdentity name="foo" publicKeyToken="00000000000" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0 - 2.0.0.0" newVersion="2.5.0.0" /&gt; &lt;/dependantAssembly&gt; &lt;/assemblyBinding&gt; </code></pre> <p>There are lots of details so it's best if you read about <a href="http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx" rel="nofollow noreferrer" title=".NET Framework Developer's Guide - Redirecting Assembly Versions">Redirecting Assembly Versions on MSDN</a> to decide which method is best for your case.</p>
<p>You can set version policy in your app.config file. Alternatively you can manually load these assemblies with a call to <code>Assembly.LoadFrom()</code> when this is done assembly version is not considered.</p>
7,816
<p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p> <p>Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.</p> <p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p> <p>For instance, sorting by a string record id gives something like:</p> <pre><code>rec1 rec10 rec14 rec2 rec20 rec3 rec4 </code></pre> <p>...and so on.</p> <p>I want this to take account of the number, so:</p> <pre><code>rec1 rec2 rec3 rec4 rec10 rec14 rec20 </code></pre> <p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p> <p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p> <p>Does anyone know a way to quickly apply a natural sort in Sql server?</p> <hr> <p>We're using:</p> <pre><code>ROW_NUMBER() over (order by {field name} asc) </code></pre> <p>And then we're paging by that.</p> <p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p> <hr> <p>We have valid user input that follows different formats for different clients.</p> <p>One might go rec1, rec2, rec3, ... rec100, rec101</p> <p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p> <p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p> <p>These formats vary a lot, but are often mixtures of letters and numbers.</p> <p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p> <p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p> <p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p> <p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>
<p>Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was <em>way</em> too slow.</p> <p>Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:</p> <ul> <li>will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)</li> <li>properly sorts decimals, so 123.333 comes before 123.45</li> <li>because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code</li> <li>supports sorting a string with an arbitrary number of numbers within it</li> <li>will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)</li> </ul> <p>The code is here:</p> <pre><code>using System; using System.Data.SqlTypes; using System.Text; using Microsoft.SqlServer.Server; public class UDF { [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)] public static SqlString Naturalize(string val) { if (String.IsNullOrEmpty(val)) return val; while(val.Contains(" ")) val = val.Replace(" ", " "); const int maxLength = 1000; const int padLength = 25; bool inNumber = false; bool isDecimal = false; int numStart = 0; int numLength = 0; int length = val.Length &lt; maxLength ? val.Length : maxLength; //TODO: optimize this so that we exit for loop once sb.ToString() &gt;= maxLength var sb = new StringBuilder(); for (var i = 0; i &lt; length; i++) { int charCode = (int)val[i]; if (charCode &gt;= 48 &amp;&amp; charCode &lt;= 57) { if (!inNumber) { numStart = i; numLength = 1; inNumber = true; continue; } numLength++; continue; } if (inNumber) { sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); inNumber = false; } isDecimal = (charCode == 46); sb.Append(val[i]); } if (inNumber) sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); var ret = sb.ToString(); if (ret.Length &gt; maxLength) return ret.Substring(0, maxLength); return ret; } static string PadNumber(string num, bool isDecimal, int padLength) { return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0'); } } </code></pre> <p>To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:</p> <pre><code>CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here go CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) EXTERNAL NAME SqlServerClr.UDF.Naturalize go </code></pre> <p>Then, you can use it like so:</p> <pre><code>select * from MyTable order by dbo.Naturalize(MyTextField) </code></pre> <p><strong>Note</strong>: If you get an error in SQL Server along the lines of <em>Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.</em>, follow the instructions <a href="http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm" rel="nofollow noreferrer">here</a> to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.</p> <p><strong>Note2</strong>: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!</p> <p><strong>Edit:</strong> Renamed the function to <em>Naturalize</em> instead of <em>NaturalSort</em>, since it does not do any actual sorting.</p>
<p>I still don't understand (probably because of my poor English).</p> <p>You could try:</p> <pre><code>ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC) </code></pre> <p>But it won't work for millions of records.</p> <p>That why I suggested to use trigger which <em>fills</em> <em>separate</em> column with <em>human value</em>.</p> <p>Moreover:</p> <ul> <li>built-in T-SQL functions are really slow and Microsoft suggest to use .NET functions instead.</li> <li><em>human value</em> is constant so there is no point calculating it each time when query runs.</li> </ul>
5,477
<p>I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows.</p>
<p>I've found Cygwin to be very useful in the past. FWIW, lately however I've shied away from it in favor of the following:</p> <ol> <li><a href="http://www.apachefriends.org/en/xampp-windows.html" rel="nofollow noreferrer">XAMPP</a></li> <li><a href="http://unxutils.sourceforge.net/" rel="nofollow noreferrer">Unixutils</a></li> </ol> <p>I like these tools even better.</p>
<p>I'm quite interested in this question myself. I've used the <a href="https://code.google.com/archive/p/jessies/wikis/CygwinSetup.wiki" rel="nofollow noreferrer">Cygwin Setup guide</a> to get set up, but it doesn't get you all the way. One thing that I learned from it, though, is that it recommends leaving the setup.exe in the directory with Cygwin so that you can quickly add packages, since apt-get apparently doesn't work that well in Cygwin. The article also talks about cyg-get as an alternative.</p>
8,036
<p>I'm working on a command line application for Solaris, written in Java6. I'd like to be able to scroll through a history of previous commands using the up and down arrows like many Unix tools allow (shells, VIM command mode prompt, etc).</p> <p>Is there any standard way of achieving this, or do I have to roll my own?</p>
<p>Yes, use the <a href="http://tiswww.case.edu/php/chet/readline/rltop.html" rel="nofollow noreferrer">GNU readline</a> library.</p>
<p>There is a SourceForge project, <a href="http://java-readline.sourceforge.net/" rel="nofollow noreferrer">http://java-readline.sourceforge.net/</a>, that provides JNI-based bindings to GNU readline. I've played around with it (not used in an actual project), and it certainly covers all of the functionality.</p>
7,148
<p><a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow noreferrer">Ajax</a>, <a href="http://en.wikipedia.org/wiki/Adobe_Flex" rel="nofollow noreferrer">Flex</a> and <a href="http://en.wikipedia.org/wiki/Microsoft_Silverlight" rel="nofollow noreferrer">Silverlight</a> are a few ways to make more interactive web applications. What kinds of factors would you consider when deciding which to use for a new web application? </p> <p>Does any one of them offer better cross-platform compatibility, performance, developer tools or community support? </p>
<p>Here's a quick rundown of each area (with lots of helpful links):</p> <h2>Cross-platform compatibility</h2> <p><a href="http://arstechnica.com/news.ars/post/20050808-5183.html" rel="nofollow noreferrer">Ajax</a> works in <a href="http://www.musingsfrommars.org/2006/03/ajax-dhtml-library-scorecard.html" rel="nofollow noreferrer">any modern browser</a> that can run <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a>. Flex requires Flash or anything else that can handle <a href="http://en.wikipedia.org/wiki/SWF" rel="nofollow noreferrer">SWF</a>s but, once that's installed, it's a <a href="http://blog.arc90.com/2006/07/10_reasons_we_love_flex_2.php" rel="nofollow noreferrer">total freeride</a> as far as compatibility. Silverlight is <a href="http://wildermuth.com/2008/04/03/Silverlight_Compatibility_Confusion" rel="nofollow noreferrer">tricky and misunderstood</a> so carefully consider your <a href="http://en.wikipedia.org/wiki/Silverlight#Compatibility" rel="nofollow noreferrer">userbase</a> before going with this MS foray into the rich web applications arms race. Also keep in mind that Silverlight is still in Beta, so it may become more widely used and installed in the future as it is developed.</p> <h2>Performance</h2> <p>I'm fearful of making too many statements about performance because it really depends on how much you are willing to optimize and the exact nature of your application. Also, some technology stacks are just never going to be very fast. <a href="http://www.jamesward.com/wordpress/2007/04/30/ajax-and-flex-data-loading-benchmarks/" rel="nofollow noreferrer">Some people out there have been making comparisons</a>, but again, <a href="http://metalinkltd.com/?p=108" rel="nofollow noreferrer">it depends on a great many factors</a> (even the version of the browser from which you are testing!). It's probably best to choose based on other factors and optimize once you've started to develop.</p> <h2>Developer tools</h2> <p>There are the "golden standard" dev tools for each of the three:</p> <ul> <li><p>Ajax has basically unlimited options, depending on the rest of your technology and architecture choices. The big questions you're actually faced with are which libraries to rely upon, and Google has voiced a pretty well adopted answer with things like <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">Web Toolkit</a>. When you get right down to it, it's just XML and JavaScript, right?</p></li> <li><p>Flex is from Adobe and, just like with Flash development, you'd better stick with <a href="http://www.adobe.com/products/flex/flexdownloads/index.html" rel="nofollow noreferrer">their homegrown tools</a> because--well--they're making the standards as they go along.</p></li> <li><p>Microsoft has positioned Microsoft Expression Blend versions 2.0 and 2.5 for designing the UI of Silverlight 1.0 and 2 applications respectively. Visual Studio 2008 can be used to develop and debug Silverlight applications (<a href="http://en.wikipedia.org/wiki/Silverlight#Development_tools" rel="nofollow noreferrer">from Wikipedia</a>). </p></li> </ul> <h2>Community support</h2> <p>There is both official and unofficial community, corporate, and open-source support for all three options. Whichever you are already integrated with and which makes you feel most at home are very individual things, but I'll offer this advice: stick with what you know. If you are a MS developer and have MSDN as your homepage, you are probably going to think the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=1840cab5-196c-4264-b55d-562242a72625&amp;displaylang=en" rel="nofollow noreferrer">Silverlight documentation</a> and forums are really helpful. Flex has a very similar story; the forums are pretty good and if you're a Flash person already, you're going to be right at home with their <a href="http://www.adobe.com/support/documentation/en/flex/" rel="nofollow noreferrer">documentation</a> and <a href="http://www.adobe.com/devnet/flex/" rel="nofollow noreferrer">user community</a>.</p> <p>On the other hand, Ajax is basically all over the place because you can implement so many different ways and use so many widely-varied libraries. Each library can have it's own forums to visit and mailing lists to lurk within for answers.</p> <p>Once again, all three have corporate giants trying to foster their communities and to get the best support possible to the developers that will give them greater market share in the future.</p>
<p>Other than what's already been mentioned here, another huge thing to consider is what your UI is going to be.</p> <p>If you're going to be using a lot of advanced UI controls like trees, lists, tab controls, etc then consider the following:</p> <ul> <li><p>JavaScript/HTML - No native support for anything beyond things basic drop down boxes, buttons, and text fields. If you want something like a tree control or tab control then you'll have to roll your own or find a third party library.</p></li> <li><p>Adobe ActionScript - Native support for a wide array of advanced UI controls</p></li> <li>Silverlight - 1.0 had very limited UI controls, but 2.0 will be adding many more and I'm sure we'll continue to see controls added in future releases.</li> </ul>
7,129
<p>I have a <code>List&lt;int&gt;</code> and a <code>List&lt;customObject&gt;</code>. The customObject class has an ID property. How can I get a <code>List&lt;customObject&gt;</code> containing only the objects where the ID property is in the <code>List&lt;int&gt;</code> using LINQ?</p> <p><strong>Edit</strong>: I accepted Konrads answer because it is easier/more intuitive to read.</p>
<pre><code>var result = from o in objList where intList.Contains(o.ID) select o </code></pre>
<p>Please note that using the join instead of contains DOES NOT work when the count of items in the list exceeds 49! You will get the error: <code>Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.</code></p>
5,861
<p>I'm having a frustrating problem with my recent built custom 3D printer so every single print I made, from the third layer, the nozzle is &quot;rubbing&quot; on the already placed filament. This results in a complete mess, melting the previous layers with the nozzle / new extrusions coming, getting malformed and out of precision forms, if I leave this happening, my Y-axis motor (bed) start to jump steps (by the force of nozzle friction to cold material). To stop that symptom, at the beginning of this, I have to raise the Z-axis by hand turning about 1/8 rotation of T8 fuse. By doing this, every rest of my printing runs peaceful, nicely, and beautiful.</p> <p>I'm using Marlin firmware, the most recent version, and Ultimaker Cura. My nozzle size is 0.5 and I'm using Ultimaker Cura's Fine Preset (0.1 mm height)</p> <p>My stepper motors axis are very well calibrated (X, Y, Z and Extruder). I tried:</p> <ul> <li>lowering and raising the print bed to get spaced or shrunken first layers to see if something helps,</li> <li>tried to change Z home offset on display,</li> <li>tried the <code>M206</code> command to change the print zone of the Z-axis,</li> <li>tried to change the first layer height on Ultimaker Cura,</li> </ul> <p>but nothing seems to solve my problems.</p> <p>Due to my lack of experience, I don't know what I could try to solve this frustrating issue. I already check and rechecked my mechanical structure and everything was fine solid and very well balanced and square.</p> <p><a href="https://i.stack.imgur.com/erJNy.jpg" rel="nofollow noreferrer" title="Photo of failed print - side"><img src="https://i.stack.imgur.com/erJNy.jpg" alt="Photo of failed print - side" title="Photo of failed print - side" /></a></p> <p><a href="https://i.stack.imgur.com/YHGU5.jpg" rel="nofollow noreferrer" title="Photo of failed print - front"><img src="https://i.stack.imgur.com/YHGU5.jpg" alt="Photo of failed print - front" title="Photo of failed print - front" /></a></p> <p>From comment:</p> <ul> <li>Printing speed are 40 mm/s,</li> <li>Temps:</li> <li>Hotend: 220 °C;</li> <li>Hot Bed: 120 °C;</li> <li>I have also tried 110 °C,</li> <li>My Z-axis uses 800 steps per mm (1/32 micro stepping on DRV8825 at RAMPS).</li> </ul> <p>I'm thinking about over extrusion but I have fine tuned my stepper, checked and rechecked for it and seems normal</p>
<p>I have made some learning on mechanical setup and discovered some issues on my printer, there are few:</p> <ol> <li>Bed warped, even with glass (thin thickness), making BAL confused with Z-movement over the bed.</li> <li>Overextrusion making layer oversized in terms of thickness.</li> <li>Some of missing mechanical fine adjustments.</li> </ol> <p>The main reason for this symptom was the overextrusion (that made my X and Y axis jump some steps when hotend collapses in the already-printed materials on their movements).</p> <p>I hope this helps some of those who have this similar problem!</p>
<p>The first picture seems to show layer shift. Usual causes include:</p> <ol> <li>Missed Z movement, so the nozzle hits the build and the layer is offset.</li> <li>Bad acceleration in X/Y, so there is missed X/Y movement, and the layer is offset.</li> </ol> <p>Adjustment: reduce Z G0 speed, and reduce X/Y speeds (G0 and G1) and acceleration, and then repeat.</p> <p>Hopefully, correcting this will make the issue in the second picture easier to diagnose.</p>
697
<p>When I print with a 0.4&nbsp; mm nozzle I have no problem with stringing at all but because I need a more detailed print I must use a 0.25&nbsp;mm nozzle.</p> <p>I use Ultimaker Cura and an Anycubic i3 Mega.</p> <p>What i tried so far:</p> <ul> <li>Enable/Disable Z hop</li> <li>Tried different retraction distance and speed.</li> <li>Tried with lower temperature</li> <li>Different wall thickness</li> </ul> <p>If you have any suggestion please let me know.</p>
<p>First, you should change the <strong>nozzle diameter</strong> setting, not just the line width setting, in Cura. Both are involved in determining extrusion. Line width can be less than or greater than nozzle size, but setting it much larger or smaller is not going to work well.</p> <p>I suspect your main problem, though, is print speed. The area of the 0.25 mm nozzle orifice is only 39% of the area of an 0.4 mm nozzle orifice, bounding the material extrusion rate <strong>at best</strong> at 39% of what you could get with the larger nozzle (in practice it will be even lower due to complex fluid dynamics, probably much lower), but at the same linear print speed with narrower lines, you'll be extruding (or trying to extrude) 62.5% as much material per unit time. Now, if that much material can't actually make it out of the nozzle, pressure builds up between the extruder gear and the nozzle, and stringing is the result.</p> <p>So, try lowering the print speed. <strong>A lot</strong> at first. If that solves the problem, gradually increase it until you find the limit. Increasing retraction and temperature may help you push it a little further. See my question and self-answer on stringing with flexible filaments, which might give you some ideas on other things to try:</p> <p><a href="https://3dprinting.stackexchange.com/q/8512/11157">Avoiding stringing with flexible filament</a></p>
<p>What worked well for me in avoiding stringing is to increase the travel move speeds significantly, disable Z-hop and to decrease printing temperature</p>
1,344
<p>If there are any language designers out there (or people simply in the know), I'm curious about the methodology behind creating standard libraries for interpreted languages. Specifically, what seems to be the best approach? Defining standard functions/methods in the interpreted language, or performing the processing of those calls in the compiled language in which the interpreter is written?</p> <p>What got me to thinking about this was the SO question about a stripslashes()-like function in Python. My first thought was "why not define your own and just call it when you need it", but it raised the question: is it preferable, for such a function, to let the interpreted language handle that overhead, or would it be better to write an extension and leverage the compiled language behind the interpreter?</p>
<p>The line between "interpreted" and "compiled" languages is really fuzzy these days. For example, the first thing Python does when it sees source code is compile it into a bytecode representation, essentially the same as what Java does when compiling class files. This is what *.pyc files contain. Then, the python runtime executes the bytecode without referring to the original source. Traditionally, a purely interpreted language would refer to the source code continuously when executing the program.</p> <p>When building a language, it is a good approach to build a solid foundation on which you can implement the higher level functions. If you've got a solid, fast string handling system, then the language designer can (and should) implement something like stripslashes() outside the base runtime. This is done for at least a few reasons:</p> <ul> <li>The language designer can show that the language is flexible enough to handle that kind of task.</li> <li>The language designer actually writes real code in the language, which has tests and therefore shows that the foundation is solid.</li> <li>Other people can more easily read, borrow, and even change the higher level function without having to be able to build or even understand the language core.</li> </ul> <p>Just because a language like Python compiles to bytecode and executes that doesn't mean it is slow. There's no reason why somebody couldn't write a Just-In-Time (JIT) compiler for Python, along the lines of what Java and .NET already do, to further increase the performance. In fact, IronPython compiles Python directly to .NET bytecode, which is then run using the .NET system including the JIT.</p> <p>To answer your question directly, the only time a language designer would implement a function in the language behind the runtime (eg. C in the case of Python) would be to maximise the performance of that function. This is why modules such as the regular expression parser are written in C rather than native Python. On the other hand, a module like getopt.py is implemented in pure Python because it can all be done there and there's no benefit to using the corresponding C library.</p>
<p>As long as you are using a portable API for the compiled code base like the <a href="http://en.wikipedia.org/wiki/C_standard_library" rel="nofollow noreferrer">ANSI C standard library</a> or <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="nofollow noreferrer">STL</a> in C++, then taking advantage of those functions would keep you from reinventing the wheel and likely provide a smaller, faster interpreter. <a href="http://www.lua.org/" rel="nofollow noreferrer">Lua</a> takes this approach and it is definitely small and fast as compared to many others.</p>
3,452
<p>Consider the Oracle <code>emp</code> table. I'd like to get the employees with the top salary with <code>department = 20</code> and <code>job = clerk</code>. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:</p> <pre><code>select * from scott.emp where deptno = 20 and job = 'CLERK' and sal = (select max(sal) from scott.emp where deptno = 20 and job = 'CLERK') </code></pre> <p>This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a <code>group by</code>? BTW, if this matters, I am using Oracle.</p>
<p>The following is slightly over-engineered, but is a good SQL pattern for "top x" queries.</p> <pre><code>SELECT * FROM scott.emp WHERE (deptno,job,sal) IN (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) </code></pre> <p>Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question <a href="https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424">SQL Query to get latest price</a></p>
<p>That's great! I didn't know you could do a comparison of (x, y, z) with the result of a SELECT statement. This works great with Oracle.</p> <p>As a side-note for other readers, the above query is missing a "=" after "(deptno,job,sal)". Maybe the Stack Overflow formatter ate it (?).</p> <p>Again, thanks Mark.</p>
7,395
<p>I'm having issues getting the C sockets API to work properly in C++ on z/OS.</p> <p>Although I am including <code>sys/socket.h</code>, I still get compile time errors telling me that <code>AF_INET</code> is not defined.</p> <p>Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?</p> <p>I discovered that there is an <code>#ifdef</code> that I'm hitting. Apparently z/OS isn't happy unless I define which &quot;type&quot; of sockets I'm using with:</p> <pre><code>#define _OE_SOCKETS </code></pre> <p>Now, I personally have no idea what this <code>_OE_SOCKETS</code> is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?</p> <p>Test App</p> <pre><code>#include &lt;sys/socket.h&gt; int main() { return AF_INET; } </code></pre> <p>Compile/Link Output:</p> <pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C &quot;./inet.C&quot;, line 5.16: CCN5274 (S) The name lookup for &quot;AF_INET&quot; did not find a declaration. CCN0797(I) Compilation failed for file ./inet.C. Object file not created. </code></pre> <p>A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any <code>#ifdef</code> statements.</p> <p>I have however noticed it contains the following:</p> <pre><code>#ifdef __cplusplus extern &quot;C&quot; { #endif </code></pre> <p>which encapsulates basically the whole file? Not sure if it matters.</p>
<p>Keep a copy of the IBM manuals handy:</p> <ul> <li><a href="http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/CBCPG1A0/CCONTENTS?DT=20090606065305" rel="noreferrer"> z/OS V1R11.0 XL C/C++ Programming Guide</a> </li> <li><a href="http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/EDCLB1A0/CCONTENTS?DT=20090607203246" rel="noreferrer"> z/OS V1R11.0 XL C/C++ Run-Time Library Reference</a> </li> </ul> <p>The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a "feature test macro"</p> <p>You should ask your friendly system programmer to install the <a href="http://www-03.ibm.com/servers/eserver/zseries/zos/le/manpgs.html" rel="noreferrer">XL C/C++ Run-Time Library Reference: Man Pages </a> on your system. Then you can do things like "man connect" to pull up the man page for the socket connect() API. When I do that, this is what I see:</p> <p>FORMAT</p> <p>X/Open</p> <pre><code>#define _XOPEN_SOURCE_EXTENDED 1 #include &lt;sys/socket.h&gt; int connect(int socket, const struct sockaddr *address, socklen_t address_len); </code></pre> <p>Berkeley Sockets</p> <pre><code>#define _OE_SOCKETS #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; int connect(int socket, struct sockaddr *address, int address_len); </code></pre>
<p>DISCLAIMER: I am not a C++ programmer, however I know C really well. I adapated these calls from some C code I have.</p> <p>Also markdown put these strange &#95; as my underscores.</p> <p>You should just be able to write an abstraction class around the C sockets with something like this:</p> <pre><code>class my_sock { private int sock; private int socket_type; private socklen_t sock_len; private struct sockaddr_in server_addr; public char *server_ip; public unsigned short server_port; }; </code></pre> <p>Then have methods for opening, closing, and sending packets down the socket.</p> <p>For example, the open call might look something like this:</p> <pre><code>int my_socket_connect() { int return_code = 0; if ( this-&gt;socket_type != CLIENT_SOCK ) { cout &lt;&lt; "This is a not a client socket!\n"; return -1; } return_code = connect( this-&gt;local_sock, (struct sockaddr *) &amp;this-&gt;server_addr, sizeof(this-&gt;server_addr)); if( return_code &lt; 0 ) { cout &lt;&lt; "Connect() failure! %s\n", strerror(errno); return return_code; } return return_code; } </code></pre>
2,240
<p>Can anyone recommend a good server-side PDF generation tool that would work in a Linux environment. I want easy as possible, pass it a XHTML file (with images) and have it generate a PDF from the <strong>rendered</strong> source.</p> <p>I don't have a massive budget, but anything under $1000 should be alright.</p> <p>Andrew</p>
<p>I used <a href="http://www.easysw.com/htmldoc/" rel="nofollow noreferrer">HTMLDoc</a> about 8 years ago and it did a good job of turning HTML tables with some basic formatting into a decent PDF report. There also seems to be an <a href="https://www.msweet.org/projects.php?Z1" rel="nofollow noreferrer">open source version</a> as well.</p>
<p>I did some searching, what about <a href="http://tbookdtd.sourceforge.net/" rel="nofollow noreferrer">tbookdtd</a>? It's downloadable <a href="http://sourceforge.net/project/showfiles.php?group_id=48834" rel="nofollow noreferrer">here</a> but it hasn't been active since 2005. It appears to convert the xml to Latex, into PDF.</p>
3,570
<p>I have three tables <code>tag</code>, <code>page</code>, <code>pagetag</code></p> <p>With the data below</p> <p><strong><em>page</em></strong></p> <pre><code>ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 </code></pre> <p><strong><em>tag</em></strong></p> <pre><code>ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 </code></pre> <p><strong><em>pagetag</em></strong></p> <pre><code>ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 </code></pre> <p>I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.</p> <pre><code>ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 </code></pre> <p>Is this possible with SQL?</p> <hr> <p>I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.</p>
<blockquote> <p>Sergio del Amo:</p> <blockquote> <p>However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.</p> </blockquote> </blockquote> <pre><code>SELECT pagetag.id, page.name, group_concat(tag.name) FROM ( page LEFT JOIN pagetag ON page.id = pagetag.pageid ) LEFT JOIN tag ON pagetag.tagid = tag.id GROUP BY page.id; </code></pre> <p>Not a very pretty query, but should give you what you want - <code>pagetag.id</code> and <code>group_concat(tag.name)</code> will be <code>null</code> for page 4 in the example you've posted above, but the page shall appear in the results.</p>
<p>I think you may need to use multiple updates.</p> <p>Something like (not tested):</p> <pre><code>select ID as 'PageId', Name as 'PageName', null as 'Tags' into #temp from [PageTable] declare @lastOp int set @lastOp = 1 while @lastOp &gt; 0 begin update p set p.tags = isnull(tags + ', ', '' ) + t.[Tagid] from #temp p inner join [TagTable] t on p.[PageId] = t.[PageId] where p.tags not like '%' + t.[Tagid] + '%' set @lastOp == @@rowcount end select * from #temp </code></pre> <p>Ugly though.</p> <p>That example's T-SQL, but I think MySql has equivalents to everything used.</p>
5,849
<p>What's the best way to get the contents of the mixed <code>body</code> element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The <code>XmlElement</code> type has the <code>InnerXml</code> property which is exactly what I'm after.</p> <p>The code as written <em>almost</em> does what I want, but includes the surrounding <code>&lt;body&gt;</code>...<code>&lt;/body&gt;</code> element, which I don't want.</p> <pre class="lang-js prettyprint-override"><code>XDocument doc = XDocument.Load(new StreamReader(s)); var templates = from t in doc.Descendants("template") where t.Attribute("name").Value == templateName select new { Subject = t.Element("subject").Value, Body = t.Element("body").ToString() }; </code></pre>
<p>I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old <strong>System.Xml</strong> method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being <strong>more than 3 times slower than the fastest</strong>.</p> <p>The results ordered by fastest to slowest:</p> <ol> <li>CreateReader - Instance Hunter (0.113 seconds)</li> <li>Plain old System.Xml - Greg Hurlman (0.134 seconds)</li> <li>Aggregate with string concatenation - Mike Powell (0.324 seconds)</li> <li>StringBuilder - Vin (0.333 seconds)</li> <li>String.Join on array - Terry (0.360 seconds)</li> <li>String.Concat on array - Marcin Kosieradzki (0.364)</li> </ol> <hr> <p><strong>Method</strong></p> <p>I used a single XML document with 20 identical nodes (called 'hint'):</p> <pre><code>&lt;hint&gt; &lt;strong&gt;Thinking of using a fake address?&lt;/strong&gt; &lt;br /&gt; Please don't. If we can't verify your address we might just have to reject your application. &lt;/hint&gt; </code></pre> <p>The numbers shown as seconds above are the result of extracting the "inner XML" of the 20 nodes, 1000 times in a row, and taking the average (mean) of 5 runs. I didn't include the time it took to load and parse the XML into an <code>XmlDocument</code> (for the <strong>System.Xml</strong> method) or <code>XDocument</code> (for all the others).</p> <p>The LINQ algorithms I used were: <em>(C# - all take an <code>XElement</code> "parent" and return the inner XML string)</em></p> <p><strong>CreateReader:</strong></p> <pre class="lang-js prettyprint-override"><code>var reader = parent.CreateReader(); reader.MoveToContent(); return reader.ReadInnerXml(); </code></pre> <p><strong>Aggregate with string concatenation:</strong></p> <pre class="lang-js prettyprint-override"><code>return parent.Nodes().Aggregate("", (b, node) =&gt; b += node.ToString()); </code></pre> <p><strong>StringBuilder:</strong></p> <pre class="lang-js prettyprint-override"><code>StringBuilder sb = new StringBuilder(); foreach(var node in parent.Nodes()) { sb.Append(node.ToString()); } return sb.ToString(); </code></pre> <p><strong>String.Join on array:</strong></p> <pre class="lang-js prettyprint-override"><code>return String.Join("", parent.Nodes().Select(x =&gt; x.ToString()).ToArray()); </code></pre> <p><strong>String.Concat on array:</strong></p> <pre class="lang-js prettyprint-override"><code>return String.Concat(parent.Nodes().Select(x =&gt; x.ToString()).ToArray()); </code></pre> <p>I haven't shown the "Plain old System.Xml" algorithm here as it's just calling .InnerXml on nodes.</p> <hr> <p><strong>Conclusion</strong></p> <p>If performance is important (e.g. lots of XML, parsed frequently), I'd <strong>use Daniel's <code>CreateReader</code> method every time</strong>. If you're just doing a few queries, you might want to use Mike's more concise Aggregate method.</p> <p>If you're using XML on large elements with lots of nodes (maybe 100's), you'd probably start to see the benefit of using <code>StringBuilder</code> over the Aggregate method, but not over <code>CreateReader</code>. I don't think the <code>Join</code> and <code>Concat</code> methods would ever be more efficient in these conditions because of the penalty of converting a large list to a large array (even obvious here with smaller lists).</p>
<pre><code>public static string InnerXml(this XElement xElement) { //remove start tag string innerXml = xElement.ToString().Trim().Replace(string.Format("&lt;{0}&gt;", xElement.Name), ""); ////remove end tag innerXml = innerXml.Trim().Replace(string.Format("&lt;/{0}&gt;", xElement.Name), ""); return innerXml.Trim(); } </code></pre>
2,582
<p>I'd like to prefix this question with the fact that I know virtually nothing about 3D printers, aside from the general principles of how they work.</p> <p>I've recently seen that SLS printers have become more affordable, to the point where in a few years they might be a compelling investment. I'm mainly interested in 3D printing miniatures for painting, and as such this one:</p> <p><a href="https://i.stack.imgur.com/tQUMO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tQUMO.jpg" alt="Warhammer 40k Kustom Boosta-Blasta"></a></p> <p>For scale, the miniature is about 150&nbsp;mm long. I'm mainly worried about smaller details, such as the faces of the Gunner or Driver. Will a consumer-grade SLS printer be able to print to such level of detail?</p>
<h2>Consumer Market?</h2> <p>While there are no &quot;consumer level&quot; SLS printers on the market currently, the question in itself is very interesting on a scientific level. The pricing edges for the consumer market for 3D printers can be somewhat estimated from the consumer electronics segment. This puts a maximum price tag of about 2000-2500 \$ onto it, comparable to a high-end PC.</p> <p>Currently<sup>Feb. 2020</sup>, most SLS machines come with 'inquire for price' or with prices of <a href="https://sintratec.com/product/sintratec-kit/" rel="nofollow noreferrer">5000 \$</a> or larger price tags, which indicates they are intended for professional or industrial use. Most SLS printers in consumer hands seem to be phased out older systems from second hand. So while there are for sure tries to get SLS more affordable, it is not there yet.</p> <h2>Resolution of SLS</h2> <p>SLS printers have resolutions based on two factors<sup><a href="https://cdn.intechopen.com/pdfs/60707.pdf" rel="nofollow noreferrer">1</a></sup>:</p> <ul> <li>grain size</li> <li>laser diameter</li> </ul> <p>Generally speaking, the finer the grain and more focussed the laser, the better the resolution. Current industrial machines - even cheap ones - work with particle sizes between 20 and 80 µm, with the bulk being around 40 to 60 µm<sup><a href="https://aip.scitation.org/doi/pdf/10.1063/1.4918516" rel="nofollow noreferrer">2</a></sup>.</p> <p>The laser focus point ranges generally in the &quot;tens of µm&quot;<sup><a href="https://cdn.intechopen.com/pdfs/60707.pdf" rel="nofollow noreferrer">1</a></sup>, and is listed with values between 50 and 300 µm for most ceramic powders in that paper.</p> <h2>Conclusion</h2> <p>As a rule of thumb, 50 µm seems to be the average nylon spot size, which is very much comparable with resin printers using SLA/mSLA/DLP technology. Details on miniatures are usually in the area of 100-200 µm, so are well achieveable with either.</p> <h3>Comparison SLS to SLA/mSLA/DLP</h3> <p>Resin technology has the benefit of being easier accessible with some entry level printes between 200 and 500 \$. Nylon SLS prints do demand a sealant but prints without any supports, Resin does at times need support.</p> <p>Printing times for DLP/mSLA is not dependant on the ammount of space used, making packing the build surface with as many models as possible benefitial, while SLS, like FDM, works with a moving spot, so the ammount of models increases print time.</p> <p>Both Technologies work with hazardous material - resin and very fine powders respecively - and demand proper PPE to handle them.</p>
<p>It's difficult to tell from your photo the level of detail required. A scale reference in the form of a metric ruler would be valuable. If, for example, the metallic eye on the gunner is 2 mm diameter, that would be 40 layers of 50 micron grains, allowing for substantial detail.</p> <p>Consumer level SLS printers, such as the Sinterit Kit, use fifty micron nylon powder and is subject to some shrinking. This implies one can expect slightly smaller than fifty micron detail to appear.</p> <p>One of our makerspace members purchased an SLS model from Shapeways. The surface is layer-free and one can see the individual granules under magnification. If you required a level of certainty of this detail, consider that you can create a model containing various levels of detail, then commission Shapeways to create it.</p> <p>It's certain that they use a production level system, but one can inquire of Shapeways of the size of the powder that is used.</p>
1,585
<p>What is the difference between a pointer variable and a reference variable?</p>
<ol> <li><p>A pointer can be re-assigned:</p> <pre><code>int x = 5; int y = 6; int *p; p = &amp;x; p = &amp;y; *p = 10; assert(x == 5); assert(y == 10); </code></pre> <p>A reference cannot be re-bound, and must be bound at initialization:</p> <pre><code>int x = 5; int y = 6; int &amp;q; // error int &amp;r = x; </code></pre> </li> <li><p>A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary <code>&amp;</code> operator and a certain amount of space that can be measured with the <code>sizeof</code> operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.</p> <pre><code>int x = 0; int &amp;r = x; int *p = &amp;x; int *p2 = &amp;r; assert(p == p2); // &amp;x == &amp;r assert(&amp;p != &amp;p2); </code></pre> </li> <li><p>You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.</p> <pre><code>int x = 0; int y = 0; int *p = &amp;x; int *q = &amp;y; int **pp = &amp;p; **pp = 2; pp = &amp;q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2); </code></pre> </li> <li><p>A pointer can be assigned <code>nullptr</code>, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to <code>nullptr</code>, but this is <a href="https://stackoverflow.com/questions/2397984/">undefined</a> and will not behave consistently.</p> <pre><code>/* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &amp;r = *static_cast&lt;int *&gt;(nullptr); // prints &quot;null&quot; under GCC 10 std::cout &lt;&lt; (&amp;r != nullptr ? &quot;not null&quot; : &quot;null&quot;) &lt;&lt; std::endl; bool f(int &amp;r) { return &amp;r != nullptr; } // prints &quot;not null&quot; under GCC 10 std::cout &lt;&lt; (f(*static_cast&lt;int *&gt;(nullptr)) ? &quot;not null&quot; : &quot;null&quot;) &lt;&lt; std::endl; </code></pre> <p>You can, however, have a reference to a pointer whose value is <code>nullptr</code>.</p> </li> <li><p>Pointers can iterate over an array; you can use <code>++</code> to go to the next item that a pointer is pointing to, and <code>+ 4</code> to go to the 5th element. This is no matter what size the object is that the pointer points to.</p> </li> <li><p>A pointer needs to be dereferenced with <code>*</code> to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses <code>-&gt;</code> to access its members whereas a reference uses a <code>.</code>.</p> </li> <li><p>References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)</p> </li> <li><p>Const references can be bound to temporaries. Pointers cannot (not without some indirection):</p> <pre><code>const int &amp;x = int(12); // legal C++ int *y = &amp;int(12); // illegal to take the address of a temporary. </code></pre> <p>This makes <code>const &amp;</code> more convenient to use in argument lists and so forth.</p> </li> </ol>
<p>In short,</p> <blockquote> <p>Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. - Extracted from Geeks for Geeks</p> </blockquote> <blockquote> <p>References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. - Extracted from Geeks for Geeks</p> </blockquote> <p>Another picture for more details:</p> <p><a href="https://i.stack.imgur.com/PBfzi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PBfzi.png" alt="From the web." /></a></p>
8,172
<p>Is there a way to <em>always</em> have LF line endings in Visual Studio? I can never seem to find it!</p>
<p>There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: <a href="http://grebulon.com/software/stripem.php" rel="noreferrer">http://grebulon.com/software/stripem.php</a></p>
<p>There's a plugin to VS called Strip'Em where you can choose which kind of new line type you want to auto convert all the line endings to when saving.</p> <p>(You can choose between LF, CRLF, CR.)</p>
6,702
<p>Has anyone had any experience in building a 'real world' application with the <a href="http://www.codeplex.com/smartclient" rel="noreferrer">Smart Client Software Factory</a>, from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls.</p>
<p>We used SCSF for a real world app with about 10 developers. It was a steep learning curve to set up and develop a pattern of usage, but once it was set up, introducing new developers to the project was VERY easy. Using CAB and SCSF was very beneficial to our project especially getting each developer up to speed and productive. </p> <p>A downfall of SCSF is that it provides ALOT of functionality that may not be used (we probably only used 60% of the functionality).</p> <p>I am also using SCSF for a new project and am considering refactoring to PRISM. PRISM allows you to cull the functionality that is not used. If you use WPF, I suggest looking into PRISM.</p>
<p>We use the <a href="http://www.codeplex.com/servicefactory" rel="nofollow noreferrer">Web Service Software Factory</a>, and we really like it because it makes it easier for developers to follow standards and appropriate patterns. The learning curve for us wasn't bad - a few hours per developer at most.</p> <p>Other than that, there aren't any other pros &amp; cons worth mentioning.</p>
2,800
<p>There is a conversion process that is needed when migrating Visual Studio 2005 web site to Visual Studio 2008 web application projects.</p> <p>It looks like VS2008 is creating a .designer. file for every aspx when you right click on a file or the project itself in Solution Explorer and select 'Convert to Web Application.'</p> <p>What is the purpose of these designer files? And these won't exist on a release build of the web application, they are just intermediate files used during development, hopefully?</p>
<p>They hold all the form designer stuff that used to go in the #Region " Web Form Designer Generated Code " section of the code. instead of putting it in the .aspx.vb file where people might edit it (mistakenly or not), it's been moved to a separate file, so that you don't have ever look at it.</p>
<p>What kibbee said. </p> <p>For the part of your question about existing on a release build, it depends on what kind of web site you have. If you have a pre-compiled web site, then <em>none</em> of code files (.vb, .cs, etc) need to be deployed the server. They are compiled into .dlls (assemblies) and deployed that way along with the .as*x files.</p>
4,811
<p>I could have sworn I read somewhere that when printing with TPU to make sure the part cooling fan is blowing. But I just did a quick Googling and couldn't find anything stating such on Matter Hackers or All3dp.</p> <p>I currently don't have a part cooling fan attached (waiting for square nuts to come in). I've been able to get by printing PLA without the fan. I'm curious if this is going to be a major obstacle with TPU.</p>
<p>You'll probably be fine printing TPU with no fan. I just started printing with TPU, and did a lot of test prints to find out what settings work. Fan made little difference. With hotend at 230 °C, which I started out with, 0-20% fan was fine. I eventually increased temperature to 250 °C, which made extrusion more consistent and allowed me to reduce linear advance K-factor somewhat, and at that temperature having a bit more fan (I'm using 40% now) seems to help the material hold its shape, but it mainly made a difference at higher print speeds (over 35 mm/s) where the motion of the nozzle was "pulling on" the still-very-soft material just extruded. At 30 mm/s and below, fan still doesn't seem very important.</p> <p>All of this is likely to vary somewhat with the properties of your machine. However I think it's safe to say you should be able to find a combination of print speed and temperature that make it possible to get by with no fan.</p> <p><strong>Follow-up:</strong> Upon further experimentation with TPU, I would say you really <strong>don't want any fan at all</strong>, except possibly for bridges. I've found significant distortion to shape just from air pressure from the fan, and at higher speeds the fan makes the print brittle just like what happens with PETG. Layers of TPU really seem to want time to melt together to bond, and without a fan blowing on them they don't seem to lose their shape during that time.</p>
<p>Sharing fan percentages like in <a href="/a/11852/">this answer</a> is only helpful if you use the same printer model, cooling fan and cooling duct. As there are many 3D printers and many cooling fans, ducts and solutions, this cannot be readily adopted to every 3D printer.</p> <p>So, in such a case I would rely on the manufacturers of the filament e.g. the flexible filament I use has settings for different printers listed <a href="http://ngen-flex.colorfabb.com/how/" rel="nofollow noreferrer">here</a>. TPU is not very prone to warping. The general rule for cooling of TPU is found to not use it for the first 2 layers and after that proceed with a moderate cooling flow. What that value is for your printer is left as an experiment. Several test/calibration print designs exist (e.g. for bridging) to test this out. It is said that a little cooling aids in better aesthetic prints (finer details) while less cooling results in stronger layer adhesion and thus stronger prints.</p>
1,564
<p>I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id.</p> <p>On the Panel:</p> <pre><code> MyPanel.DefaultButton = SearchButton.ID</code></pre> <p>On the Control:</p> <pre><code>Me.Page.Form.DefaultButton = SearchButton.UniqueID </code></pre> <p>Works fine in IE &amp; Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying &quot;Object reference not set to an instance of an a object.</p> <p>Anyone run across this before?</p>
<p>Ends up this resolved my issue:</p> <pre><code> SearchButton.UseSubmitBehavior = False </code></pre>
<p>I might be wrong and this might not make a difference but have you tried:</p> <pre><code>Me.Page.Form.DefaultButton = SearchButton.ID </code></pre> <p>instead of</p> <pre><code>Me.Page.Form.DefaultButton = SearchButton.UniqueID </code></pre>
2,788
<p>I'm building a 3D printer and I've been looking around for materials suitable to make the frame.</p> <p>I have occasional access to a laser cutter which I could use to manufacture a ply box-type (UltiMaker) enclosure, but I like the ease of adjustment provided by the T-slot beam kits.</p> <p>I don't have any metal-cutting machine tools. Can aluminium beam be cut by hand with a hacksaw to a good degree of accuracy? How does one finish the cut end?</p>
<p>Aluminum of almost every grade is very easy to cut with a hacksaw. I would suggest to mark clearly the cut line and to wrap masking tape at the edge of the cut. Consider to allow for about 2-3 millimeters (1/16") extra material for final finishing. Cut across the line, rotate the part ninety degrees and cut again. Once you have the guide cuts in place, you should be able to manage a square cut by following those guides</p> <p>You will want to have a clamping mechanism available, such as a vise or workbench type device. </p> <p>After the cut is done, use a sharp file to make final adjustments to the length and appearance. Push the file, do not drag it backwards. Push forward, lift away from the work piece as you return, then push again. Pick up a file card, which is a fine metal-tooth brush used to clear the teeth of the file.</p> <p>It is very easy to remove material with a hand file, perhaps three or four strokes to remove 1/16".</p> <p>Your accuracy will depend on the measurement of the lines you create and how carefully you file to the edge of those lines.</p>
<p>As an alternative solution, Misumi sells extrusions precision-cut to length for a very reasonable price. You'll get better quality ends and a more precisely square frame from Misumi than if you try to cut them yourself. The HFS-5 series of 2020 is perfect for 3D printers. </p>
222
<p>I'm looking for design\architectual guidance for modern text editors.</p> <p><em>Modern</em> text editor means that: </p> <ul> <li>It has support for syntax highlighting</li> <li>It has auto-completion (something like IntelliSense)</li> <li>It has advanced navigation capabilities (incremental search, etc.)</li> </ul> <p>Following properties will be a plus:</p> <ul> <li>Implemented in managed language (Java, any .NET language)</li> <li>Modular architecutre</li> <li>Add-in support</li> </ul> <p>I'm very interested in <em>text editor related</em> design\architecure documents\articles, links to open source projects. </p> <p>I'm <strong>not</strong> interested in general recommendations, OOP/design patterns books advertisement.</p> <p>Currently I'm analyzing <a href="http://sharpdevelop.net/OpenSource/SD/" rel="noreferrer">SharpDevelop code editor</a> source code. Links to similar projects will be appreciated.</p>
<p>The ultimate text editor is, of course, emacs. I found <a href="http://www.finseth.com/craft/" rel="noreferrer">The Craft of Text Editing, or, Emacs for the Modern World </a> to be an excellent self-study guide for the basics of writing an editor. The examples are all in plain old C, and the text might look a bit dated (it is from 1991), but the basic ideas are still valid, and you thoroughly understand <em>why</em> the editor works the way it does.</p>
<p>Have you looked at vim? It supports autocompletion, syntax highlighting, incremental search, integrated building, etc, etc. It is modular and many of its more advanced features are implemented as plugins that either ship with it or can be found separately (e.g., svn integration, code indexing with cscope/ctags, transparent reading/writing over ssh). </p> <p>It has apis for writing plugins in several langauges (e.g., python, ruby, perl) as well as its own extension language ('vimscript').</p> <p>I don't know what they have in terms of high-level architecture documentation, but there is an active community and a developer mailing list that should be able to answer specific questions about how it works if you start digging through the source.</p>
8,309
<p>I have a <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> application that I am converting over to use webservices instead of straight up database queries. There are some extremely long lists that <em>before</em> could be returned easily with a simple SQL query. I'd like to figured out how implement the paging using JSF/web services. Is there a good design pattern for doing paged web services?</p> <p>If it matters, I'm currently using the <a href="http://en.wikipedia.org/wiki/Apache_MyFaces" rel="nofollow noreferrer">Apache MyFaces</a> reference implementation of JSF with the Tomahawk extensions (a set of JSF components created by the MyFaces development team prior to its donation to Apache).</p>
<p>I like Seam's Query objects: <a href="http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e7527" rel="nofollow noreferrer">http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e7527</a></p> <p>They basically abstract all the SQL/JPA in a Seam component that JSF can easily use.</p> <p>If you don't want to use Seam and/or JPA you could implement a similar pattern.</p>
<p>If you are getting all the results back from the webservice at once and can't include pagination into the actual web service call, you can try setting the list of items to a property on a managed bean. Then you can hook that up to the "value" attribute on a Tomahawk dataTable: </p> <p><a href="http://myfaces.apache.org/tomahawk-project/tomahawk/tagdoc/t_dataTable.html" rel="nofollow noreferrer">http://myfaces.apache.org/tomahawk-project/tomahawk/tagdoc/t_dataTable.html</a></p> <p>and then you can use a Tomahawk dataScroller to paginate over the list of items stored in that property. Here is the reference for that component, it works well with the dataTable component:</p> <p><a href="http://myfaces.apache.org/tomahawk-project/tomahawk/tagdoc/t_dataScroller.html" rel="nofollow noreferrer">http://myfaces.apache.org/tomahawk-project/tomahawk/tagdoc/t_dataScroller.html</a></p> <p>You can include this inside the header/footer facets of the dataTable or as a separate compoment (you will need to specify the id of the dataTable in the 'for' attribute of the dataScroller. </p> <p>There's other neat things you can do with the dataTable like sorting and toggling details for each row, but that can be implemented once you get the basic pagination working. </p> <p>Hope that helps!</p>
9,531
<p>I have an Enumerable array</p> <pre><code>int meas[] = new double[] {3, 6, 9, 12, 15, 18}; </code></pre> <p>On each successive call to the mock's method that I'm testing I want to return a value from that array.</p> <pre><code>using(_mocks.Record()) { Expect.Call(mocked_class.GetValue()).Return(meas); } using(_mocks.Playback()) { foreach(var i in meas) Assert.AreEqual(i, mocked_class.GetValue(); } </code></pre> <p>Does anyone have an idea how I can do this?</p>
<p>There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it. The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.</p> <pre><code>var meas = new int[] { 3, 6, 9, 12, 15, 18 }; using (mocks.Record()) { int forMockMethod = 0; SetupResult.For(mocked_class.GetValue()).Do( new Func&lt;int&gt;(() =&gt; meas[forMockMethod++]) ); } using(mocks.Playback()) { foreach (var i in meas) Assert.AreEqual(i, mocked_class.GetValue()); } </code></pre>
<p>IMHO, yield will handle this. <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx" rel="nofollow noreferrer">Link</a>.</p> <p>Something like:</p> <pre><code>get_next() { foreach( float x in meas ) { yield x; } } </code></pre>
9,468
<p>For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)</p>
<p>9 out of 10 times, code folding means that you have failed to use the <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="noreferrer">SoC principle</a> for what its worth.<br /> I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up.<br />It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method.<br /> <br /> Whenever you can, pull some code out of the main class, and into a helper or factory class. <br /></p> <pre><code>foreach (var item in Items) { //.. 100 lines of validation and data logic.. } </code></pre> <p>is not as readable as</p> <pre><code>foreach (var item in Items) { if (ValidatorClass.Validate(item)) RepositoryClass.Update(item); } </code></pre> <p><br /> <br /> My $0.02 anyways.</p>
<p>I prefer #regions myself, but an old coworker couldn't stand to have things hidden. I understood his point once I worked on a page with 7 #regions, at least 3 of which had been auto-generated and had the same name, but in general I think they're a useful way of splitting things up and keeping everything less cluttered.</p>
2,780
<p>I have a whole bunch of files with filenames using our lovely Swedish letters <strong>å å</strong> and <strong>ö</strong>. For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace <strong>å</strong> with <strong>a</strong>, <strong>ö</strong> with <strong>o</strong> and so on. </p> <p>This is charset troubles at their worst.</p> <p>I have a set of test files:</p> <pre><code>files\Copy of New Text Documen åäö t.txt files\fofo.txt files\New Text Document.txt files\worstcase åäöÅÄÖéÉ.txt </code></pre> <p>I'm basing my script on this line, piping it's results into various commands</p> <pre><code>for %%X in (files\*.txt) do (echo %%X) </code></pre> <p>The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:</p> <pre><code>files\Copy of New Text Documen †„” t.txt files\fofo.txt files\New Text Document.txt files\worstcase †„”Ž™‚.txt </code></pre> <p>So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.</p> <p>How would you solve this problem? I'm open to any type of tools, commandline or otherwise…</p> <p><strong>EDIT:</strong> This is a one time problem, so I'm looking for a quick 'n ugly fix</p>
<p>You can use this code (Python)</p> <h1>Rename international files</h1> <pre><code># -*- coding: cp1252 -*- import os, shutil base_dir = "g:\\awk\\" # Base Directory (includes subdirectories) char_table_1 = "áéíóúñ" char_table_2 = "aeioun" adirs = os.walk (base_dir) for adir in adirs: dir = adir[0] + "\\" # Directory # print "\nDir : " + dir for file in adir[2]: # List of files if os.access(dir + file, os.R_OK): file2 = file for i in range (0, len(char_table_1)): file2 = file2.replace (char_table_1[i], char_table_2[i]) if file2 &lt;&gt; file: # Different, rename print dir + file, " =&gt; ", file2 shutil.move (dir + file, dir + file2) ### </code></pre> <p>You have to change your encoding and your char tables (I tested this script with Spanish files and works fine). You can comment the "move" line to check if it's working ok, and remove the comment later to do the renaming.</p>
<p>I would write this in C++, C#, or Java -- environments where I know for certain that you can get the Unicode characters out of a path properly. It's always uncertain with command-line tools, especially out of Cygwin.</p> <p>Then the code is a simple find/replace or regex/replace. If you can name a language it would be easy to write the code.</p>
8,105
<p>I have a long print that keeps aborting. At some random point mid-print the printer says "Click to resume...". There is nothing in the G-code that asks for user confirmation. What could it be that triggers this? I noticed that sometimes (not every time) there is a blob of plastic in the way that should not be there.</p> <p>On one occasion, after the "Click to resume...", the LCD showed the message <code>FY178.N16466</code> and again waited for a click.</p> <p>The printer is an Anet A8 with Marlin 1.1.9. Slicer is Cura. I am printing via USB from Cura directly.</p> <p>This is the error message:</p> <p><a href="https://i.stack.imgur.com/QXdNc.jpg" rel="nofollow noreferrer" title="&quot;Click to resume...&quot; error message"><img src="https://i.stack.imgur.com/QXdNc.jpg" alt="&quot;Click to resume...&quot; error message" title="&quot;Click to resume...&quot; error message"></a></p>
<p>To answer your question directly, this action (<code>Click to resume...</code>) is triggered by a buffer overflow of the Marlin firmware that is caused by the repetitive sending of <code>M105</code> command by Ultimaker Cura (without checking the result).</p> <p>This problem is a <a href="https://github.com/Ultimaker/Cura/issues/3994" rel="nofollow noreferrer">reported problem</a> and fixed in the next release of Ultimaker Cura (please do note that as of posting this answer, the 3.6 Beta release is available for <a href="https://ultimaker.com/en/blog/52744-ultimaker-cura-36-beta-available-now" rel="nofollow noreferrer">download</a>). It appears to be a communication problem between Ultimaker Cura 3.4+ and 1.1.8+ versions of the Marlin firmware and has to to with polling of the temperature (<code>M105</code>). The link above also states it is fixed in the 3.6 release (which is the next release) as the fix has been integrated in the main code base.</p> <p>This describes the problem:</p> <blockquote> <p>To update the temperatures in the monitor, Cura sends M105 pings every 2 seconds. It seems that if this is done during a print without waiting for an <code>OK</code> from the printer, the serial buffer on the printer may still overflow eventually (causing Marlin to complain/pause).</p> </blockquote> <p>and this describes the solution:</p> <blockquote> <p>During some operations, such as preheating, the printer responds to new commands with <code>echo:busy</code>. While it is busy, it does send temperature messages, but these are not prepended with an <code>ok</code>, because the <code>ok</code> is supposed to show that a command was received and executed. So the two patches I wrote do the following:</p> <ul> <li>the pattern matching no longer looks for <code>ok</code> messages, but looks for temperature updates (this fixes the temperature updating while the printer is preheating) </li> <li>once the printer has said that it is busy, stop asking for temperature updates until the next <code>ok</code> is received (this prevents the serial buffer overflowing while preheating)</li> </ul> </blockquote> <hr> <p><em>Old answer centered around the firmware (based on the text of the OP, no photo with the actual error message was added yet):</em></p> <p><strike>The text <code>click to resume print</code> cannot be found (with case insensitive search) in the latest sources of Marlin 1.1.9 down to Marlin 1.1.6. This means that you are using a different fork, an older version of Marlin or the message is not displayed as such.</p> <p>The text message <code>Resume print</code> can be found, and is part of the message constant <code>MSG_RESUME_PRINT</code></p> <pre><code>#define MSG_RESUME_PRINT _UxGT("Resume print") </code></pre> <p>But, this cannot be found in some sort of a concatenation using <code>MSG_RESUME_PRINT</code>!</strike></p>
<p>Tonight I had faced the same problem.</p> <p>I've read somewhere (can't find the source now) that this is a Cura bug that has been fixed in Cura 3.6 beta</p>
1,070
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="noreferrer">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html" rel="noreferrer">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html" rel="noreferrer">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
<p>I can't help the way it's stored, but at least formatting works correctly: </p> <pre><code>'%.1f' % round(n, 1) # Gives you '5.6' </code></pre>
<p>What about:</p> <pre><code>round(n,1)+epsilon </code></pre>
8,093
<p>I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:</p> <pre><code>private static IEnumerator&lt;TextBox&gt; FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count &gt; 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2 != null) { yield return textBox2; } } } </code></pre> <p>Using it like this:</p> <pre><code>foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } </code></pre> <p>But of course the compiler spits its dummy, because <em>foreach</em> expects an <strong>IEnumerable</strong> rather than an <strong>IEnumerator</strong>.</p> <p>Is there a way to do this without having to create a separate class with a <strong>GetEnumerator()</strong> method?</p>
<p>As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.</p>
<p>If you are given an enumerator, and need to use it in a for-each loop, you could use the following to wrap it:</p> <pre> static public class enumerationHelper { public class enumeratorHolder&lt;T&gt; { private T theEnumerator; public T GetEnumerator() { return theEnumerator; } public enumeratorHolder(T newEnumerator) { theEnumerator = newEnumerator;} } static enumeratorHolder&lt;T&gt; toEnumerable&lt;T&gt;(T theEnumerator) { return new enumeratorHolder&lt;T&gt;(theEnumerator); } private class IEnumeratorHolder&lt;T&gt;:IEnumerable&lt;T&gt; { private IEnumerator&lt;T&gt; theEnumerator; public IEnumerator&lt;T&gt; GetEnumerator() { return theEnumerator; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return theEnumerator; } public IEnumeratorHolder(IEnumerator&lt;T&gt; newEnumerator) { theEnumerator = newEnumerator; } } static IEnumerable&lt;T&gt; toEnumerable&lt;T&gt;(IEnumerator&lt;T&gt; theEnumerator) { return new IEnumeratorHolder&lt;T&gt;(theEnumerator); } } </pre> <p>The <code>toEnumerable</code> method will accept anything that <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged &#39;c#&#39;" rel="tag">c#</a> or <a href="/questions/tagged/vb" class="post-tag" title="show questions tagged &#39;vb&#39;" rel="tag">vb</a> would regard an acceptable return type from <code>GetEnumerator</code>, and return something that can be used in <code>foreach</code>. If the parameter is an <code>IEnumerator&lt;&gt;</code> the response will be an <code>IEnumerable&lt;T&gt;</code>, though calling <code>GetEnumerator</code> on it once will likely yield bad results.</p>
2,548
<p>I have an <a href="https://www.thingiverse.com/thing:3723481" rel="nofollow noreferrer">STL</a> (Raspberry Pi 4 casing) that automatically places itself like below on the bed surface:</p> <p><a href="https://i.stack.imgur.com/0Xm8V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Xm8V.png" alt="enter image description here" /></a></p> <p>Would it be a better and more efficient print if I place it like this:</p> <p><a href="https://i.stack.imgur.com/9Slno.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Slno.png" alt="enter image description here" /></a></p> <p>At first, I thought this is no-brainer, the bigger surface should be the bottom layer. However, the horizontal print might result a more efficient head movement.</p>
<p>The second placement is a better choice from an overall standpoint. In the vertical placement, adhesion is going to be more critical, although Prusa printers have good bonding for PLA and ABS, from my direct experience.</p> <p>The other aspect of more importance is that the holes are going to be distorted in the vertical arrangement. The cut-outs in the smaller portion will also &quot;droop&quot; unless otherwise supported. If supported, you'll have greater post-processing labor and unsightly surfaces.</p> <p>The design is quite well done, as the corners have radii which allows for smoother carriage travel, rather than abrupt stops with direction changes at each end.</p> <p>Importing the model and having the result appear as in the first image means that the designing software swaps the z-axis and the y-axis, which is relatively common.</p>
<p>You've already got the correct answer, but I want to address an additional misconception in your question: head movement efficiency. Most 3D print jobs are <em>acceleration-bound</em>, not <em>top-speed-bound</em>. Without really cranking up the acceleration limits (which requires Klipper and input shaper tuning), the head will only reach the requested speed on <em>long linear moves</em>.</p> <p>The orientation lying flat has a lot of those: the 4 sides are all long, and the diagonal fill line are long.</p> <p>The orientation with the part standing up on one end has very short lines, and a lot more of them.</p>
2,024
<p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile &gt;&gt; x; cerr &lt;&lt; x &lt;&lt; endl; } return 0; } </code></pre> <p><strong>input.txt</strong>:</p> <pre><code>10 20 30 </code></pre> <p><strong>Output</strong>:</p> <pre><code>10 20 30 30 </code></pre> <p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>
<p>Just follow closely the chain of events.</p> <ul> <li>Grab 10</li> <li>Grab 20</li> <li>Grab 30</li> <li>Grab EOF</li> </ul> <p>Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.</p> <p>Try this:</p> <pre><code>while (true) { int x; iFile &gt;&gt; x; if( iFile.eof() ) break; cerr &lt;&lt; x &lt;&lt; endl; } </code></pre> <p>By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.</p>
<pre><code>int x; ifile &gt;&gt; x while (!iFile.eof()) { cerr &lt;&lt; x &lt;&lt; endl; iFile &gt;&gt; x; } </code></pre>
4,177
<p>Which <strong>standalone Windows GUI application</strong> do you recommend for use for accessing a Subversion repository?</p> <p>Edit: A lot of people are mentioning Tortoise, however I am looking for an application not a shell extension. Also people are questioning my reasoning behind not wanting to use a shell extension. In our environment we rather interact with the repository (when not using an IDE plugin) through a management application and not navigate the files through Windows Explorer.</p>
<p><strong>Standalone Clients</strong></p> <p>For total stand alone <a href="http://www.syncrosvnclient.com/" rel="nofollow noreferrer">Synchro SVN</a> is a powerful and cross platform solution. It looks like the most native application on each of the platforms.</p> <p>The <a href="http://subversion.tigris.org/links.html#clients" rel="nofollow noreferrer">Subversion website</a> includes a listing of other <strong>standalone SVN Clients</strong> (most are cross platform). [Copied list below from <a href="http://subversion.tigris.org/links.html#clients]" rel="nofollow noreferrer">http://subversion.tigris.org/links.html#clients]</a></p> <p><strong>eSvn</strong> - cross-platform QT-based GUI frontend to Subversion <a href="http://sourceforge.net/projects/esvn" rel="nofollow noreferrer">http://sourceforge.net/projects/esvn</a></p> <p><strong>FSVS</strong> - fast subversion command-line client centered around software deployment <a href="http://fsvs.tigris.org/" rel="nofollow noreferrer">http://fsvs.tigris.org/</a></p> <p><strong>KDESvn</strong> - A Subversion client for KDE <a href="http://www.alwins-world.de/wiki/programs/kdesvn" rel="nofollow noreferrer">http://www.alwins-world.de/wiki/programs/kdesvn</a></p> <p><strong>QSvn</strong> - A cross-platform GUI Subversion client <a href="http://ar.oszine.de/projects/qsvn/" rel="nofollow noreferrer">http://ar.oszine.de/projects/qsvn/</a></p> <p><strong>RapidSVN</strong> - A cross-platform GUI front-end for Subversion <a href="http://rapidsvn.tigris.org/" rel="nofollow noreferrer">http://rapidsvn.tigris.org/</a></p> <p><strong>RSVN</strong> - Python script which allows multiple repository-side operations in a single, atomic transaction. <a href="https://opensvn.csie.org/traccgi/rsvn/trac.cgi/wiki" rel="nofollow noreferrer">https://opensvn.csie.org/traccgi/rsvn/trac.cgi/wiki</a></p> <p><strong>SmartSVN</strong> - A cross-platform GUI client for Subversion (Not open source. Available in a free and a commercial version.) <a href="https://www.smartsvn.com/" rel="nofollow noreferrer">https://www.smartsvn.com/</a></p> <p><strong>Subcommander</strong> - A cross-platform Subversion GUI client including a visual text merge tool. <a href="http://subcommander.tigris.org/" rel="nofollow noreferrer">http://subcommander.tigris.org/</a></p> <p><strong>SvnX</strong> - A Mac OS X Panther GUI client. <a href="http://www.lachoseinteractive.net/en/community/subversion/svnx/" rel="nofollow noreferrer">http://www.lachoseinteractive.net/en/community/subversion/svnx/</a></p> <p><strong>Syncro SVN Client</strong> - Cross-platform graphical Subversion client. (Not open source. Free trial versions available for Mac OS X, Windows and Linux.) <a href="http://www.syncrosvnclient.com" rel="nofollow noreferrer">http://www.syncrosvnclient.com</a></p> <p><strong>WorkBench</strong> - Cross platform software development GUI built on Subversion written in Python <a href="http://pysvn.tigris.org/" rel="nofollow noreferrer">http://pysvn.tigris.org/</a></p> <p><strong>Versions</strong> - A GUI Subversion client for Mac OS X. (Not open source; requires commercial license.) <a href="http://www.versionsapp.com/" rel="nofollow noreferrer">http://www.versionsapp.com/</a></p> <p><strong>ZigVersion</strong> - a Subversion Interface for Mac OS X. Aims to design an interface around the typical workflows of programmers. (Note that this is not open source.) <a href="http://zigversion.com/" rel="nofollow noreferrer">http://zigversion.com/</a></p> <p><strong>Integrated Clients</strong></p> <p><a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">TortoiseSVN</a> is the best general use system [An integrated system is not standalone - Thanks Martin Kenny]. It integrates itself into Windows Explorer (You can use it in explorer or any shell dialog) so it works extremely well and gives you the full power of SVN.</p> <p><a href="http://ankhsvn.open.collab.net/" rel="nofollow noreferrer">Ankhsvn</a> is a good solution that integrates into Visual Studios (Except Express Editions).</p> <p><a href="http://svnnotifier.tigris.org/" rel="nofollow noreferrer">SVN Notifier</a> monitors your repositories and will notify you when anything changes. It integrates with TortoiseSVN to show you diffs and commit logs. Very handy when working in a team environment.</p>
<p>Memory and disk IO can be a problem with TSVNCache, which manages Tortoise's icon overlays. You can fix it by putting your checkouts in one or two directories and making the cache process only look at those directories, rather than your entire drive.</p> <p><a href="http://www.paraesthesia.com/archive/2007/09/26/optimize-tortoise-svn-cache-tsvncache.exe-disk-io.aspx" rel="nofollow noreferrer">See this link for instructions.</a></p>
8,364
<p>Are there any VC++ settings I should know about to generate better PDB files that contain more information? </p> <p>I have a crash dump analysis system in place based on the project <a href="http://code.google.com/p/crashrpt/" rel="nofollow noreferrer">crashrpt</a>.</p> <p>Also, my production build server has the source code installed on the D:\, but my development machine has the source code on the C:\. I entered the source path in the VC++ settings, but when looking through the call stack of a crash, it doesn't automatically jump to my source code. I believe if I had my dev machine's source code on the D:\ it would work. </p>
<blockquote> <p>"Are there any VC++ settings I should know about"</p> </blockquote> <p>Make sure you turn off Frame pointer ommision. Larry osterman's blog has <a href="http://blogs.msdn.com/larryosterman/archive/2007/03/12/fpo.aspx" rel="noreferrer">the historical details</a> about fpo and the issues it causes with debugging.</p> <blockquote> <p>Symbols are loaded successfully. It shows the callstack, but double clicking on an entry doesn't bring me to the source code.</p> </blockquote> <p>What version of VS are you using? (Or are you using Windbg?) ... in VS it should defintely prompt for source the first time if it doesn't find the location. However it also keeps a list of source that was 'not found' so it doesn't ask you for it every time. Sometimes the don't look list is a pain ... to get the prompt back up you need to go to solution explorer/solution node/properties/debug properties and edit the file list in the lower pane.</p> <p>Finally you might be using 'stripped symbols'. These are pdb files generated to provide debug info for walking the callstack past FPO, but with source locations stripped out (along with other data). The public symbols for windows OS components are stripped pdbs. For your own code these simply cause pain and are not worth it unless you are providing your pdbs to externals. How would you have one of these horrible stripped pdbs? You might have them if you use "binplace" with the -a command.</p> <p>Good luck! A proper mini dump story is a godsend for production debugging.</p>
<p>In case anyone is interested, a co-worker replied to this question to me via email:</p> <p>Artem wrote: </p> <blockquote> <p>There is a flag to MiniDumpWriteDump() that can do better crash dumps that will allow seeing full program state, with all global variables, etc. As for call stacks, I doubt they can be better because of optimizations... unless you turn (maybe some) optimizations off.</p> <p>Also, I think disabling inline functions and whole program optimization will help quite a lot.</p> <p>In fact, there are many dump types, maybe you could choose one small enough but still having more info <a href="http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx</a></p> <p>Those types won't help with call stack though, they only affect the amount of variables you'll be able to see.</p> <p>I noticed some of those dump types aren't supported in dbghelp.dll version 5.1 that we use. We could update it to the newest, 6.9 version though, I've just checked the EULA for MS Debugging Tools -- the newest dbghelp.dll is still ok to redistribute.</p> </blockquote>
5,681
<p>When attempting to print using the SSRS Viewer Web Part in SharePoint I get the following error.</p> <blockquote> <p>An error occured during printing. (0x8007F303)</p> </blockquote> <p>The settings we are using in this box (production) are exactly the same as the settings in testing where this works perfectly fine. </p> <p>Anyone have any good ideas or faced this before?</p>
<p>I found some ideas by Googling.</p> <ul> <li><a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=307315" rel="nofollow noreferrer">Someone had issue with "SSRS server configured for Sharepoint Integrated mode with Cumulative update package 3 for SQL Server 2005 Service Pack 2" but "the problem vanished after installing the .NET framework 3.0 SP1"</a></li> <li>You can get this error if you have <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.sqlserver.reportingsvcs&amp;tid=570c2859-0e7a-4d6d-87de-ea8576963565&amp;p=1" rel="nofollow noreferrer">"old instances of the old ReportViewer control in your web sites bin directories or anywhere else it could be accessed by your web application."</a></li> <li>It's another error 0x800C0005, but there is <a href="https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1012031&amp;SiteID=1" rel="nofollow noreferrer">an incident where the error only occurred in production environment</a>. bradsy@Microsoft says</li> </ul> <blockquote> <p>You can enable Client print logging by setting the follow reg key. Once enabled, you can look in your print users temporary (cd %temp%) directory and find a print log file. Windows</p> <p>Registry Editor Version 5.00</p> <p><code>[HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\80\Reporting Services]</code> <code>"LogRSClientPrintInfo"=dword:00000001</code></p> <p>You can send the log file to me and I can take a look to see if there is any extra information.</p> </blockquote> <p>Maybe you should collect the log and send it to the forum.</p>
<p>You may have a custom authentication in use for Reporting Services defined in your web.config. Check if that is the case, remove the custom authentication and try again.</p>
9,453
<p>Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).</p> <p>Do you know any algorithm to do this kind of job?</p>
<p>These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!</p> <p><strong>Before you begin</strong></p> <p>Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.</p> <p>Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.</p> <p><a href="https://www.mathworks.com/" rel="noreferrer">Matlab</a> is an excellent tool for testing and evaluating images.</p> <p><strong>Testing the algorithms</strong></p> <p>You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.</p> <p>The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.</p> <p>It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!</p> <p>You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.</p> <p><strong>Colour Buckets</strong></p> <p>With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':</p> <pre><code>white red blue green black </code></pre> <p>(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.</p> <p>Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.</p> <p><strong>Edge detection</strong></p> <p>How about using <a href="https://en.wikipedia.org/wiki/Edge_detection" rel="noreferrer">Edge Detection</a>. <a href="https://i.stack.imgur.com/mY9PV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mY9PV.png" alt="alt text"></a><br> <sub>(source: <a href="http://upload.wikimedia.org/wikipedia/en/thumb/8/8e/EdgeDetectionMathematica.png/500px-EdgeDetectionMathematica.png" rel="noreferrer">wikimedia.org</a>)</sub> </p> <p>With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.</p> <p>Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied <a href="https://en.wikipedia.org/wiki/Gabor_filter" rel="noreferrer">Gabor Filter</a> (a type of edge detection) in various rotations.</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Gabor-ocr.png/220px-Gabor-ocr.png" alt="alt text"></p> <p>Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves. </p> <p><strong>Regions of Interest</strong></p> <p>Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:</p> <p><a href="https://i.stack.imgur.com/Sgg79.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Sgg79.jpg" alt="alt text"></a><br> <sub>(source: <a href="http://meetthegimp.org/wp-content/uploads/2009/04/97.jpg" rel="noreferrer">meetthegimp.org</a>)</sub> </p> <p>The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.</p> <p>If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:</p> <p><a href="https://i.stack.imgur.com/z7U80.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/z7U80.jpg" alt="alt text"></a><br> <sub>(source: <a href="http://www.per2000.eu/assets/images/3_dots_black_03.jpg" rel="noreferrer">per2000.eu</a>)</sub> </p> <p>We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.</p> <p>Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.</p> <p>It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably <em>designed</em> to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.</p> <p><strong>Morphing</strong></p> <p><a href="https://en.wikipedia.org/wiki/Morphing" rel="noreferrer">Morphing</a> two images is the process of turning one image into the other through a set of steps:</p> <p><img src="https://t0.gstatic.com/images?q=tbn:ff9g8dy_q1Nr4M:http://blog.ekoventure.com/data//1498/original/morph.jpg&amp;t=1" alt="alt text"></p> <p>Note, this is different to fading one image into another!</p> <p>There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.</p> <p>Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.</p> <p>In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.</p> <p>This technique <em>could</em> work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.</p> <p><strong>Zipping</strong></p> <p>Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.</p> <p>One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.</p> <p>Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about <a href="https://computer.howstuffworks.com/file-compression.htm" rel="noreferrer">how compression works</a> will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.</p> <p><strong>Transparency</strong></p> <p>Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.</p> <p><strong>Inverting Signals</strong></p> <p>An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.</p> <p><a href="https://i.stack.imgur.com/Jq3kQ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Jq3kQ.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.themotorreport.com.au/wp-content/uploads/2008/07/noise-cancellation.gif" rel="noreferrer">themotorreport.com.au</a>)</sub> </p> <p>Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.</p> <p>However, consider two images that are equal, except one of them has a brighten effect applied to it:</p> <p><a href="https://i.stack.imgur.com/24hiI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/24hiI.jpg" alt="alt text"></a><br> <sub>(source: <a href="https://www.mcburrz.com/images/photo/brighten.jpg" rel="noreferrer">mcburrz.com</a>)</sub> </p> <p>Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.</p> <p>I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.</p> <p><strong>Tree Data structures</strong></p> <p>At first these don't seem to fit for the problem, but I think they could work.</p> <p>You could think about extracting certain properties of an image (for example colour bins) and generate a <a href="https://en.wikipedia.org/wiki/Huffman_coding" rel="noreferrer">huffman tree</a> or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.</p> <p>This probably wouldn't work, but it's an idea. The <a href="https://en.wikipedia.org/wiki/Trie" rel="noreferrer">trie datastructure</a> is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:</p> <pre><code>FFFFFF|000000|FDFD44|FFFFFF </code></pre> <p>We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.</p> <p>Comparing trie trees should be reasonably easy, and could possible provide effective results. </p> <p><strong>More ideas</strong></p> <p>I stumbled accross an interesting paper breif about <a href="https://ieeexplore.ieee.org/document/387577/?arnumber=387577" rel="noreferrer">classification of satellite imagery</a>, it outlines:</p> <blockquote> <p>Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.</p> </blockquote> <p>It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.</p> <p><strong>Other things to consider</strong></p> <p>There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.</p> <p>Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.</p> <p>Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.</p> <p>If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.</p> <p>Be careful to not fall into attempting to complete the never ending project, good luck!</p>
<p>If you're willing to consider a different approach altogether to detecting illegal copies of your images, you could consider <a href="http://www.watermarkingworld.org/faq.html" rel="nofollow noreferrer">watermarking</a>. (from 1.4)</p> <blockquote> <p>...inserts copyright information into the digital object without the loss of quality. Whenever the copyright of a digital object is in question, this information is extracted to identify the rightful owner. It is also possible to encode the identity of the original buyer along with the identity of the copyright holder, which allows tracing of any unauthorized copies.</p> </blockquote> <p>While it's also a complex field, there are techniques that allow the watermark information to persist through gross image alteration: (from 1.9)</p> <blockquote> <p>... any signal transform of reasonable strength cannot remove the watermark. Hence a pirate willing to remove the watermark will not succeed unless they debase the document too much to be of commercial interest.</p> </blockquote> <p>of course, the faq calls implementing this approach: "...very challenging" but if you succeed with it, you get a high confidence of whether the image is a copy or not, rather than a percentage likelihood.</p>
4,373
<p>I'd like to force Klipper to perform power on (using <code>M80</code>) before homing. For this purpose I'm trying to override <code>G28</code>:</p> <pre><code>[gcode_macro G28] rename_existing: G28_BASE gcode: M80 G28_BASE { rawparams } </code></pre> <p>But for some reason this does not work, I'm getting the following error:</p> <pre><code>G-Code macro rename of different types ('G28' vs 'G28_BASE') </code></pre> <p>Isn't <code>G28</code> overridable? Is there any other way to achieve the desired behavior?</p>
<p>Because of the way parameters work differently (<code>Sx</code> vs <code>NAME=x</code>) for gcode style commands vs Klipper extended ones, the rename has to be to the &quot;same type&quot; of command. <code>G28_BASE</code> does not fit the pattern to be considered a &quot;gcode style&quot; one. Use <code>G9028</code> or <code>G28.1</code> or something instead and it should work.</p>
<p>Besides using a different macro, it is also possible to use <a href="https://www.klipper3d.org/Config_Reference.html#homing_override" rel="nofollow noreferrer">[homing_override]</a> which allows you to redefine the homing sequence.</p> <p>You can write a simple homing_override like (untested!)</p> <pre><code>[homing_override] axes: xyz gcode: M80 G28 </code></pre> <p>and you are done.</p> <p>Be aware that this very simple override will home all axes every time homing is called: &quot;G28 X0&quot; will home also Y and Z. You can put checks to home only what is requested, see <a href="https://github.com/zellneralex/klipper_config/blob/master/homing.cfg" rel="nofollow noreferrer">here</a> but it become more involved.</p>
2,108
<p>I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.</p>
<p><code>std::remove</code> does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to <code>container_type::erase</code> to do the actual removal of the extra elements that are now at the end of the container:</p> <pre><code>std::vector&lt;int&gt; vec; // .. put in some values .. int int_to_remove = n; vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end()); </code></pre>
<p>If you want to do it without any extra includes: </p> <pre><code>vector&lt;IComponent*&gt; myComponents; //assume it has items in it already. void RemoveComponent(IComponent* componentToRemove) { IComponent* juggler; if (componentToRemove != NULL) { for (int currComponentIndex = 0; currComponentIndex &lt; myComponents.size(); currComponentIndex++) { if (componentToRemove == myComponents[currComponentIndex]) { //Since we don't care about order, swap with the last element, then delete it. juggler = myComponents[currComponentIndex]; myComponents[currComponentIndex] = myComponents[myComponents.size() - 1]; myComponents[myComponents.size() - 1] = juggler; //Remove it from memory and let the vector know too. myComponents.pop_back(); delete juggler; } } } } </code></pre>
6,108
<p>I have an information retrieval application that creates bit arrays on the order of 10s of million bits. The number of "set" bits in the array varies widely, from all clear to all set. Currently, I'm using a straight-forward bit array (<code>java.util.BitSet</code>), so each of my bit arrays takes several megabytes.</p> <p>My plan is to look at the cardinality of the first <em>N</em> bits, then make a decision about what data structure to use for the remainder. Clearly some data structures are better for very sparse bit arrays, and others when roughly half the bits are set (when most bits are set, I can use negation to treat it as a sparse set of zeroes). </p> <ul> <li>What structures might be good at each extreme? </li> <li>Are there any in the middle?</li> </ul> <p>Here are a few constraints or hints:</p> <ol> <li>The bits are set only once, and in index order.</li> <li>I need 100% accuracy, so something like a Bloom filter isn't good enough.</li> <li>After the set is built, I need to be able to efficiently iterate over the "set" bits.</li> <li>The bits are randomly distributed, so run-length&ndash;encoding algorithms aren't likely to be much better than a simple list of bit indexes.</li> <li>I'm trying to optimize memory utilization, but speed still carries <em>some</em> weight.</li> </ol> <p>Something with an open source Java implementation is helpful, but not strictly necessary. I'm more interested in the fundamentals.</p>
<p>Unless the data is truly random <strong><em>and</em></strong> has a symmetric 1/0 distribution, then this simply becomes a lossless data compression problem and is very analogous to CCITT Group 3 compression used for black and white (i.e.: Binary) FAX images. CCITT Group 3 uses a Huffman Coding scheme. In the case of FAX they are using a fixed set of Huffman codes, but for a given data set, you can generate a specific set of codes for each data set to improve the compression ratio achieved. As long as you only need to access the bits sequentially, as you implied, this will be a pretty efficient approach. Random access would create some additional challenges, but you could probably generate a binary search tree index to various offset points in the array that would allow you to get close to the desired location and then walk in from there.</p> <p><strong><em>Note</em></strong>: The Huffman scheme still works well even if the data is random, as long as the 1/0 distribution is not perfectly even. That is, the less even the distribution, the better the compression ratio.</p> <p>Finally, if the bits are truly random with an even distribution, then, well, according to <em>Mr. Claude Shannon</em>, you are not going to be able to compress it any significant amount using any scheme.</p>
<p>Straight forward lossless compression is the way to go. To make it searchable you will have to compress relatively small blocks and create an index into an array of the blocks. This index can contain the bit offset of the starting bit in each block.</p>
5,676
<p>I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process.</p> <p>I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain.</p> <p>When this crash happens, where can I find the crash dump for analysis?</p>
<p>Download Debugging tools for Windows: <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx" rel="noreferrer">http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx</a></p> <p>Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES: <a href="http://support.microsoft.com/kb/286350" rel="noreferrer">http://support.microsoft.com/kb/286350</a></p> <p>The command should be something like (if you are using IIS6):</p> <pre><code>cscript adplus.vbs -crash -pn w3wp.exe </code></pre> <p>This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a *.DMP file).</p> <p>You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump...</p> <p>By default, WinDBG will show you (next to the command line) the thread were the process crashed.</p> <p>The first thing you need to do in WinDBG is to load the .NET Framework extensions:</p> <pre><code>.loadby sos mscorwks </code></pre> <p>then, you will display the managed callstack:</p> <pre><code>!clrstack </code></pre> <p>if the thread was not running managed code, then you'll need to check the native stack:</p> <pre><code>kpn 200 </code></pre> <p>This should give you some ideas. To continue troubleshooting I recommend you read the following article:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ee817663.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ee817663.aspx</a></p>
<p>A quick search found <a href="http://www.iisfaq.com/default.aspx?view=P197" rel="nofollow noreferrer">IISState</a> - it relies on the <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow noreferrer">Windows debugging tools</a> and needs to be running when a crash occurs, but given the circumstances you've described, this shouldn't be a problem,</p>
7,688
<p>My designer keeps throwing out the term "liquid" layout. What does this mean?</p> <p><strong>Thanks for the clarification, I have always just called this a percentage layout, and thought he was saying that the pieces could be moved around, and that was liquid</strong></p>
<p>A "liquid" layout is a site layout that expands to fill the entire available area as the browser window is resized. Typically this is done using CSS. Liquid layouts can be quite helpful for certain types of sites, but they also tend to be significantly more effort than fixed width layouts, and their usefulness depends on the site content and how well implemented they are.</p>
<p>Liquid Layouts refer to the design concept of a website. A liquid layout will move in and out when you resize your browser window, due to is having percentages and relative widths in the CSS.</p>
8,772
<p>In FlashPrint there is an <strong>Extrusion Ratio</strong> setting. It's set to 97 % for the stock PLA profile and 107 % for the stock PETG profile.</p> <p>I would've thought these would be 100 % by default (and the same for all materials). Why is it that these defaults make sense and they differ? Why would you need to push more PETG for the same print than PLA if they're the same diameter filament?</p> <p><a href="https://i.stack.imgur.com/fiXhW.png" rel="nofollow noreferrer" title="FlashPrint Extrusion Ratio setting"><img src="https://i.stack.imgur.com/fiXhW.png" alt="FlashPrint Extrusion Ratio setting" title="FlashPrint Extrusion Ratio setting" /></a></p>
<p>If your extruder uses spring tension to hold the filament against the hob, the effective diameter of the filament at the point the hob contacts, which determines the amount moved, is a function of the compressibility of the material. Thus, it makes sense to use a higher flow ratio for more compressible filaments. However, this is very much a matter of what type of extruder your machine has, and doesn't apply if you have a tension arm holding the idler bearing at fixed distance from the hob.</p>
<p>I may be entirely out of my league here, But I think it's related to Viscosity, or how thin or thick the fluid plastic is while hot and Temperature Expansion, how much larger in volume the fluid plastic will be hot compared to cold.</p>
2,006
<p>What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.</p> <p>CLR integration isn't an option for me either.</p> <p>The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)</p>
<p>Create two tables and then join to them to convert stored GMT dates to local time:</p> <pre><code>TimeZones e.g. --------- ---- TimeZoneId 19 Name Eastern (GMT -5) Offset -5 </code></pre> <p>Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future)</p> <pre><code>DaylightSavings --------------- TimeZoneId 19 BeginDst 3/9/2008 2:00 AM EndDst 11/2/2008 2:00 AM </code></pre> <p>Join them like this:</p> <pre><code>inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst </code></pre> <p>Convert dates like this:</p> <pre><code>dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert) </code></pre>
<p>Maintain a TimeZone table, or shell out with an extended stored proc (xp_cmdshell or a COM component, or your own) and ask the OS to do it. If you go the xp route, you'd probably want to cache the offset for a day.</p>
4,442
<p>For a university project, my partner and I need to print the robot Poppy. This is an open source robotic project, <a href="https://www.poppy-project.org/fr/" rel="nofollow noreferrer">poppy-project.org</a>.</p> <p>We are printing it with a double extruder SpiderBot with PLA and HIPS as support material. Our principal issue is the weakness of the pieces we print.</p> <p>It prevents us from removing the support material without damaging the piece. We don't have the chemicals to dissolve HIPS.</p> <p>Have you some advice to make the pieces stronger, or a more gentle method to remove the HIPS?</p> <p>Thanks for the replies</p>
<p>Having a bit more experience since my comment post above, I can offer up a possible solution. If your printer is able to print ABS, it works great with HIPS as support material. I've been printing boatloads of ABS models. When support is needed, the HIPS supports will bond reasonably well to the ABS, but when cooled, flick off with a sharp pointed instrument such as a razor knife point.</p> <p>As an additional reference, a good bond to the print bed is required for both ABS and HIPS and if your slicer allows support density adjustment, increase the support in that manner. My slicer (Simplify3D) would print an accordian type of support unless instructed otherwise. I set up for alternating 45° patterns making a denser but also more vertically rigid structure.</p> <p>If you cannot print ABS, PLA and PVA as Ogre55 suggests is about your only option. I see from the 'net that the SpiderBot Pro supports ABS, which implies the basic version might not have a heated bed.</p>
<p>Why not try using PVA(Polyvinyl alcohol) for support material.</p> <p>I use it for my support material with PLA, and it dissolves in water.</p> <p>here is a link to some on Amazon.<br> <a href="https://smile.amazon.com/eSUN-1-75mm-filament-natural-0-5kg/dp/B00MVIQASU/ref=sr_1_3?s=industrial&amp;ie=UTF8&amp;qid=1508539512&amp;sr=1-3&amp;keywords=PVA" rel="nofollow noreferrer">https://smile.amazon.com/eSUN-1-75mm-filament-natural-0-5kg/dp/B00MVIQASU/ref=sr_1_3?s=industrial&amp;ie=UTF8&amp;qid=1508539512&amp;sr=1-3&amp;keywords=PVA</a></p>
579
<p>Is it possible to use an UnhandledException Handler in a Windows Service?</p> <p>Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:</p> <pre> <code> Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work. Try MyServiceComponent.Start() Catch ex As Exception 'call into our exception handler MyExceptionHandlingComponent.ManuallyHandleException (ex) 'zero is the default ExitCode for a successfull exit, so if we set it to non-zero ExitCode = -1 'So, we use Environment.Exit, it seems to be the most appropriate thing to use 'we pass an exit code here as well, just in case. System.Environment.Exit(-1) End Try End Sub </code> </pre> <p>Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?</p>
<p>Ok, I’ve done a little more research into this now. When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to. These methods are invoked from within the base class so I did a little poking around with reflector. OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine "System.ServiceProcess, Version=2.0.0.0" decompiles like this:</p> <pre> <code> Private Sub ServiceQueuedMainCallback(ByVal state As Object) Dim args As String() = DirectCast(state, String()) Try Me.OnStart(args) Me.WriteEventLogEntry(Res.GetString("StartSuccessful")) Me.status.checkPoint = 0 Me.status.waitHint = 0 Me.status.currentState = 4 Catch exception As Exception Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { exception.ToString }), EventLogEntryType.Error) Me.status.currentState = 1 Catch obj1 As Object Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { String.Empty }), EventLogEntryType.Error) Me.status.currentState = 1 End Try Me.startCompletedSignal.Set End Sub </code> </pre> <p>So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine. The other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way.</p> <p>So I ‘think’ that explains why my Exception Handling component can’t catch UnhandledException on Start and Stop, but I’m not sure if it explains why timers that are setup in OnStart can’t cause an UnhandledException when they fire. </p>
<p>You can subscribe to the <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx" rel="nofollow noreferrer">AppDomain.UnhandledException event</a>. If you have a message loop, you can tie to the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="nofollow noreferrer">Application.ThreadException event</a>.</p>
8,264
<p>I'm not sure what the correct size should be.</p> <p>Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source.</p> <p><a href="http://www.hanselman.com/blog/MakeYourWebsiteMobileAndIPhoneFriendlyAddHomeScreenIPhoneIconsAndAdjustTheViewPort.aspx" rel="noreferrer">Hanselman</a>'s and <a href="http://playgroundblues.com/posts/2008/jan/15/iphone-bookmark-iconage/" rel="noreferrer">playgroundblues</a>'s comments suggest different sizes including 163x163 and 60x60.</p> <p>Apple's own <a href="http://www.apple.com/apple-touch-icon.png" rel="noreferrer">apple.com icon</a> is 129x129!</p> <p>See my related question: <a href="https://stackoverflow.com/questions/1505/how-do-i-give-my-web-sites-an-icon-for-iphone">How do I give my web sites an icon for iPhone?</a></p>
<p>It seems that Apple guidelines as of August 3, 2010 now include the "High resolution" images (for iPhone 4) in their "required" icon sizes.</p> <p>Looks like we need to provide both a 57x57 and a 114x114 image now, as well as a 640x960 title image.</p> <p>See <a href="http://developer.apple.com/iphone/library/documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW2" rel="nofollow noreferrer">Custom Icon and Image Creation Guidelines</a> (Javascript required) which is part of a whole document:</p> <ul> <li><a href="https://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/MobileHIG.pdf" rel="nofollow noreferrer">iOS Human Interface Guidelines (2013; by Apple Inc; PDF; 26,3 MB)</a></li> </ul>
<p>I don't think there is a "correct size". Since the iPhone really is running OSX, the icon rendering system is pretty robust. As long as you give it a high-quality image with the right aspect ratio and a resolution at least as high as the actual output will be, the OS will downscale very cleanly. My site uses a 158x158 and the icon looks pixel-perfect on the iPhone screen.</p>
2,391
<p>Are there any documented techniques for speeding up mySQL dumps and imports?</p> <p>This would include my.cnf settings, using ramdisks, etc. </p> <p>Looking only for documented techniques, preferably with benchmarks showing potential speed-up.</p>
<ol> <li>Get a copy of <em>High Performance MySQL</em>. Great book. </li> <li>Extended inserts in dumps </li> <li>Dump with --tab format so you can use mysqlimport, which is faster than mysql &lt; dumpfile</li> <li>Import with multiple threads, one for each table.</li> <li>Use a different database engine if possible. importing into a heavily transactional engine like innodb is awfully slow. Inserting into a non-transactional engine like MyISAM is much much faster.</li> <li>Look at the table compare script in the Maakit toolkit and see if you can update your tables rather than dumping them and importing them. But you're probably talking about backups/restores.</li> </ol>
<p>Using indexes but not too much, activate query cache, using sphinx for big database, here is some good tips <a href="http://www.keedeo.com/media/1857/26-astuces-pour-accelerer-vos-requetes-mysql" rel="nofollow">http://www.keedeo.com/media/1857/26-astuces-pour-accelerer-vos-requetes-mysql</a> (In French)</p>
9,270
<p>Trying to do this sort of thing...</p> <pre><code>WHERE username LIKE '%$str%' </code></pre> <p>...but using bound parameters to prepared statements in PDO. e.g.:</p> <pre><code>$query = $db-&gt;prepare("select * from comments where comment like :search"); $query-&gt;bindParam(':search', $str); $query-&gt;execute(); </code></pre> <p>I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.</p> <p>I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?</p>
<p>Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:</p> <pre><code>$str = "%$str%"; $query = $db-&gt;prepare("select * from comments where comment like :search"); $query-&gt;bindParam(':search', $str); $query-&gt;execute(); </code></pre>
<p>5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:</p> <pre><code>$query = $db-&gt;prepare("select * FROM table WHERE field LIKE CONCAT('%',:search,'%')"); $query-&gt;bindParam(':search', $str); $query-&gt;execute(); </code></pre> <p>I'm not sure if there will be a performance hit due to the overhead of calling the <code>CONCAT</code> function, but I wanted to pass this along as an option. Hopefully it will help someone.</p>
8,579
<p>I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.</p> <p>Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.</p> <p>Here's a screenshot of it currently.</p> <p><img src="https://i.stack.imgur.com/XK48E.png" alt="ISO Address"></p> <p>Any ideas?</p> <hr> <p>@Chris</p> <p>A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.</p> <p>I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.</p> <p>I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).</p> <p>It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.</p> <p>Though if someone comes up with another way to approach the problem I'm open to that too.</p> <hr> <p>I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.</p> <pre><code>resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0; $A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines }) $('iso_address').rows = linecount; }; </code></pre>
<p>Facebook does it, when you write on people's walls, but only resizes vertically.</p> <p>Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.</p> <p>None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.</p> <p>Some JavaScript code to do it, using <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype</a> (because that's what I'm familiar with):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script language="javascript"&gt; google.load('prototype', '1.6.0.2'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;textarea id="text-area" rows="1" cols="50"&gt;&lt;/textarea&gt; &lt;script type="text/javascript" language="javascript"&gt; resizeIt = function() { var str = $('text-area').value; var cols = $('text-area').cols; var linecount = 0; $A(str.split("\n")).each( function(l) { linecount += Math.ceil( l.length / cols ); // Take into account long lines }) $('text-area').rows = linecount + 1; }; // You could attach to keyUp, etc. if keydown doesn't work Event.observe('text-area', 'keydown', resizeIt ); resizeIt(); //Initial on load &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.</p>
<p>Here is an extension to the Prototype widget that Jeremy posted on June 4th:</p> <p>It stops the user from entering more characters if you're using limits in textareas. It checks if there are characters left. If the user copies text into the textarea, the text is cut off at the max. length:</p> <pre><code>/** * Prototype Widget: Textarea * Automatically resizes a textarea and displays the number of remaining chars * * From: http://stackoverflow.com/questions/7477/autosizing-textarea * Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js */ if (window.Widget == undefined) window.Widget = {}; Widget.Textarea = Class.create({ initialize: function(textarea, options){ this.textarea = $(textarea); this.options = $H({ 'min_height' : 30, 'max_length' : 400 }).update(options); this.textarea.observe('keyup', this.refresh.bind(this)); this._shadow = new Element('div').setStyle({ lineHeight : this.textarea.getStyle('lineHeight'), fontSize : this.textarea.getStyle('fontSize'), fontFamily : this.textarea.getStyle('fontFamily'), position : 'absolute', top: '-10000px', left: '-10000px', width: this.textarea.getWidth() + 'px' }); this.textarea.insert({ after: this._shadow }); this._remainingCharacters = new Element('p').addClassName('remainingCharacters'); this.textarea.insert({after: this._remainingCharacters}); this.refresh(); }, refresh: function(){ this._shadow.update($F(this.textarea).replace(/\n/g, '&lt;br/&gt;')); this.textarea.setStyle({ height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px' }); // Keep the text/character count inside the limits: if($F(this.textarea).length &gt; this.options.get('max_length')){ text = $F(this.textarea).substring(0, this.options.get('max_length')); this.textarea.value = text; return false; } var remaining = this.options.get('max_length') - $F(this.textarea).length; this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining')); } }); </code></pre>
2,901
<p>I am looking for a (preferably) command-line tool that can reformat the C# source code on a directory tree. Ideally, I should be able to customize the formatting. Bonus points if the tool can be run on <a href="https://en.wikipedia.org/wiki/Mono_%28software%29" rel="nofollow noreferrer">Mono</a> (or Linux).</p>
<p>You could also try <a href="http://www.narrange.net" rel="nofollow noreferrer">NArrange</a> to reformat your code. The formatting options it supports are still pretty limited, but it can process an entire directory and is a command-line tool. Also, NArrange runs under Mono.</p>
<p>For completeness, check out <a href="http://uncrustify.sourceforge.net/" rel="nofollow noreferrer">http://uncrustify.sourceforge.net/</a></p>
4,690
<p>I have a framework written in Perl that sets a bunch of environment variables to support interprocess (typically it is sub process) communication. We keep a sets of key/value pairs in XML-ish files. We tried to make the key names camel-case <code>somethingLikeThis</code>. This all works well.</p> <p>Recently we have had occasion to pass control (chain) processes from Windows to UNIX. When we spit out the <code>%ENV</code> hash to a file from Windows the <code>somethingLikeThis</code> key becomes <code>SOMETHINGLIKETHIS</code>. When the Unix process picks up the file and reloads the environment and looks up the value of <code>$ENV{somethingLikeThis}</code> it does not exist since UNIX is case sensitive (from the Windows side the same code works fine). </p> <p>We have since gone back and changed all the keys to UPPERCASE and solved the problem, but that was tedious and caused pain to the users. Is there a way to make Perl on Windows preserve the character case of the keys of the environment hash?</p>
<p>As far as I remember, using ALL_CAPS for environment variables is the recommended practice in both Windows and *NIX worlds. My guess is Perl is just using some kind of legacy API to access the environment, and thus only retrieves the upper-case-only name for the variable.</p> <p>In any case, you should never rely on something like that, even more so if you are asking your users to set up the variables, just imagine how much aggravation and confusion a simple misspelt variable would produce! You have to remember that some OSes that will remain nameless have not still learned how to do case sensitive files...</p>
<p>Jack M.: Agreed, it is not a problem on Windows. If I create an environment variable Foo I can reference it in Perl as $ENV{FOO} or $ENV{fOO} or $ENV{foo}. The problem is: I create it as Foo and dump the entire %ENV to a file and then read in the file from *NX to recreate the Environment hash and use the same script to reference $ENV{Foo}, that hash value does not exist (the $ENV{FOO} does exist). </p> <p>We had adopted the all UPPERCASE workaround that davidg suggested. I was just wondering if there was ANY way to "preserve case" when writing out the keys to the %ENV hash from Perl on Windows.</p>
6,220
<p>I've created a simple desktop application in C# 3.0 to learn some C#, wpf and .Net 3.5. My application essentially reads data from a csv file and stores it in a SQL server CE database. I use sqlmetal to generate the ORM code for the database. My first iteration of this app is ugly as hell and I'm in the process of refactoring it.</p> <p>Which brings me to my question. How would you architect a desktop database app in C#? What are the best practices?</p> <p>Do you create a Database Abstraction Layer (DAL) which uses the sqlmetal generated code? Or is the generated code enough of an abstraction?</p> <p>If you use DAL pattern, do you make it a singleton or a static member? Do you use the View-Model-ModelView pattern with the DAL pattern?</p> <p>Apologies if this seems like a long open ended question, but I have been giving this a lot of thought recently. I see a lot of examples on how to architect an enterprise n-tier app in C# but not that many on architecting standalone desktop apps.</p>
<p>I would start with the <a href="http://codeplex.com/CompositeWPF" rel="nofollow noreferrer">Composite Application Guidance for WPF</a> (<em>cough</em> PRISM <em>cough</em>) from Microsoft's P&amp;P team. With the download comes a great reference application that is the starting point for most of my WPF development today.</p> <p>The <a href="http://www.dotnetrocks.com/default.aspx?showNum=374" rel="nofollow noreferrer">DotNetRocks crew</a> just interviewed <a href="http://blogs.msdn.com/gblock/" rel="nofollow noreferrer">Glenn Block</a> and <a href="http://www.softinsight.com/bnoyes/" rel="nofollow noreferrer">Brian Noyes</a> about this if you're interested in hearing more from them.</p> <p>Even better, Prism is not nearly as heavy as the CAB was, if you're familiar at all with that from the WinForms days.</p>
<p>I would say yes, it could easily be structured towards smaller applications. There is a learning curve towards getting started, but honestly, it helped me understand WPF better than attempting to start from scratch. After starting a project with CompositeWPF and then starting another project without it, I found myself attempting to duplicate features of CompositeWPF on my own because I missed those features! :)</p>
6,770
<p>I have just got a Monoprice Maker Select 3d printer (which is really just a Wanhao Duplicator i3). </p> <p>I want to print a model that came on the included SD card (<code>1.gcode</code>) with ABS filament. I first press "<code>Preheat ABS</code>" and wait for the display to show the correct temperatures, 245°C for the extruder and 90°C for the print bed. Then, I mount the SD card and select the file to print. </p> <p>However, once I do that, the "goal" temperatures change to 195°C for the extruder and 50°C for the print bed, and the temperatures reported by the printer gradually go down as the printer waits for it to match the "goal" temperature. This results in a failed print, with the filament sticking to the extruder in a clump. </p> <p>What is going on here? I am trying PLA with the same file, and it seems to work fine, although the temperature change still occurs. </p>
<p>The demo files are gcode files generated for use with the sample PLA that comes with the printer. If you want to print it with ABS select the file and set the temperature manually afterwards. </p>
<p>If you want to use the demo files, you can probably pause the print as soon as it starts, and manually set the extruder temperatures before resuming the print. Easier to generate new g-code though.</p>
465
<p>In the SSW rules to better SQL Server Database there is an example of a full database maintenance plan: <a href="http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterSQLServerDatabases.aspx#MaintenancePlan" rel="noreferrer">SSW</a>. In the example they run both a Reorganize Index and then a Rebuild Index and then Update Statistics. Is there any point to this? I thought Reorganize Index was a fast but less effective version of Rebuild Index? and that an index rebuild would also update the statistics automatically (on the clustered index at least).</p>
<p>Doing a <code>REORGANIZE</code> and then a <code>REBUILD</code> on the same indexes is pointless, as any changes by the <code>REORGANIZE</code> would be lost by doing the <code>REBUILD</code>.</p> <p>Worse than that is that in the maintenance plan diagram from SSW, it performs a <code>SHRINK</code> first, which fragments the indexes as a side effect of the way it releases space. Then the <code>REBUILD</code> allocates more space to the database files again as working space during the <code>REBUILD</code> operation.</p> <ul> <li><p><code>REORGANIZE</code> is an online operation that defragments leaf pages in a clustered or non-clustered index page by page using little extra working space.</p></li> <li><p><code>REBUILD</code> is an online operation in Enterprise editions, offline in other editions, and uses as much extra working space again as the index size. It creates a new copy of the index and then drops the old one, thus getting rid of fragmentation. Statistics are recomputed by default as part of this operation, but that can be disabled.</p></li> </ul> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms189858.aspx" rel="noreferrer">Reorganizing and Rebuilding Indexes</a> for more information.</p> <p>Don't use <code>SHRINK</code> except with the <code>TRUNCATEONLY</code> option and even then if the file will grow again then you should think hard as to whether it's necessary:</p> <p><a href="http://www.sqlservercentral.com/articles/SHRINKFILE/71414/" rel="noreferrer">sqlservercentral_SHRINKFILE</a> </p>
<p>My two cents... This method follows the spec outlined on tech net: <a href="http://technet.microsoft.com/en-us/library/ms189858(v=sql.105).aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms189858(v=sql.105).aspx</a></p> <pre><code>USE [MyDbName] GO SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER OFF GO CREATE PROCEDURE [maintenance].[IndexFragmentationCleanup] AS DECLARE @reIndexRequest VARCHAR(1000) DECLARE reIndexList CURSOR FOR SELECT INDEX_PROCESS FROM ( SELECT CASE WHEN avg_fragmentation_in_percent BETWEEN 5 AND 30 THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REORGANIZE;' WHEN avg_fragmentation_in_percent &gt; 30 THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REBUILD with(ONLINE=ON);' END AS INDEX_PROCESS ,avg_fragmentation_in_percent ,t.NAME FROM sys.dm_db_index_physical_stats(NULL, NULL, NULL, NULL, NULL) AS a INNER JOIN sys.indexes AS i ON a.object_id = i.object_id AND a.index_id = i.index_id INNER JOIN sys.tables t ON t.object_id = i.object_id WHERE i.NAME IS NOT NULL ) PROCESS WHERE PROCESS.INDEX_PROCESS IS NOT NULL ORDER BY avg_fragmentation_in_percent DESC OPEN reIndexList FETCH NEXT FROM reIndexList INTO @reIndexRequest WHILE @@FETCH_STATUS = 0 BEGIN BEGIN TRY PRINT @reIndexRequest; EXEC (@reIndexRequest); END TRY BEGIN CATCH DECLARE @ErrorMessage NVARCHAR(4000); DECLARE @ErrorSeverity INT; DECLARE @ErrorState INT; SELECT @ErrorMessage = 'UNABLE TO CLEAN UP INDEX WITH: ' + @reIndexRequest + ': MESSAGE GIVEN: ' + ERROR_MESSAGE() ,@ErrorSeverity = 9 ,@ErrorState = ERROR_STATE(); END CATCH; FETCH NEXT FROM reIndexList INTO @reIndexRequest END CLOSE reIndexList; DEALLOCATE reIndexList; RETURN 0 GO </code></pre>
2,912
<p>Lets say I have a loop in Bash:</p> <pre><code>for foo in `some-command` do do-something $foo done </code></pre> <p><code>do-something</code> is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 <code>do-something</code>'s at once.</p> <p>The naive approach seems to be:</p> <pre><code>for foo in `some-command` do do-something $foo &amp; done </code></pre> <p>This will run <em>all</em> <code>do-something</code>s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing <em>all</em> at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the <code>do-something</code>s are finished.</p> <p>How would you write this loop so there are always X <code>do-something</code>s running at once?</p>
<p>Depending on what you want to do xargs also can help (here: converting documents with pdf2ps):</p> <pre><code>cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w ) find . -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps </code></pre> <p>From the docs:</p> <pre><code>--max-procs=max-procs -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done. </code></pre>
<p>$DOMAINS = "list of some domain in commands" for foo in <code>some-command</code> do</p> <pre><code>eval `some-command for $DOMAINS` &amp; job[$i]=$! i=$(( i + 1)) </code></pre> <p>done</p> <p>Ndomains=<code>echo $DOMAINS |wc -w</code></p> <p>for i in $(seq 1 1 $Ndomains) do echo "wait for ${job[$i]}" wait "${job[$i]}" done</p> <p>in this concept will work for the parallelize. important thing is last line of eval is '&amp;' which will put the commands to backgrounds.</p>
5,906