instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>How do you usually convert line breaks in a form textbox or input=text element to html line breaks?</p>
<p>Thanks</p>
<p>Edit: Is it always \r\n with all browsers?</p>
|
<p>Or in C#:</p>
<pre><code>myString.Replace("\r\n", "<br />");
</code></pre>
<p>If you're worried about it being different on different platforms, you could also do: </p>
<pre><code>myString.Replace("\r\n", "<br />");
myString.Replace("\n", "<br />");
myString.Replace("\r", "<br />");
</code></pre>
|
<p>You will most likely have to escape the back slashes for it to behave the way you are expecting.</p>
<pre><code>MyString.Replace("\\r\\n", "<br />")
</code></pre>
<p>or </p>
<pre><code>MyString.Replace("\\r\\n", Environment.NewLine)
</code></pre>
| 45,799
|
<p>I noticed that the generic <code>IEnumerator<T></code> inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?</p>
<p>Usually, we use foreach statement to go through a <code>IEnumerator<T></code> instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally. </p>
|
<p>Basically it was an oversight. In C# 1.0, <code>foreach</code> <em>never</em> called <code>Dispose</code> <sup>1</sup>. With C# 1.2 (introduced in VS2003 - there's no 1.1, bizarrely) <code>foreach</code> began to check in the <code>finally</code> block whether or not the iterator implemented <code>IDisposable</code> - they had to do it that way, because retrospectively making <code>IEnumerator</code> extend <code>IDisposable</code> would have broken everyone's implementation of <code>IEnumerator</code>. If they'd worked out that it's useful for <code>foreach</code> to dispose of iterators in the first place, I'm sure <code>IEnumerator</code> would have extended <code>IDisposable</code>.</p>
<p>When C# 2.0 and .NET 2.0 came out, however, they had a fresh opportunity - new interface, new inheritance. It makes much more sense to have the interface extend <code>IDisposable</code> so that you don't need an execution-time check in the finally block, and now the compiler knows that if the iterator is an <code>IEnumerator<T></code> it can emit an unconditional call to <code>Dispose</code>.</p>
<p>EDIT: It's incredibly useful for <code>Dispose</code> to be called at the end of iteration (however it ends). It means the iterator can hold on to resources - which makes it feasible for it to, say, read a file line by line. Iterator blocks generate <code>Dispose</code> implementations which make sure that any <code>finally</code> blocks relevant to the "current point of execution" of the iterator are executed when it's disposed - so you can write normal code within the iterator and clean-up should happen appropriately.</p>
<hr>
<p><sup>1</sup> Looking back at the 1.0 spec, it was already specified. I haven't yet been able to verify this earlier statement that the 1.0 implementation didn't call <code>Dispose</code>.</p>
|
<p>IIRC The whole thing about having <code>IEnumerable<T></code> and <code>IEnumerable</code> is a result of <code>IEnumerable</code> predating .Net's template stuff. I suspect that your question is in the same way.</p>
| 28,779
|
<p>JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? </p>
<p><em>Edit:</em> Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?</p>
<p><em>Edit 2:</em> Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, <strong>what is the point of HttpOnly</strong>?</p>
<p><em>Edit 3:</em> Here is a quote from Wikipedia:</p>
<blockquote>
<p>When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The <code>HttpOnly</code> flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].</p>
</blockquote>
<p>I understand that <code>document.cookie</code> is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? </p>
<p>In your example, I cannot write to your <code>document.cookie</code>, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.</p>
<pre><code><script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
</code></pre>
<p><em>Edit 4:</em> Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...</p>
<p><em>Final Edit:</em> Ahh, apparently both sites are wrong, this is actually a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=380418" rel="noreferrer">bug in FireFox</a>. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.</p>
<p>To reiterate everything I've learned:</p>
<ul>
<li>HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)</li>
<li>HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.</li>
<li>XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.</li>
</ul>
<p><em>edit: This information is likely no longer up to date.</em></p>
|
<p>Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server.</p>
<p>In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the "vote" controller method.</p>
<p>More generally, cookies are <strong>not</strong> required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.</p>
<p>However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.</p>
<blockquote>
<p>In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.</p>
</blockquote>
<p>XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on).</p>
<p>You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible.</p>
<p>Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie.</p>
<blockquote>
<p>Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?</p>
</blockquote>
<p>Consider this scenario:</p>
<ul>
<li>I find an avenue to inject JavaScript code into the page.</li>
<li>Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.</li>
<li>Jeff submits a stellar answer to your question.</li>
<li>Because he submits it with my cookie data instead of his, the answer will become mine.</li>
<li>You vote up "my" stellar answer.</li>
<li>My real account gets the point.</li>
</ul>
<p>With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.</p>
<blockquote>
<p>Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...</p>
</blockquote>
<p>That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.</p>
<p>However, if you go back to my example scenario, you can see where HTTP-Only <em>does</em> successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon).</p>
<p>It boils down to the fact that a) no single improvement will solve <em>all</em> vulnerabilities and b) no system will <em>ever</em> be completely secure. HTTP-Only <strong>is</strong> a useful tool in shoring up against XSS.</p>
<p>Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction.</p>
|
<p>No, the page that the AJAX call requests has access to cookies too & that's what checks whether you're logged in.</p>
<p>You can do other authentication with the Javascript, but I wouldn't trust it, I always prefer putting any sort of authentication checking in the back-end.</p>
| 4,764
|
<p>Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops?</p>
<p>(this question is specific, not about optimization in general, thanks)</p>
|
<p>It works by placing extra code to count the number of times each codepath is taken. When you compile a second time the compiler uses the knowledge gained about execution of your program that it could only guess at before. There are a couple things PGO can work toward:</p>
<ul>
<li>Deciding which functions should be inlined or not depending on how often they are called.</li>
<li>Deciding how to place hints about which branch of an "if" statement should be predicted on based on the percentage of calls going one way or the other.</li>
<li>Deciding how to optimize loops based on how many iterations get taken each time that loop is called.</li>
</ul>
<p>You never really know how much these things can help until you test it.</p>
|
<p>The fun thing about optimization is that speed gains are found in the unlikeliest of places.</p>
<p>It's also the reason you need a profiler, rather than guessing where the speed problems are.</p>
<p>I recommend starting with a profiler (<code>gperf</code> if you're using GCC) and just start poking around the results of running your application through some normal operations.</p>
| 7,578
|
<p>ExtJS has Ext.each() function, but is there a map() also hidden somewhere?</p>
<p>I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.</p>
<p>Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:</p>
<pre><code>Ext.map = function(arr, f) { ... };
</code></pre>
<p>But is this really the correct way to do this?</p>
|
<p>It appears, that my colleges here are using <a href="http://code.google.com/p/ext-basex/" rel="nofollow noreferrer">ext-basex</a>, which extends Array.prototype with map() and other methods.</p>
<p>So I can just write:</p>
<pre><code>[1, 2, 3].map( function(){ ... } );
</code></pre>
<p>Problem solved.</p>
|
<p>ExtJS doesn't replace Javascript language itself. Array functions aren't in the focus of ExtJS core. However there is a special Ext.Array object type. You can extend it on your own.</p>
<p>EDIT: Not Ext.Array, but just extended Array object.</p>
| 31,344
|
<p>I'm helping a typical small company that started with a couple of outsourced systems (google apps, svn/trac). added an internal jabber server (ejabber for mostly iChat clients). subscribes to a couple of webservices (e.g. highrisehq). and has a vpn service provided by a pfsense freebsd firewall.</p>
<p>And the net result of all this is that they're drowning in passwords and accounts. </p>
<p>It seems that if they had a single unified login / single signon service they could go a long way to combining these. E.g.: ldap as the master repository, radius linked to it for vpn, ejabber and even WPA2 wireless access, plugins for google app sign on, and perhaps an openid server for external websites like highrisehq.</p>
<p>It seems that all these tools exist separately, but does anyone know of a single box that combines them with a nice GUI and auto-updates? (e.g. like pfsense/m0n0wall for firewalls, freeNAS for storage). It doesn't have to be FOSS. A paid box would be fine too.</p>
<p>I figure this must exist. Microsoft's Active Directory is likely one solution but they'd rather avoid Windows if possible. There seem to be various "AAA" servers that ISPs use or for enterprise firewall/router management, but that doesn't seem quite right.</p>
<p>Any obvious solutions I'm missing? Thanks!</p>
|
<p>It's been over a year since you originaly asked the question, so I'm guessing you've solved your problem by now. But if someone else is interested in a possible solution I suggest the following:</p>
<p>First of all, I don't know of any "all in one" solution to your problem. However it's quite easy to combine three products that will solve all of your needs and provide a single source for User management and password storage.</p>
<p>The first thing to do is install an LDAP Directory to manage Users and Groups (and possibly other objects outside the scope of your question). This can be <a href="http://www.openldap.org/" rel="nofollow noreferrer">OpenLDAP</a>, <a href="http://directory.apache.org/" rel="nofollow noreferrer">Apache DS</a>, Microsoft Active Directory, etc. Basically any LDAP Server will do.</p>
<p>Second I recommend installing <a href="http://freeradius.org/" rel="nofollow noreferrer">FreeRADIUS</a> with the <a href="http://www.ibm.com/developerworks/library/l-radius/" rel="nofollow noreferrer">LDAP Directory configured</a> as it's backend Service.</p>
<p>Third get a license of <a href="http://www.atlassian.com/software/crowd/" rel="nofollow noreferrer">Atlassian Crowd</a>. It provides OpenID and Google Apps authentication. Prices for up to 50 Users start at $10 and go all the way up to $8000 for an unlimited user license. </p>
<p>Installation and Configuration of the three is relatively easy. You'll probably put most work into creating your Users and Groups. You can install all three components on a single Server and end up with a box that allows you to authenticate pretty much everything from Desktop Login, over Google Apps and other Web Apps, down to VPN and even Switch, WiFi and Router Login.</p>
<p>Just make sure you configure your Roles and Groups wisely! Otherwise you might end up with some Sales Person being able to do administration on your Firewalls and Routers :-)</p>
|
<p>This is something I was looking for as well, and <a href="http://www.turnkeylinux.org/openldap" rel="nofollow">http://www.turnkeylinux.org/openldap</a> looks like the solution: "appliance" installation, and it includes encrypted online backup which is easily restored to a new or replacement machine. </p>
| 41,364
|
<p>Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site?</p>
|
<p>There is a good article describing custom actions here:
<a href="http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx" rel="nofollow noreferrer">ScottGu's Blog</a></p>
<p>The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate:</p>
<pre><code>Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)
Try
Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir))
IISVdir.Properties.Item("AppPoolId").Item(0) = appPool
IISVdir.CommitChanges()
Catch ex As Exception
Throw ex
End Try
End Sub
Private strServer As String = "localhost"
Private strRootSubPath As String = "/W3SVC/1/Root"
Private strSchema As String = "IIsWebVirtualDir"
Public Overrides Sub Install(ByVal stateSaver As IDictionary)
MyBase.Install(stateSaver)
Try
Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString
Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString
Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString)
Catch ex As Exception
Throw ex
End Try
End Sub
</code></pre>
<p>...Where APPPOOL is supplied as an argument in the Custom Action.</p>
|
<p>You can use a CustomAction to modify IIS during deployment, Here is an article how to do it:
<a href="http://msdn.microsoft.com/en-us/library/aa289522.aspx" rel="nofollow noreferrer">Modifying Internet Information Services During Deployment with Custom Actions</a></p>
<p>The example in the article is in VB.Net, and does not show explicitly how to change the Application Pool, but it should be easy to figure it out.</p>
| 20,195
|
<p>I have the following code block in my xslt;</p>
<pre><code> <xsl:when test="StatusData/Status/Temperature > 27">
<td bgcolor="#ffaaaa">
<xsl:value-of select="StatusData/Status/Temperature" />
</td>
</xsl:when>
</code></pre>
<p>But as you might guess when the value is 34,5 instead of 34.5 it is recognised as a string which makes integer comparison not possible. I thought replacing , with . would be solution that needs a char replace. My question is how I can do this
or
It would be great to know more about string operations in XSLT...</p>
|
<p>There is a <code>translate()</code> function in XPath:</p>
<pre><code>test="translate(StatusData/Status/Temperature, ",", ".") > 27"
</code></pre>
<p>Additionally you should make use of the number function, which converts it's argument to a number (or NaN, if that fails):</p>
<pre><code>test="number(translate(StatusData/Status/Temperature, ",", ".")) > 27.0"
</code></pre>
<p>See the <a href="http://www.w3.org/TR/xpath#function-translate" rel="noreferrer">documentation for <code>translate()</code></a> and the <a href="http://www.w3.org/TR/xpath#function-number" rel="noreferrer">documentation for <code>number()</code></a> at w3.org.</p>
|
<p>Thanx a lot.</p>
<p>it works but with one simple modification:</p>
<pre><code>test="number(translate(StatusData/Status/Temperature, ',', '.')) > 27.0"
</code></pre>
<p>by the way it is not about XSLT it is about XPath :) good to learn...</p>
| 33,644
|
<p>Does anybody know good illustration for basic <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a> usage? Something like images in this directory: <a href="http://www.ivy.fr/mercurial/ref/v1.0/" rel="nofollow noreferrer">http://www.ivy.fr/mercurial/ref/v1.0/</a> (they are for <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a>), single image illustrating most common actions.</p>
|
<p>That one is more detailed (From <a href="http://agata.in2p3.fr/dotclear/index.php?2005/05/13/6-subversion-svn-quickstart" rel="nofollow noreferrer">Subversion (svn) quickstart</a>):</p>
<p><img src="https://i.stack.imgur.com/aE3jL.png" alt="alt text"></p>
|
<p>Another <a href="http://aji.techshu.com/svn/" rel="nofollow noreferrer">good introduction</a>:</p>
<p><a href="https://i.stack.imgur.com/egDkP.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/egDkP.gif" alt="alt text"></a><br>
<sub>(source: <a href="http://img.idealwebtools.com/blog/svn.gif" rel="nofollow noreferrer">idealwebtools.com</a>)</sub> </p>
| 42,838
|
<p>I using the Win32 API and C/C++. I have a HFONT and want to use it to create a new HFONT. The new font should use the exact same font metrics except that it should be bold. Something like:</p>
<pre><code>HFONT CreateBoldFont(HFONT hFont) {
LOGFONT lf;
GetLogicalFont(hFont, &lf);
lf.lfWeight = FW_BOLD;
return CreateFontIndirect(&lf);
}
</code></pre>
<p>The "GetLogicalFont" is the missing API (as far as I can tell anyway). Is there some other way to do it? Preferrably something that works on Windows Mobile 5+.</p>
|
<p>You want to use the <a href="http://msdn.microsoft.com/en-us/library/dd144904%28v=vs.85%29.aspx" rel="noreferrer">GetObject function</a>.</p>
<pre><code>GetObject ( hFont, sizeof(LOGFONT), &lf );
</code></pre>
|
<p>Something like this - note that error checking is left as an exercise for the reader. :-)</p>
<pre><code>static HFONT CreateBoldWindowFont(HWND window)
{
const HFONT font = (HFONT)::SendMessage(window, WM_GETFONT, 0, 0);
LOGFONT fontAttributes = { 0 };
::GetObject(font, sizeof(fontAttributes), &fontAttributes);
fontAttributes.lfWeight = FW_BOLD;
return ::CreateFontIndirect(&fontAttributes);
}
static void PlayWithBoldFont()
{
const HFONT boldFont = CreateBoldWindowFont(someWindow);
.
. // Play with it!
.
::DeleteObject(boldFont);
}
</code></pre>
| 48,483
|
<p>It's known that you should declare events that take as parameters <code>(object sender, EventArgs args)</code>. Why?</p>
|
<p>This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event.</p>
<p><strong>Edit:</strong> Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern.</p>
|
<p>The <strong>EventArgs</strong> class alone is useless since it must be derived to instantiate with any content. This would indicate a subclass should be used, and many already exist in .NET. Sadly, I can't find any good generic ones. </p>
<p>Let's say you want to delegate logging to a generic event... WITHOUT WRITING YOUR OWN EventArgs SUBCLASS. It may seem a pointless exercise, but I like using existing features. You can pass your string through the Object argument, but that goes against it's intended use. Try to find a good reference of EventArgs subclasses on Google, and you'll come up dry. (At least I did.) </p>
<p>ReSharper helps a bit, since when you type "EventArgs" you'll see a list of all classes (within your using/imports scope) that CONTAIN the string "EventArgs". Perusing the list you'll see many classes with no string members. When you get to <strong>ControlEventArgs</strong>, you see that the Text property might be used, but with all of the overhead of a windows control. <strong>ConvertEventArgs</strong> might be useful, since you pass the type along with the data, but this still requires tight coupling that's neither well-documented nor inherently type-safe. <strong>DataReceivedEventArgs</strong> has no implementation. <strong>EntryWrittenEventArgs</strong> requires an EventLogEntry with a byte array or StreamingContext for data. <strong>ErrorEventArgs</strong> is closer, with an Exception message, if you don't mind calling all of your log events Exception ErrorEvents internally. <strong>FileSystemEventArgs</strong> is probably the closest yet, with two strings and a required WatcherChangeTypes enum argument that CAN be set to 0, if you know what you're doing. <strong>LabelEditEventArgs</strong> uses an int and a string, if you don't mind requiring the Windows.Forms namespace. <strong>RenamedEventArgs</strong> is similar to FileSystemEventArgs with an extra string. Finally, <strong>ResolveEventArgs</strong> in System.Runtime.InteropServices passes a single string. There are other libraries, but I stuck to some of the most common ones. So, depending on the implementation I can use <strong>ErrorEventArgs</strong>, <strong>FileSystemEventArgs</strong> or <strong>ResolveEventArgs</strong> for logging.</p>
| 13,030
|
<p>I have printed a couple weeks perfectly fine with my Ender 3. Two weeks ago I changed the firmware but the settings were all fine and resulted in good prints.</p>
<p>Now, suddenly <em>during</em> a print the extruder motor started to under-extrude.</p>
<p>I thought "hey, could be the file" and used a test file that printed well two weeks ago: Under-extrusion, barely a line.</p>
<p>I looked at the extruder, no filament grinding, no clicking from lost steps or moving against pressure. The Bowden tube is firmly seated though.</p>
<p>I measured what is coming out: instead of 50 mm I ordered to push into the hotend got 28.7 mm. So I went and looked at the steps/mm, which is 93, exactly what it is also on the TronXY X1, which uses pretty much the same extruder setup but for a different style, same sized gear.</p>
<p>I cleaned out the nozzle nevertheless, but that didn't change the results.</p>
<p>What might be wrong and how can I fix it?!</p>
<p>Edit:</p>
<ul>
<li>Touching the filament while I was printing a freshly sliced test, I realized it DID lose steps, just the filament did slip back (almost) quietly. Pressing a finger on the filament made me able to feel the shiver in it.</li>
<li>Inspecting what was printed showed, that the nozzle had migrated against the print platform a little over the weeks.</li>
</ul>
|
<p>A close inspection of what happened when printing the first layer resulted in this:</p>
<ul>
<li>The missing steps on the new print came from the nozzle scraping too close to the print surface, which lead to no first layer</li>
<li>Readjusting the Z-axis end stop, which had moved down, resulted in no more lost steps, but the print not sticking for the first test.</li>
<li><p>Releveling the bed and making sure the bar was parallel to the bed resulted in a perfect first layer.</p></li>
<li><p>Lost steps and under-extrusion could not be replicated after 48 hours of <em>rest</em> for the printer.</p></li>
</ul>
<p>I have no idea why the print had failed due to under-extrusion <em>during</em> the print, but apparently, my immediate tests were flawed enough to not detect the first layer height resulting in getting almost no extrusion. This I mistook for massive under-extrusion, making me believe something else was at fault.</p>
|
<p>Sounds similar to something I experienced with my Y-axis. The grub screw on the toothed wheel had come a little loose, and I was experiencing a reasonably consistent degree of slip.</p>
<p>In the extruder particularly, these locking screws might not be too obvious to check.</p>
| 1,026
|
<p>I'm not sure if this has been asked or not yet, but how much logic should you put in your UI classes?</p>
<p>When I started programming I used to put all my code behind events on the form which as everyone would know makes it an absolute pain in the butt to test and maintain. Overtime I have come to release how bad this practice is and have started breaking everything into classes.</p>
<p>Sometimes when refactoring I still have that feeling of "where should I put this stuff", but because most of the time the code I'm working on is in the UI layer, has no unit tests and will break in unimaginable places, I usually end up leaving it in the UI layer.</p>
<p>Are there any good rules about how much logic you put in your UI classes? What patterns should I be looking for so that I don't do this kind of thing in the future?</p>
|
<p>Just logic dealing with the UI. </p>
<p>Sometimes people try to put even that into the Business layer. For example, one might have in their BL:</p>
<pre><code>if (totalAmount < 0)
color = "RED";
else
color = "BLACK";
</code></pre>
<p>And in the UI display totalAmount using color -- which is completely wrong. It should be:</p>
<pre><code>if (totalAmount < 0)
isNegative = true;
else
isNegative = false;
</code></pre>
<p>And it should be completely up to the UI layer how totalAmount should be displayed when isNegative is true.</p>
|
<p>Input validations attached to control.
Like emails,age,date validators with text boxes</p>
| 42,770
|
<p>In Visual Studio 2005, I have a solution with explicit dependencies specified via the Project Dependencies dialog.</p>
<p>When I build via devenv /rebuild Release for example, the projects are built in a different order than when loading up the IDE. This is an order not allowed by my specified dependencies.</p>
<p>In some cases, devenv crashes :(</p>
<p>The log shows a number before each line showing an order, which I believe is the dependency-induced order:</p>
<p>11>MyExeProject - 1 error(s), 0 warning(s)</p>
<p>However, the builds appear to be <strong>started</strong> in that order, <strong>interrupted</strong> and continue in another order - which does not work. So 8 may finish its build before 11. If 11 links in 8, there is a problem.</p>
<p>A similar reordering happens in the IDE, but the build order still maintains integrity.</p>
<p>Need to build by command line, any ideas why this is or what the cause is?</p>
|
<p>Ok, here is the real answer, I believe.</p>
<p>Multiprocessor Builds are enabled. The dependency order is still enforced in the IDE, but not via command line, at least in VS 2005.</p>
<p>Turning it off is through Tools/Options/Build and Run. Set maximum to 1.</p>
|
<p>If devenv didn't crash for you when building in the IDE, you've been lucky.</p>
<p>The following workaround is obnoxious but it worked for me, sigh. Reboot and set the BIOS to allow only a single CPU core to run.</p>
| 46,569
|
<p>We are working on a website for a client that (for once) is expected to get a fair amount of traffic on day one. There are press releases, people are blogging about it, etc. I am a little concerned that we're going to fall flat on our face on day one. What are the main things you would look at to ensure (in advance without real traffic data) that you can stay standing after a big launch?</p>
<p>Details: This is a <a href="https://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="nofollow noreferrer">L/A/M/PHP</a> stack, using an internally developed MVC framework. This is currently being launched on one server, with Apache and MySQL both on it, but we can break that up if need be.</p>
<p>We are already installing <a href="https://en.wikipedia.org/wiki/Memcached" rel="nofollow noreferrer">Memcached</a> and doing as much PHP-level caching as we can think of. Some of the pages are rather query intensive, and we are using <a href="https://en.wikipedia.org/wiki/Smarty_(template_engine)" rel="nofollow noreferrer">Smarty</a> as our template engine. Keep in mind there is no time to change any of these major aspects--this is the just the setup. What sorts of things should we watch out for?</p>
|
<p>Measure first, and then optimize. Have you done any load testing? Where are the bottlenecks?</p>
<p>Once you know your bottlenecks then you can intelligently decide if you need additional database boxes or web boxes. Right now you'd just be guessing.</p>
<p>Also, how does your load testing results compare against your expected traffic? Can you handle two times the expected traffic? Five times? How easy/fast can you acquire and release extra hardware? I'm sure the business requirement is to not fail during launch, so make sure you have <em>lots</em> of capacity available. You can always release it afterwards when the load has stabilized and you know what you need.</p>
|
<p>Look into using <a href="http://varnish.projects.linpro.no/" rel="nofollow noreferrer">Varnish</a> - it's a caching reverse proxy server (like <a href="https://en.wikipedia.org/wiki/Squid_%28software%29" rel="nofollow noreferrer">Squid</a>, but much more single purpose).</p>
<p>I've run some pretty big sites behind it, and it seemed to work really well.</p>
| 14,358
|
<p>I've recently purchased a Makerbot Replicator Dual clone made by CTC. I'm in the process of upgrading/adding a few parts to it, but noticed that I can't control or print via USB.</p>
<p>The machine prints perfectly from an SD card and I can see information in the terminal from the printer via USB in RepG and through OctoPrint - Such as M105 - but can't send any .x3g files to print or upgrade firmware (I wanted to flash Sailfish 7.7 eventually).</p>
<p>To clarify;</p>
<p><strong>In Octoprint</strong></p>
<ul>
<li>Temperature auto-reporting is working</li>
<li>Can send M105, M27, etc.. & get response</li>
<li>Can select .x3g files from the SD card to print & the printer starts</li>
<li>Can upload files (.stl, .x3G, .gco etc..) to Octopi, but even the .x3g files wont actually start on the printer.</li>
<li>Tried sending <code>M140 T0 S200</code> & <code>M106 T0 S100</code> which received OK response, but there was no change reported, or indeed actually happening with the tool</li>
</ul>
<p><em>Terminal Output from OctoPrint at connection:</em></p>
<pre><code>Changing monitoring state from "Offline" to "Opening serial port"
Connected to: <octoprint_GPX.gpxprinter.GpxPrinter instance at 0x6c9a02d8>, starting monitor
Starting baud rate detection...
Changing monitoring state from "Opening serial port" to "Detecting baudrate"
Trying baudrate: 115200
Recv: start
Send: N0 M110 N0*125
Changing monitoring state from "Detecting baudrate" to "Operational"
Recv: Makerbot v7.4
Send: N0 M110 N0*125
Recv: echo: gcode to x3g translation by GPX
Recv: SD card ok
Recv: T:27 /0 B:21 /0 T0:27 /0 T1:26 /0 @:0 B@:0
Recv: T:27 /0 B:20 /0 T0:27 /0 T1:26 /0 @:0 B@:0
Recv: T:27 /0 B:21 /0 T0:27 /0 T1:26 /0 @:0 B@:0
Recv: ok
Send: N1 M115*39
Recv: ok PROTOCOL_VERSION:0.1 FIRMWARE_NAME:Makerbot FIRMWARE_VERSION:7.4 FIRMWARE_URL:https://support.makerbot.com/learn/earlier-products/replicator-original/updating-firmware-for-the-makerbot-replicator-via-replicatorg_13302 MACHINE_TYPE:r1d EXTRUDER_COUNT:2
Send: M21
Recv: ok
Recv: SD card ok
Send: M20
Recv: ok
Recv: Begin file list
Recv: 2GB
Recv: System Volume Information
Recv: mesh_bed.stl
Recv: xyzCalibration_cube.x3g
Recv: CTCB_3DBenchy.x3g
Recv: 3DBenchy.x3g
Recv: ActiveCoolingDuct.x3g
Recv: CTCB_ActiveDuctD4_UN.x3g
Recv: UK_TROLLEY_TOKEN.x3g
Recv: mesh_bed.x3g
Recv: z-axis-support.x3g
Recv: bed-screws.x3g
Recv: spool_nut.x3g
Recv: 2016_spool.x3g
Recv: 2016_spool_no_raft.x3g
Recv: ActiveDuctD4_UN.x3g
Recv: Z_Axis_Support_Ends.x3g
Recv: End file list
Send: M105
Recv: ok T:27 /0 B:20 /0 T0:27 /0 T1:26 /0 @:0 B@:0
Send: M105
</code></pre>
<p><strong>In ReplicatorG</strong></p>
<ul>
<li>The software connects to the board via USB and recognises that it is a Mightyboard running f/w 7.4</li>
<li>Reports that it is an unvarified board</li>
<li>Cannot use the GUI control tab to send commands to the printer</li>
<li>Cannot send sliced .x3g files over USB, console shows a time out error instantly</li>
<li>Saving .x3g to SD card does work</li>
</ul>
<p>Is my Mightyboard just a dud, or is there something I can do to try and fix it?</p>
<p>The reason I want to try and solve this now, is that I'm planning on adding active cooling and LED lighting control so don't really want to do all that just to find out that I need to replace the board soon.</p>
<hr />
<h3>Additional info</h3>
<p>Some information meaning that the current firmware and board is reported, as well as current temperatures of the extruders and heat bed. I can print .x3g files from the SD card, but I can't send G-code commands or .x3g files through USB.</p>
<p>I have just tried a few G-code commands through OctoPrint terminal with mixed results. <code>M105</code> works, <code>M140</code> & <code>M106</code> don't.</p>
|
<p>Good morning, and welcome to 3D Printing SE.</p>
<p>You said: "I can see information from the printer via USB in RepG and through OctoPrint, but can't send any prints, commands or upgrade firmware (I wanted to flash Sailfish 7.7 eventually)." This means that the USB communication is working fine. It isn't a question of drivers or the FTDI interface chip. That must be working fine or you wouldn't have any USB communication.</p>
<p>I would look toward a problem with slight dialect differences in the firmware that is flashed compared with the expectations of the host software.</p>
<p>I am not an expert regarding the differences in firmware G-code dialects, but there are at least: Marlin, Repetier, Mach3, LinuxCNC, Machinekit, Smoothie, Makerware, Sailfish. I got this list from the <a href="https://slic3r.org/about/" rel="nofollow noreferrer">"about"</a> page for Slic3r.</p>
<p>I would start by trying to slice files with different dialects and seeing if one of the resulting G-code files prints. You may also find a description of the firmware you have flashed with references one of these names, which would save a lot of time.</p>
<p>For flashing, you could try dropping back to the Arduino level and use those flashing tools.</p>
<hr>
<p>More answer in response to the information you have added to the question.</p>
<p>X3G files are not G-code files. If you are using a control program that expects G-code, it will not be able to handle X3G code. Similarly, if the printer expects X3G, it may not understand G-code.</p>
<p>Octoprint has an adapter layer that seems to interconvert between g-code and GPX. You are running this layer. At about line 11 of the log file you added to the question:</p>
<blockquote>
<p>Recv: echo: gcode to x3g translation by GPX</p>
</blockquote>
<p>The GPX add-in may be perfect, and it may cover all version of firmware and all functions. I don't use it and am unfamiliar with it.</p>
<p>To flash your board, I would be reluctant to assume that Octoprint/GPX new how to run that protocol. I would use the host software supplied by the vendor. Flashing is an infrequent operation, and add-on software is less likely to have it 100% correct. If I were writing GPX, I would intentionally make flashing be out-of-scope, since the consequences of doing it wrong could easily be to brick the printer.</p>
<p>Since Octoprint/GPX claims to be able to print to the printer, I would being all software up the respective current versions. Flash current Sailfish firmware using the supplied host tools. Update to the current/best version of Octoprint/GPX. Read the release notes of Octoprint/GPX for known issues.</p>
<p>It seems that X3D files are fairly limited in their use, which will constrain your options to be within the scope of the community that uses X3D files. I tried to add the X3D tag to your question, but so far no one has created the X3D tag.</p>
<p>Makerbot is part of Stratasys, and should be well supported. It may be well supported mostly within its ecosystem. You have a clone of a Makerbot machine, so, even though most or all of the printer parts are open source, you may not be able to use the genuine Makerbot host control software.</p>
<p>Your question asked if your controller board was working. It almost certainly is. I think you have a software/firmware compatibility problem.</p>
|
<p>It is possible that your board has a cloned FT232R USB-to-serial bridge chip, and FTDI drivers supplied via the Windows update channel will not work with cloned chips. Try using the Windows setup executable from the following page:</p>
<p><a href="https://www.ftdichip.com/Drivers/VCP.htm" rel="nofollow noreferrer">FTDI Chip: Virtual COM Port Drivers</a></p>
<p>Note that there are no known problems with MacOS and Linux drivers.</p>
| 1,377
|
<p>Can anyone tell how Adobe Acrobat 9 was made? I like the look and feel of the GUI and I'm curious how it was made. Specifically, what programming language was used to make it?</p>
|
<p>All of Adobe's major products are written in C++. Although they're mostly written using proprietary toolkits, Adobe has actually open-sourced some of their common low-level libraries. You can read more about them, and download them yourself, at <a href="http://stlab.adobe.com/" rel="noreferrer">Adobe's Software and Technology Lab (STLab)</a>. One of their libraries, <a href="http://stlab.adobe.com/group__asl__overview.html#asl_overview_adam_and_eve_architecture" rel="noreferrer">Adam and Eve</a>, I find especially interesting and generally useful.</p>
|
<p>I believe it was programmed in C++ using the Evil framework.</p>
| 17,769
|
<p>How can I find the origins of conflicting DNS records?</p>
|
<p>You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available <strong>nslookup</strong> command line tool:</p>
<pre><code>command line> nslookup
> set querytype=soa
> stackoverflow.com
Server: 217.30.180.230
Address: 217.30.180.230#53
Non-authoritative answer:
stackoverflow.com
origin = ns51.domaincontrol.com # ("primary name server" on Windows)
mail addr = dns.jomax.net # ("responsible mail addr" on Windows)
serial = 2008041300
refresh = 28800
retry = 7200
expire = 604800
minimum = 86400
Authoritative answers can be found from:
stackoverflow.com nameserver = ns52.domaincontrol.com.
stackoverflow.com nameserver = ns51.domaincontrol.com.
</code></pre>
<p>The <strong>origin</strong> (or <strong>primary name server</strong> on Windows) line tells you that <strong>ns51.domaincontrol</strong> is the main name server for <strong>stackoverflow.com</strong>.</p>
<p>At the end of output all authoritative servers, including backup servers for the given domain, are listed.</p>
|
<p>Unfortunately, most of these tools only return the NS record as provided by the actual name server itself. To be more accurate in determining which name servers are actually responsible for a domain, you'd have to either use "whois" and check the domains listed there OR use "dig [domain] NS @[root name server]" and run that recursively until you get the name server listings...</p>
<p>I wish there were a simple command line that you could run to get THAT result dependably and in a consistent format, not just the result that is given from the name server itself. The purpose of this for me is to be able to query about 330 domain names that I manage so I can determine exactly which name server each domain is pointing to (as per their registrar settings).</p>
<p>Anyone know of a command using "dig" or "host" or something else on *nix?</p>
| 5,892
|
<p>I'm aware of some of the test data generators out there, but most seem to just fill name and address style databases [feel free to correct me].</p>
<p>We have a large integrated and normalised application - e.g. invoices have part numbers linked to stocking tables, customer numbers linked to customer tables, change logs linked to audit information, etc which are obviously difficult to fill randomly. Currently we obfuscate real life data to get test data (but not very well).</p>
<p>What tools\methods do you use to create large volumes of data to test with?</p>
|
<p>Where I work we use <a href="http://www.red-gate.com/products/SQL_Data_Generator/index.htm" rel="nofollow noreferrer">RedGate Data Generator</a> to generate test data.</p>
<p>Since we work in the banking domain. When we have to work with nominative data (Credit card numbers, personnal ID, phone numbers) we developed an application that can <em>mask</em> these database fields so we can work with them as real data.</p>
<p>I can say with Redgate you can get close to what your real data can look like on a production server since you can customize every field of every table in your BD.</p>
|
<p>Joel also mentioned RedGate in <a href="https://blog.stackoverflow.com/2008/06/podcast-11/">podcast #11</a></p>
| 3,701
|
<p>I am running C# framework 2.0 and I would like to get some of the data from a list? The list is a List<>. How can I do that without looping and doing comparaison manually on each element of the List<>?</p>
|
<p>You can try Predicate. Here is a code I wrote to illustrate the point. Of course, as you can see in this example, you can move the Predicate outside the calling class and have a control on it. This is useful if you need to have more option with it. Inside the predicate you can do many comparison with all property/function of your object.</p>
<pre><code> static void Main()
{
List<SimpleObject> list = new List<SimpleObject>();
list.Add(new SimpleObject(1,"Jon"));
list.Add(new SimpleObject( 2, "Mr Skeet" ));
list.Add(new SimpleObject( 3,"Miss Skeet" ));
Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
{
return simpleObject.Name.Contains("Skeet");
};
list = list.FindAll(yourFilterCriteria);//Get only name that has Skeet : Here is the magic
foreach (SimpleObject o in list)
{
Console.WriteLine(o);
}
Console.Read();
}
public class SimpleObject
{
public int Id;
public string Name;
public SimpleObject(int id, string name)
{
this.Id=id;
this.Name=name;
}
public override string ToString()
{
return string.Format("{0} : {1}",Id, Name);
}
}
</code></pre>
|
<p>Unfortunately the List data structure requires iteration to find data (note that the FindAll methods above will iterate your collection under the covers - just in case you were trying to avoid that at all costs), unless you know the index of that data then you can do this:</p>
<pre><code>List<String> list = new List<String>();
list.Add("andrew");
list.Add("nicole");
String value = list[1]; // returns "nicole"
</code></pre>
| 48,738
|
<p>With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).</p>
<p>One of the main issues with testing forms is that only a few controls have a <code>hwnd</code> handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.</p>
<p>Any experience to share?</p>
|
<h1>1. Write Testable Code</h1>
<p>First, stop writing business logic into your Form's code behind. That's not the place for it. It can't be properly tested there. In fact, you really shouldn't have to test your form itself at all. It should be a dead dumb simple view that responds to User Interaction and then delegates responsibility for responding to those actions to another class that <strong><em>is</em></strong> testable.</p>
<p>How do you do that? Familiarizing yourself with the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller pattern</a> is a good start. </p>
<p><img src="https://i.stack.imgur.com/iY37U.png" alt="Model View Controller diagram"></p>
<p>It can't be done <em>perfectly</em> in VBA due to the fact that we get either events or interfaces, never both, but you can get pretty close. Consider this simple form that has a text box and a button.</p>
<p><img src="https://i.stack.imgur.com/ts6jl.png" alt="simple form with text box and button"></p>
<p>In the form's code behind, we'll wrap the TextBox's value in a public property and re-raise any events we're interested in.</p>
<pre><code>Public Event OnSayHello()
Public Event AfterTextUpdate()
Public Property Let Text(value As String)
Me.TextBox1.value = value
End Property
Public Property Get Text() As String
Text = Me.TextBox1.value
End Property
Private Sub SayHello_Click()
RaiseEvent OnSayHello
End Sub
Private Sub TextBox1_AfterUpdate()
RaiseEvent AfterTextUpdate
End Sub
</code></pre>
<p>Now we need a model to work with. Here I've created a new class module named <code>MyModel</code>. Here lies the code we'll put under test. Note that it naturally shares a similar structure as our view.</p>
<pre><code>Private mText As String
Public Property Let Text(value As String)
mText = value
End Property
Public Property Get Text() As String
Text = mText
End Property
Public Function Reversed() As String
Dim result As String
Dim length As Long
length = Len(mText)
Dim i As Long
For i = 0 To length - 1
result = result + Mid(mText, (length - i), 1)
Next i
Reversed = result
End Function
Public Sub SayHello()
MsgBox Reversed()
End Sub
</code></pre>
<p>Finally, our controller wires it all together. The controller listens for form events and communicates changes to the model and triggers the model's routines.</p>
<pre><code>Private WithEvents view As Form_Form1
Private model As MyModel
Public Sub Run()
Set model = New MyModel
Set view = New Form_Form1
view.Visible = True
End Sub
Private Sub view_AfterTextUpdate()
model.Text = view.Text
End Sub
Private Sub view_OnSayHello()
model.SayHello
view.Text = model.Reversed()
End Sub
</code></pre>
<p>Now this code can be run from any other module. For the purposes of this example, I've used a standard module. I highly encourage you to build this yourself using the code I've provided and see it function.</p>
<pre><code>Private controller As FormController
Public Sub Run()
Set controller = New FormController
controller.Run
End Sub
</code></pre>
<hr>
<p>So, that's great and all <strong><em>but what does it have to do with testing?!</em></strong> Friend, it has <strong><em>everything</em></strong> to do with testing. What we've done is make our code <em>testable</em>. In the example I've provided, there is no reason what-so-ever to even try to test the GUI. The only thing we really need to test is the <code>model</code>. That's where all of the real logic is. </p>
<p>So, on to step two.</p>
<h1>2. Choose a Unit Testing Framework</h1>
<p>There aren't a lot of options here. Most frameworks require installing COM Add-ins, lots of boiler plate, weird syntax, writing tests as comments, etc. That's why I got involved in <a href="https://github.com/rubberduck-vba/Rubberduck" rel="noreferrer">building one myself</a>, so this part of my answer isn't impartial, but I'll try to give a fair summary of what's available.</p>
<ol>
<li><p><a href="http://accunit.access-codelib.net/" rel="noreferrer">AccUnit</a></p>
<ul>
<li>Works only in Access.</li>
<li>Requires you to write tests as a strange hybrid of comments and code. (no intellisense for the comment part.</li>
<li>There <strong><em>is</em></strong> a graphical interface to help you write those strange looking tests though.</li>
<li>The project has not seen any updates since 2013.</li>
</ul></li>
<li><p><a href="http://vb-lite-unit.sourceforge.net/" rel="noreferrer">VB Lite Unit</a>
I can't say I've personally used it. It's out there, but hasn't seen an update since 2005.</p></li>
<li><p><a href="http://xlvbadevtools.codeplex.com/" rel="noreferrer">xlUnit</a>
xlUnit isn't awful, but it's not good either. It's clunky and there's lots of boiler plate code. It's the best of the worst, but it doesn't work in Access. So, that's out.</p></li>
<li><p>Build your own framework</p>
<p>I've <a href="https://codereview.stackexchange.com/questions/62781/unit-testing-in-vba">been there and done that</a>. It's probably more than most people want to get into, but it is completely possible to build a Unit Testing framework in Native VBA code.</p></li>
<li><p><a href="https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing" rel="noreferrer">Rubberduck VBE Add-In's Unit Testing Framework</a><br>
<em>Disclaimer: I'm one of the co-devs</em>.</p>
<p>I'm biased, but this is by far my favorite of the bunch.</p>
<ul>
<li>Little to no boiler plate code.</li>
<li>Intellisense is available.</li>
<li>The project is active.</li>
<li>More documentation than most of these projects.</li>
<li>It works in most of the major office applications, not just Access.</li>
<li>It is, unfortunately, a COM Add-In, so it has to be installed onto your machine.</li>
</ul></li>
</ol>
<h1>3. Start writing tests</h1>
<p>So, back to our code from section 1. The only code that we <em>really</em> needed to test was the <code>MyModel.Reversed()</code> function. So, let's take a look at what that test could look like. (Example given uses Rubberduck, but it's a simple test and could translate into the framework of your choice.)</p>
<pre><code>'@TestModule
Private Assert As New Rubberduck.AssertClass
'@TestMethod
Public Sub ReversedReversesCorrectly()
Arrange:
Dim model As New MyModel
Const original As String = "Hello"
Const expected As String = "olleH"
Dim actual As String
model.Text = original
Act:
actual = model.Reversed
Assert:
Assert.AreEqual expected, actual
End Sub
</code></pre>
<h2>Guidelines for Writing Good Tests</h2>
<ol>
<li>Only test one thing at a time.</li>
<li>Good tests only fail when there is a bug introduced into the system or the requirements have changed.</li>
<li>Don't include external dependencies such as databases and file systems. These external dependencies can make tests fail for reasons outside of your control. Secondly, they slow your tests down. If your tests are slow, you won't run them.</li>
<li>Use test names that describe what the test is testing. Don't worry if it gets long. It's most important that it is descriptive.</li>
</ol>
<hr>
<p>I know that answer was a little long, and late, but hopefully it helps some people get started in writing unit tests for their VBA code.</p>
|
<p>Data Access Pages have been deprecated by MS for quite some time, and never really worked in the first place (they were dependent on the Office Widgets being installed, and worked only in IE, and only badly then).</p>
<p>It is true that Access controls that can get focus only have a window handle when they have the focus (and those that can't get focus, such as labels, never have a window handle at all). This makes Access singularly inappropriate to window handle-driven testing regimes.</p>
<p>Indeed, I question why you want to do this kind of testing in Access. It sounds to me like your basic Extreme Programming dogma, and not all of the principles and practices of XP can be adapted to work with Access applications -- square peg, round hole.</p>
<p>So, step back and ask yourself what you're trying to accomplish and consider that you may need to utilize completely different methods than those that are based on the approaches that just can't work in Access.</p>
<p>Or whether that kind of automated testing is valid at all or even useful with an Access application.</p>
| 6,962
|
<p>I am not that hot at regular expressions and it has made my little mind melt some what.</p>
<p>I am trying to find all the tables names in a query. So say I have the query:</p>
<pre><code>SELECT one, two, three FROM table1, table2 WHERE X=Y
</code></pre>
<p>I would like to pull out "table1, table2" or "table1" and "table2"</p>
<p>But what if there is no where statement. It could be the end of the file, or there could be a group by or an order by etc. I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.</p>
<p>Is this a doable Regex expression? Am I being a Regex pleb?</p>
<p>(P.S. this will be done in C# but presume that doesn't matter much).</p>
|
<p>RegEx isn't very good at this, as it's a lot more complicated than it appears:</p>
<ul>
<li>What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway.</li>
<li>What about nested queries?</li>
<li>What if there is no table (selecting a constant)</li>
<li>What about line breaks and other whitespace formatting?</li>
<li>Alias names?</li>
</ul>
<p>I could go on.</p>
<p>What you can do is look for an sql parser, and run your query through that.</p>
|
<p>This will pull out a table name on an insert Into query:</p>
<pre><code>(?<=(INTO)\s)[^\s]*(?=\(())
</code></pre>
<p>The Following will do the same but with a select including joins</p>
<pre><code>(?<=(from|join)\s)[^\s]*(?=\s(on|join|where))
</code></pre>
<p>Finally going back to an insert if you want to return just the values that are held in an insert query use the following Regex</p>
<pre><code>(?i)(?<=VALUES[ ]*\().*(?=\))
</code></pre>
<p>I know this is an old thread but it may assist someone else looking around</p>
<p>Enjoy</p>
| 35,555
|
<p>Heres my link:</p>
<p><a href="http://tinyurl.com/6j727e" rel="noreferrer">http://tinyurl.com/6j727e</a></p>
<p>If you click on the link in test.php, it opens in a modal box which is using the jquery 'facebox' script.</p>
<p>I'm trying to act upon a click event in this box, and if you view source of test.php you'll see where I'm trying to loacte the link within the modal box.</p>
<pre><code> $('#facebox .hero-link').click(alert('click!'));
</code></pre>
<p>However, it doesn't detect a click and oddly enough the click event runs when the page loads.</p>
<p>The close button DOES however have a click event built in that closes the box, and I suspect my home-grown click event is being prevented somehow, but I can't figure it out.</p>
<p>Can anyone help? Typically its the very last part of a project and its holding me up, as is always the way ;)</p>
|
<p>First, the reason you're getting the alert on document load is because the <code>#click</code> method takes a function as an argument. Instead, you passed it the return value of <code>alert</code>, which immediately shows the alert dialog and returns null.</p>
<p>The reason the event binding isn't working is because at the time of document load, <code>#facebox .hero-link</code> does not yet exist. I think you have two options that will help you fix this.</p>
<p><strong>Option 1) Bind the click event only after the facebox is revealed. Something like:</strong></p>
<pre><code>$(document).bind('reveal.facebox', function() {
$('#facebox .hero-link').click(function() { alert('click!'); });
});
</code></pre>
<p><strong>Option 2) Look into using the <a href="http://brandonaaron.net/docs/livequery/" rel="noreferrer">jQuery Live Query Plugin</a></strong></p>
<blockquote>
<p>Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.</p>
</blockquote>
<p>jQuery Live Query will automatically bind the click event when it recognizes that Facebox modified the DOM. You should then only need to write this:</p>
<pre><code>$('#facebox .hero-link').click(function() { alert('click!'); });
</code></pre>
|
<p>Alternatively use event delegation</p>
<p>This basically hooks events to containers rather than every element and queries the event.target in the container event.</p>
<p>It has multiple benefits in that you reduce the code noise (no need to rebind) it also is easier on browser memory (less events bound in the dom)</p>
<p>Quick example <a href="http://pastebin.me/4922b20867e9d" rel="nofollow noreferrer">here</a></p>
<p><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery" rel="nofollow noreferrer">jQuery plugin</a> for easy event delegation</p>
<p>P.S event delegation is pencilled to be in the next release (1.3) coming very soon.</p>
| 45,585
|
<p>...just like packages do.</p>
<p>I use Emacs (maybe, it can offer some kind of solution).</p>
<p>For example <code>(defun the-very-very-long-but-good-name () ...)</code> is not to useful later in code. But the name like <code>Fn-15</code> or the first letters abbreviation is not useful too.
Is it possible either to have an alias like for packages or to access the documentation string while trying to recall the function's name?</p>
<p>In other words, is it possible for functions to mix somehow self-documenting and short names?</p>
|
<p>You want <code>defalias</code>. <code>(defalias 'newname 'oldname)</code> will preserve documentation and even show "newname is an alias for `oldname'" when its documentation is requested.</p>
|
<p>You could simply have a function that just calls another function. </p>
| 23,333
|
<p>Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>.</p>
<p>I'm wondering how does one integrate a Gecko or WebKit one.</p>
<ol>
<li>Are there VCL examples somewhere?</li>
<li>If not, how would one go about doing it?</li>
<li>Where's the best place to find the core for Gecko and/or WebKit in an embeddable format?</li>
</ol>
|
<p>TWebBrowser <strong>is</strong> IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See</p>
<ul>
<li><a href="http://www.adamlock.com/mozilla/" rel="nofollow noreferrer">http://www.adamlock.com/mozilla/</a></li>
<li><a href="http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html" rel="nofollow noreferrer">http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html</a></li>
<li><a href="http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/" rel="nofollow noreferrer">http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/</a></li>
</ul>
<h2>Time has moved on</h2>
<p>This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now.</p>
|
<p><strong>Edit:</strong> Lars beat me to it, unfortunately</p>
<p>Well there is an ActiveX control based on the Gecko engine that tries to present an exact copy of the IWebBrowser API (which TWebBrowser uses).</p>
<p>You can find it here: <a href="http://www.iol.ie/~locka/mozilla/control.htm" rel="nofollow noreferrer">http://www.iol.ie/~locka/mozilla/control.htm</a>
Unfortunately it looks like it hasn't been updated in a while. The last version is based on Gecko 1.7.12 and I believe Gecko is currently up to 1.9.x (used in Firefox 3)</p>
| 19,674
|
<p>I've built the mechanics of my 3D printer myself, because I need to print parts that are really huge, (and for budget reasons). <strong>So, I already have the 3D movement functionality.</strong></p>
<p>But what I need now, is the printing mechanism itself. I've been reading a lot, but it became clear to me that things are more complicated than I thought. </p>
<p>Let's skip mechanics and software, I'm just interested in how the print head works. Can somebody explain me that?</p>
<p>To be honest, I was so naive that I thought that I just had to buy one part with one data wire (print/noprint) and the 5 V/GND wires. But it came to my intension that things are way more complicated. </p>
<p>For example, these RepRap printers have some kind of air tube attached to the print head. I'm not sure what that's all about, is it cooling?</p>
<p>Perhaps I'm always reading the wrong manuals (i.e. the more advanced ones). Can somebody enlighten me or point me to a good starting point?</p>
|
<p>You will certainly find that the print functionality of a 3d printer is a bit more complex than you suggest. The mechanical portions include a means to push the filament into a heated nozzle as well as the software portion to regulate the speed of the filament movement. You haven't referenced the heater cartridge and temperature sensor, but you will discover that aspect soon enough.</p>
<p>The "air tube" you think you've seen is likely called a bowden tube. Such designs permit lighter weight print heads, which is beneficial for speed, acceleration and precision, but has complications with respect to compression of the filament as well as retraction considerations. Non-bowden print heads will have the extruder motor as part of the moving assembly, with the drive wheels very close to the nozzle opening. This allows for flexible filament and more precise control of the filament feed. </p>
<p>Either design has compromises, so one must determine priorities for the design.</p>
<p>Cooling is also a factor. The heater cartridge is designed to heat the nozzle to a specific temperature for the type of filament used, but also requires a means to keep the heat from traveling to the portion of filament not in the nozzle. You'll discover terms such as heat break, referring to narrow threaded portion connecting the nozzle assembly to the heat sink. There will also be a cooling fan to blow air over the heat sink and very often a cooling fan to cool the filament as it exits the nozzle and attaches to the model being printed.</p>
<p>You suggest to ignore the mechanics and software, but it's important to be aware of both when considering the principles of the print head assembly.</p>
<p>Simplified, filament enters bowden tube then into heat sink, pushed by extruder motor (or) filament is pushed into heat sink by extruder motor. Filament travels through heat break, gets melted in heater block and exits nozzle. Sheesh, that's way too simple.</p>
|
<p>The first point to start would be the RepRap wiki entry for <a href="http://reprap.org/wiki/Category:Extruders" rel="nofollow noreferrer">extruders</a>:</p>
<blockquote>
<h3>cold end</h3>
<p>The "Cold End" is usually the bulk of the extruder. It is
often the actual carriage on one axis and supports the rest of the
parts. In some designs, the "Cold End" is split into two parts; one
part does the driving of the filament that is stationary and connected
to the carriage portion, of a lighter weight design for easier
movement, with a flexible tube. The drive is a motor that rotates a
knurled, hobbed, or toothed pinch wheel against a pressure plate or
bearing with the filament forced between them. Usually, the motor is
geared to the pinch wheel to increase available torque and extrusion
control (smoothness). The gearing can be a 3D printed pinion and gear,
stock worm wheel and gear, or a more expensive integral motor gearbox.
Stepper motors are used almost universally after initial trials with
DC motors did not achieve the required repeatability. Servo motors are
an option, though they are not seen in the literature yet. The final
function, some form of cooling, keeps the "Cold End" cold. With the
close proximity to the "Hot End" and possible heated build platforms
and enclosures, it is sometimes necessary to have additional passive
or active cooling of the cold end parts. Heat sinks and fans are often
used; water and Peltier effect cooling is also discussed. Much of this
bulk is usually made from 3D printed parts and the temperature is
maintained within safe limits.</p>
<h3>hot end attachment</h3>
<p>The "Cold End" is
connected to the "Hot End" across a thermal break or insulator (the
Bowden tube if used is on the cold side of this thermal break). This
has to be rigid and accurate enough to reliably pass the filament from
one side to the other, but still prevent much of the heat transfer.
The materials of choice are usually PEEK plastic with PTFE liners or
PTFE with stainless steel mechanical supports or a combination of all
three. A Hot End is frequently joined to the Cold End using a Groove
Mount where the thermal break or insulator is part of the Hot End
assembly and the Cold End body is provisioned with a cylindrical
recess. Many cold ends push the filament out a large hole centered
between 2 small holes about 50 mm apart. (Is there a name for this
de-facto standard?) Some people rigidly attach a groove mount hot end
to such a cold end with the mounting plate adapter and two short
bolts. A few people put 2 long bolts through those holes and then put
a spring around those bolts to make a spring extruder.</p>
<h3>hot end</h3>
<p>The
"Hot End" is the active part of the 3D printer that melts the
filament. It allows the molten plastic to exit from the small nozzle
to form a thin and tacky bead of plastic that will adhere to the
material it is laid on. The first RepRap hot end was made of brass.
Researchers have also made hot ends from glass or aluminium. The hot
end consists of a melting zone or chamber with two holes. The cold end
forces the filament into the hot end -- into the heating chamber of
the hot end -- through one hole. The molten plastic exits the heating
chamber through the other hole at the tip. The hole in the tip
(nozzle) has a diameter of between 0.3mm and 1.0mm with typical size
of 0.5mm with present generation extruders. Outside the tip of the
barrel is a heating means, either a wire element or a standard wire
wound resistor. The heat required is of the order of 20W with typical
temperatures around 150 to 250 degrees Centigrade. For feedback
control of the nozzle temperature, a thermistor is usually attached
close to the nozzle, though a thermocouple may serve with suitable
control hardware. High temperature materials are needed here. These
include metals, cements and glues, glass and mineral fibre materials,
PEEK, PTFE and Kapton tape.</p>
<h3>mount to rest of machine</h3>
<p>The ways
extruders are mounted on the rest of the machine have evolved over
time into informal mounting standards. These informal standards
include the Vertical X Axis Standard, the Quick-fit extruder mount,
the OpenX mount, etc. Such de-facto standards allows new extruder
designs to be tested on existing printer frames, and new printer frame
designs to use existing extruders. (Does the "greg-adapter.scad"
adapter in the Prusa i3 Build Manual let me mount an OpenX extruder on
a Vertical X Axis machine?)</p>
</blockquote>
<p>You can also google for extruder and/or hotend in combination with 3d printing for a first starting point.</p>
| 384
|
<p>This problem started <a href="http://forums.asp.net/t/1304033.aspx" rel="nofollow noreferrer">on a different board</a>, but <a href="https://stackoverflow.com/users/60/dave-ward">Dave Ward</a>, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.</p>
<p>Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">a nice article about using JavaScript</a>. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.</p>
<p>I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like <code>Page.Response.BufferOutput = False</code>. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?</p>
<p>For reference, a link to the working version of a simpler version of my application is located @ <a href="http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx" rel="nofollow noreferrer">http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx</a> and the same version that isn't working is located @ <a href="http://www.tabroom.org/Ajaxfun/Default.aspx" rel="nofollow noreferrer">http://www.tabroom.org/Ajaxfun/Default.aspx</a>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad.</p>
|
<p>Hey, Jason. Sorry you're still having trouble with this.</p>
<p>What I would do is set up a simple page like:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Response.Write(i + "<br />");
Response.Flush();
Thread.Sleep(1000);
}
}
</code></pre>
<p>As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened.</p>
<p>Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved.</p>
<p>Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious.</p>
|
<p>I don't know that you can force buffering - but a reverse proxy server between you and the server would affect buffering (since the buffer then affects the proxy's connection - not your browser's).</p>
| 4,446
|
<p>I have a C# interface with certain method parameters declared as <code>object</code> types. However, the actual type passed around can differ depending on the class implementing the interface:</p>
<pre><code>public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
</code></pre>
<p>The problem with MyClass2 is that the conversion of <code>byte[]</code> to and from <code>object</code> is <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx" rel="noreferrer">boxing and unboxing</a>, which are computationally expensive operations affecting performance.</p>
<p>Would solving this problem with a <a href="http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx" rel="noreferrer">generic interface</a> avoid boxing/unboxing?</p>
<pre><code>public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
</code></pre>
<p>How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?</p>
<p>Thank you!</p>
|
<blockquote>
<p>The problem with MyClass2 is that the
conversion of byte[] to and from
object is boxing and unboxing, which
are computationally expensive
operations affecting performance.</p>
</blockquote>
<p>There is no boxing involved with array types, even one with value type elements. An array is a reference type.</p>
<p>The overhead on (byte[]) arg is minimal at best.</p>
|
<p>Given you're using a recent version of mono, 2.0 if you can.</p>
<p>Generic interface performance on Mono is very good, on pair with regular interface dispatch.</p>
<p>Dispatch of generic virtual methods[1] is terrible on all released versions of mono, it has improved in 1.9 thou.</p>
<p>The problem is not that bad as the performance issue with generic virtual methods has been fixed for the next release of mono (2.2), which is scheduled to the end of this year.</p>
<p>[1] A generic virtual method is something like:</p>
<p>public interface Foo {</p>
<pre><code> void Bla<T> (T a, T b);
</code></pre>
<p>}</p>
| 16,933
|
<p>In Apple's iPhone apps (like Contacts), they have a nice magnifying glass icon at the top of the table view index. Since the table view index API is character-based, I assume that this magnifying glass is a Unicode character. So far I've resorted to placing a question mark character there, but that looks lame.</p>
<p>Can anyone tell me what character the magnifying glass is?</p>
|
<p>Returning <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW49" rel="nofollow noreferrer"><code>UITableViewIndexSearch</code></a> as section index title (same as @"{search}") also works.</p>
<p>In Swift you would use <code>UITableView.indexSearch</code>.</p>
|
<p>Someone <a href="http://forums.macrumors.com/showthread.php?t=555877" rel="nofollow noreferrer">claims that Apple told them</a> this isn't supported in the SDK.</p>
| 29,098
|
<p>I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a <code>java.util.HashMap<java.awt.Point, Segment></code>. However, I keep getting an OutOfMemory exception. (<code>Segment</code> is my own class - very light weight - one <code>String</code> field, and 3 <code>int</code> fields).</p>
<pre>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.HashMap.resize(HashMap.java:508)
at java.util.HashMap.addEntry(HashMap.java:799)
at java.util.HashMap.put(HashMap.java:431)
at bus.tools.UpdateMap.putSegment(UpdateMap.java:168)</pre>
<p>This seems quite ridiculous since I see that there is plenty of memory available on the machine - both in free RAM and HD space for virtual memory.</p>
<p>Is it possible Java is running with some stringent memory requirements? Can I increase these?</p>
<p>Is there some weird limitation with <code>HashMap</code>? Am I going to have to implement my own? Are there any other classes worth looking at?</p>
<p>(I am running Java 5 under OS X 10.5 on an Intel machine with 2GB RAM.)</p>
|
<p>You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small.</p>
<p>You can programmatically check how much memory is available by using the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html" rel="noreferrer">Runtime</a> class.</p>
<pre><code>// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
</code></pre>
<p>(Example from <a href="http://www.exampledepot.com/egs/java.lang/GetHeapSize.html" rel="noreferrer">Java Developers Almanac</a>)</p>
<p>This is also partially addressed in <a href="http://java.sun.com/docs/hotspot/HotSpotFAQ.html" rel="noreferrer">Frequently Asked Questions About the Java HotSpot VM</a>, and in the <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html" rel="noreferrer">Java 6 GC Tuning page</a>.</p>
|
<p>Also might want to take a look at this:</p>
<p><a href="http://java.sun.com/docs/hotspot/gc/" rel="nofollow noreferrer">http://java.sun.com/docs/hotspot/gc/</a></p>
| 29,090
|
<p>I'm interested in finding good icons/images that can be used in both 'free' and proprietary programs. </p>
<p>Please include a description of any license restrictions associated with the source of the icons you suggest.</p>
|
<p>I use two search engines:</p>
<p><a href="http://www.iconfinder.net/index.php?q=file" rel="noreferrer">IconFinder</a> and <a href="http://www.iconlook.com/search.icon?q=file&s12=on&s16=on&s22=on&s32=on&s48=on&s64=on&s128=on" rel="noreferrer">IconLook</a>.</p>
<p>If you can't find what you want, this <a href="http://speckyboy.com/2008/03/04/top-40-free-icon-resources-for-web-designers-updated-speckyboy/" rel="noreferrer">blog post</a> has a list of great resources.</p>
|
<p>I've had the best luck with <a href="http://www.iconbuffet.com" rel="nofollow noreferrer">Icon Buffet</a> and <a href="http://stockicons.com" rel="nofollow noreferrer">StockIcons</a></p>
| 7,025
|
<p>In the past, I used Microsoft Web Application Stress Tool and Pylot to stress test web applications. I'd written a simple home page, login script, and site walkthrough (in an ecommerce site adding a few items to a cart and checkout).</p>
<p>Just hitting the homepage hard with a handful of developers would almost always locate a major problem. More scalability problems would surface at the second stage, and even more - after the launch.</p>
<p>The URL of the tools I used were Microsoft Homer (aka <a href="http://www.microsoft.com/downloads/details.aspx?familyid=e2c0585a-062a-439e-a67d-75a89aa36495&displaylang=en" rel="noreferrer">Microsoft Web Application Stress Tool</a>) and <a href="https://code.google.com/archive/p/pylt/" rel="noreferrer">Pylot</a>.</p>
<p>The reports generated by these tools never made much sense to me, and I would spend many hours trying to figure out what kind of concurrent load the site would be able to support. It was always worth it because the stupidest bugs and bottlenecks would always come up (for instance, web server misconfigurations).</p>
<p>What have you done, what tools have you used, and what success have you had with your approach? The part that is most interesting to me is coming up with some kind of a meaningful formula for calculating the number of concurrent users an app can support from the numbers reported by the stress test application.</p>
|
<p>Here's another vote for <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer"><strong>JMeter</strong></a>.</p>
<p>JMeter is an open-source load testing tool, written in Java. It's capable of testing a number of different server types (for example, web, web services, database, just about anything that uses requests basically).</p>
<p>It does however have a steep learning curve once you start getting to complicated tests, but it's well worth it. You can get up and running very quickly, and depending on what sort of stress-testing you want to do, that might be fine.</p>
<p>Pros: </p>
<ul>
<li>Open-Source/Free tool from the Apache project (helps with buy-in)</li>
<li>Easy to get started with, and easy to use once you grasp the core concepts. (Ie, how to create a request, how to create an assertion, how to work with variables etc).</li>
<li>Very scalable. I've run tests with 11 machines generating load on the server to the tune of almost a million hits/hour. It was <em>much</em> easier to setup than I was expecting.</li>
<li>Has an active community and good resources to help you get up and running. Read the tutorials first and play with it for a while. </li>
</ul>
<p>Cons:</p>
<ul>
<li>The UI is written in Swing. (ugh!)</li>
<li>JMeter works by parsing the response text returned by the server. So if you're looking to validate any sort of javascript behaviours, you're out of luck.</li>
<li>Learning curve is steep for non-programmers. If you're familiar with regular expressions, you're already ahead of the game.</li>
<li>There are large numbers of (<em>insert expletive</em>) idiots in the support forum asking stupid questions that could be easily solved if they'd give the documentation even a cursory glance. ('How do I use JMeter to stress-test my Windows GUI' shows up quite frequently).</li>
<li>Reporting 'out of the box' leaves much to be desired, particularly for larger tests. In the test I mentioned above, I ended up having to write a quick console app to do some of the 'xml-logfile' to 'html' conversions. That was a few years ago though, so it's probable that this would no longer be required.</li>
</ul>
|
<p>One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.</p>
| 2,903
|
<p>For a while now, my AmazonBasics PETG filament has been working like a charm. Now, it is balling up on my nozzle. I've tried slowing it down, re-leveling the bed, etc. I don't want to go through the hassle of replacing my nozzle with a Micro-Swiss all metal 0.4 mm nozzle. I've tried the other extruder which I know works with PLA, but same results. I'm using a Flashforge Creator Pro(2016).</p>
|
<p>PETG does this. PETG is like glue when soft this is why when you level the bed you have to add an additional 0.1 mm distance for PETG. PETG should not be as close as PLA, but futher away. It will stick to the hotend so preferably change the hotend from brass to a nickle plated nozzle (e.g. Micro Swiss, PETG does not stick to that nozzle at all).</p>
|
<p>PETG does this. PETG is like glue when soft this is why when you level the bed you have to add an additional 0.1 mm distance for PETG. PETG should not be as close as PLA, but futher away. It will stick to the hotend so preferably change the hotend from brass to a nickle plated nozzle (e.g. Micro Swiss, PETG does not stick to that nozzle at all).</p>
| 1,226
|
<p>So I have a self build Mendel Reprap style 3d printer.</p>
<p>I've not used it in sometime after moving house but I'm looking to use it again. What should I pay attention to before calibrating and running it again?</p>
|
<p>Increase nozzle temperature. When the filament is new it will print easier, requiring less heat to print well. So if you didn't store your filament properly to begin with, increasing print temperature will make it jam less and increase layer bonding. </p>
<p>The reason for this is because the moisture that accumulates in the filament will absorb heat and evaporate when printed, meaning that the filament itself isn't getting the same amount of heating as it used to.</p>
<p>That being said, the storage suggestions mentioned by tbm should be your first priority. I personally put my filament in Zip Lock plastic bags and store these in a dry location not exposed to sun or temperature changes.</p>
|
<p>PLA absorbs moisture, so keeping the filament dry is a key factor. Aside from that, PLA is naturally more brittle than other plastics like ABS and Nylon Sorry, tried to find a graph to prove it, but couldn't find one.</p>
<p>There's a good <a href="https://groups.google.com/forum/#!topic/makerbot/Rdx2ZnJeQzs">Google Group discussion</a> and many other resources that go over good storage habits, but as for fixing the existing filament.</p>
<p>Try the following: </p>
<ul>
<li>Place PLA in an enclosure (plastic bin, Zip-loc bag, etc.)</li>
<li>If you have some, add some moisture absorber(s)</li>
<li>Place the tub in a warm environment (naturally or artificially) and make sure the area is dry as possible (not in the shed in the back, by the woods...). Possibly next to a heater vent or space heater in your house?</li>
</ul>
<p>Essentially, you're trying to treat the material. When the material goes through a heat treatment (aka the heat block in the extruder), the mechanical properties are beginning to change. The brittleness can be set by how quickly the material cools. I'm speculating that the moisture does any of the following:</p>
<ol>
<li>Keeps the filament from heating up to the desired extrusion temperature.</li>
<li>Burns the filament.</li>
<li>The moisture is evaporated, leaving gaps in the extruded filament (under microscope).</li>
</ol>
<p>I looked into this a few years ago and have forgotten most of what I found out, but I'll keep looking and update my answer here.</p>
| 326
|
<p>I am developing an iPhone application that persists data to a SQLite3 database. </p>
<p>For each row I persist I wish to include a 'created date' and a 'last modified date'</p>
<p>My question is what is the recommend approach for storing this information in a table? </p>
<p>The properties are represented as NSDate in my application but I am unsure how to represent this information in my table.</p>
<p>It appears that SQLite3 provides a DATETIME type but does not have a native understanding of how to parse this information.</p>
<p>Any help would be much appreciated.</p>
<p>Thanks in advance.</p>
|
<p>I typically use a double, something like:</p>
<pre><code>sqlite3_bind_double(statement, index, [dateObject timeIntervalSince1970]);
</code></pre>
<p>where dateObject is an NSDate*. Then, when getting the data out of the DB, use</p>
<pre><code>[NSDate dateWithTimeIntervalSince1970:doubleValueFromDatabase];
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/1711504/how-get-datetime-column-in-sqlite-objecite-c/1711591#1711591">How get a datetime column in SQLite with Objective C</a></p>
| 31,265
|
<p>Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information.</p>
<p>It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth.</p>
<p>But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that?</p>
|
<p>You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen.</p>
<p>Use the link tag:</p>
<pre><code><link rel="stylesheet" type="text/css" href="print.css" media="print, handheld" />
<link rel="stylesheet" type="text/css" href="screen.css" media="screen" />
</code></pre>
<p>to embed your stylesheet into your document. </p>
<p>To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example:</p>
<pre class="lang-css prettyprint-override"><code>.newStyle1 {
display: none;
}
</code></pre>
<p>Then anything set to the style of <code>newStyle1</code> will not be displayed. </p>
|
<p>The easiest way is to use CSS media types. For each CSS file you include, you can specify where it ought to be used: on-screen, when printing, for handhelds, for screen-readers, or various combinations of these.</p>
<p>Example: <em><link rel="stylesheet" type="text/css" media="print, handheld" href="foo.css"></em></p>
<p>This has been a standard since CSS2, and most browsers support it now. More information is available here: <a href="http://www.w3.org/TR/CSS2/media.html" rel="nofollow noreferrer">http://www.w3.org/TR/CSS2/media.html</a></p>
| 11,055
|
<p>On a website I'm working we have an onsite login and a private login, the problem I'm having is that Firefox doesn't seem to be able to differentiate between these login forms.</p>
<p>Does anybody know how I can make clear that these are different logins?</p>
<p>I already tried giving the form fields different names and ids, ex: onsite_login and login but without success.</p>
<p><strong>edit:</strong> my form-tags are not being mixed up, they aren't even on the same page</p>
<p>The two forms on the different pages</p>
<pre><code><form method="post" action="/en/login/1">
<fieldset>
<p>
<input type="hidden" value="login" name="form"/>
<input type="hidden" value="en" name="redirect"/>
<label for="onsite_username">Username<abbr title="Required ">*</abbr></label>
<input type="text" class="input-text" maxlength="255" value="" name="onsite_username" id="onsite_username"/>
<label for="onsite_password">Password<abbr title="Required ">*</abbr></label>
<input type="password" class="input-password" maxlength="255" value="" name="onsite_password" id="onsite_password"/>
<input type="submit" value="Log in" name="submit" class="input-submit"/>
</p>
</fieldset>
</form>
</code></pre>
<p>and</p>
<pre><code><form method="post" action="">
<fieldset>
<input type="hidden" value="login" name="form"/>
<div>
<label for="username">Username</label>
<input type="text" class="input-text" value="" name="username" id="username"/>
</div><div>
<label for="password">Password</label>
<input type="password" class="input-password" value="" name="password" id="password"/>
</div>
<input type="submit" value="Aanmelden" class="input-submit"/>
</fieldset>
</form>
</code></pre>
|
<p>Apparently this is not possible due to the way Firefox stores its passwords.</p>
<p>A password-manager entry is stored with the following data</p>
<ul>
<li>The username (encrypted and secured with Firefox Master Password).</li>
<li>The password (encrypted and secured with Firefox Master Password).</li>
<li>The hostname of the webpage containing the login form.</li>
<li>The hostname of the webpage to which the form data has been submitted.</li>
</ul>
<p>Thus Firefox does not distinguish between the two loginfields on my page.</p>
|
<p>I'm not sure.. but try to give them a different ID like <code><form method="POST" action="#" id="login1"></code></p>
| 46,354
|
<p>I want to dynamically add menuitems to my master page based on membership security login role. From what I've read RenderAction in the master page html could perhaps do this. Since I'm fumbling thru this I am not sure how it would look and how in the controller I check my current role. I am considering creating a table and relating the allowable menu items to role relationship so I can pass to the master page for rendering the dynamic menu items.</p>
|
<p>In the controller, I would create a MenuModel class or the like, that is the model for your menu. It would be a data only class. Create and populate it in the controller, taking into consideration the current user's access permissions. This will allow you to write unit tests that ensure your security code is correct.</p>
<p>Then I'd pass that to the view via ViewData. I'd combine that with a helper method that knows how to render the menu based on the MenuModel class.</p>
|
<p>I'm not sure if this is what you are looking for, but I had a question along the same lines a few weeks ago:</p>
<p><a href="https://stackoverflow.com/questions/121000/stuck-creating-a-security-trimmed-htmlactionlink-extension-method">Stuck creating a "security trimmed" html.ActionLink extension method</a></p>
<p>This allowed me to extend a menu in the master page (or any other page) controlling the access to the menu items through the Authorize attribute:</p>
<p>Here is <a href="http://inq.me/post/ASPNet-MVC-Extension-method-to-create-a-Security-Aware-HtmlActionLink.aspx" rel="nofollow noreferrer">my code to do this</a>.</p>
| 28,159
|
<p>I am making a post from a .NET console app to a .NET web service. I know that the timeout on the server side is 20 min, but if my client takes more than 100 seconds to post my data to that service then I get a timeout exception. How would I tell my client to wait the available 20 min to timeout?</p>
|
<p>on the client side, your webservice object has a timeout value. It should be pretty easy to set by going:</p>
<pre><code>myServiceInstance.Timeout = 1200000
</code></pre>
<p>for 20 minutes</p>
|
<p>Yup the <code>ServiceInstance.Timeout</code> is the property to set.</p>
<p>I blogged about it here
<a href="http://stackpanel.com/blog/2008/10/client-timeout-accessing-asmx-web-service/" rel="nofollow noreferrer">http://stackpanel.com/blog/2008/10/client-timeout-accessing-asmx-web-service/</a></p>
| 36,251
|
<p>I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? </p>
<p>Best I could come up with (I am certain it gets better than this):</p>
<pre><code>public void MyCallback(object sender, EventArgs e) { _flag = true;}
[Test]
public void DoSomethingRaisesEvent() {
_flag = false;
using(_mocks.Record()) {
Expect.Call(delegeate { _obj.DoSomething();});
}
using(_mocks.Playback()) {
_obj = new SomethingDoer();
_obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
Assert.IsTrue(_flag);
}
}
</code></pre>
|
<p>I found <a href="http://haacked.com/archive/2006/12/13/tip_jar_unit_test_events_with_anonymous_delegates.aspx" rel="noreferrer">this article by Phil Haack on how to test events using anonymous delegates</a></p>
<p>Here is the code, ripped directly from his blog for those too lazy to click through:</p>
<pre><code>[Test]
public void SettingValueRaisesEvent()
{
bool eventRaised = false;
Parameter param = new Parameter("num", "int", "1");
param.ValueChanged +=
delegate(object sender, ValueChangedEventArgs e)
{
Assert.AreEqual("42", e.NewValue);
Assert.AreEqual("1", e.OldValue);
Assert.AreEqual("num", e.ParameterName);
eventRaised = true;
};
param.Value = "42"; //should fire event.
Assert.IsTrue(eventRaised, "Event was not raised");
}
</code></pre>
|
<p>I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks</p>
<p>In any case, here is another way I like to deal with events:</p>
<pre><code>[Test]
public void MyEventTest()
{
IEventRaiser eventRaiser;
mockView = _mocks.CreateMock<IView>();
using (_mocks.Record())
{
mockView.DoSomethingEvent += null;
eventRaiser = LastCall.IgnoreArguments();
}
using (_mocks.Playback())
{
new Controller(mockView, mockModel);
eventRaiser.Raise(mockView, EventArgs.Empty);
}
}
</code></pre>
| 17,955
|
<p>We all know, that the best layer hight is, when you have multiples of full steps. If it is not, sometimes steps get skipped and end up bad layer-to-layer adhesion when one height step missed a tiny bit and then the next catches up, creating an extra-thick layer. For example, this was printed somewhat deliberately, and here, the extra spaced layers are perfect for delaminating the print with just a fingernail:</p>
<p><a href="https://i.stack.imgur.com/QwkYK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/QwkYK.jpg" alt="Delaminating Print"></a></p>
<p>The Ender 3 I have uses the following Z-Rod:</p>
<ul>
<li>Diameter 8 mm</li>
<li>4 flutes</li>
<li>ca 13 Threads per inch
<ul>
<li>That is <a href="https://mdmetric.com/tech/tict.htm" rel="noreferrer">according to the table</a>, a 2 mm pitch for <em>one</em> thread.</li>
<li>As a result, it's an 8 mm pitch for each of the 4 threads.</li>
</ul></li>
</ul>
<p>The firmware (Marlin) I use claims in <code>configuration.h</code> that the NEMA17 motor would be using 400 Steps per mm in Z. <code>configuration_adv.h</code> tells that the microsteps on the Z-axis motor are 16.</p>
<p>In the printer's menu, Babystepping is in increments of 0.049 mm (though some rounding error seems to be there: 5 Babysteps are 0.250 mm).</p>
|
<blockquote>
<p>that the NEMA17 motor would be using 400 Steps per mm in Z. <code>configuration_adv.h</code> tells that the microsteps on the Z-axis motor are 16.</p>
</blockquote>
<p>Easy. There are 400 microsteps in a millimeter, and 16 microsteps in a full step. So, there are 400/16=25 full steps in a millimeter. So a full step is 1/25<sup>th</sup> of a millimeter, or 0.04 mm. Your layer height should be a multiple of this.</p>
<p>As your leadscrew has a lead of 8 mm (i.e., a full rotation will move the Z-axis by 8 mm), a full step is either 8/200=0.04 mm (for a 1.8 degree stepper) or 8/400=0.02 mm (for a 0.9 degree stepper). So, apparently, you have a 1.8 degree stepper (and this is the most common type of stepper).</p>
|
<p>I see you've already accepted an answer, but based on your comments I think you have some misunderstandings of the topic which are worth clarifying as part of answering this question.</p>
<blockquote>
<p>0.2125 layer height (+1/4 microstep) and doing all the movements in absolute movements instead of relative forced the result, as the target heights were as a result at 0.2125 mm (for the stepper that's effectively a 0.2 mm), 0.425 (0.4), 0.675 (for the stepper that's, depending on rounding or truncting, 0.6 or 0.7), 0.9 (here they are both 0.9) and so on.</p>
</blockquote>
<p>It sounds like your understanding is that the stepper driver is "rounding"/"truncating" to Z positions that are multiples of 0.1 mm. Perhaps that's based on the LCD status display of the Ender 3's firmware, which is based on Marlin 1.0 or something around that version, and shows current coordinates rounded or truncated (I forget which) to one decimal place. This does not have anything to do with the positioning limitations of the actual machine; it's just bad user interface design.</p>
<p>The actual firmware position is translated from the floating point value in the gcode to the nearest step/microstep that the stepper driver can represent. With full steps being 0.04 mm, microsteps are 0.0025 mm (1/16 of a step). All of these positions are "exact" in a logical sense, but of course subject to physical limits of the mechanical parts and accuracy of microstepping. On the topic of microstepping accuracy, you should read <a href="https://hackaday.com/2016/08/29/how-accurate-is-microstepping-really/" rel="nofollow noreferrer">How Accurate Is Microstepping Really?</a> Most if not all models of the Ender 3 have A4988 stepper drivers, one of the chips reviewed in that article. But the important part is that there's no rounding/truncation to whole steps taking place. Rather, the stepper driver is <em>trying</em> to position the motor in between whole steps by balancing the magnetic fields pulling it in each direction, with the goal of producing a linear interpolation between the two adjacent full steps. How well it does this is a matter of the quality of the stepper drivers and the load on the motor.</p>
<p>Back to your test, your layer height of 0.2125 mm is not one step plus 1/4 microstep. It's 5 steps (5 * 0.04 mm) plus 0.0125 mm which is 5 microsteps. This is probably a decent test - 5 is 1 mod 16, so you'll end up with a period-16 cycle of microstep positions, at 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, and 11 microsteps mod the whole step. This is pretty close to a period of 3, so you might expect to see some irregularity from poor microstepping accuracy that looks periodic every 3 layers, or you might see it repeating only every 16 layers (every 3.4 mm). But regardless I would not expect delamination problems from this. I think there's another serious extrusion problem behind the photo in your question, and you should probably open a new question about what it might be.</p>
| 1,464
|
<p>I want to make a .NET Form as a TopMost Form for another external App (not .NET related, pure Win32) so it stays above that Win32App, but not the rest of the apps running.</p>
<p>I Have the handle of the Win32App (provided by the Win32App itself), and I've tried <a href="http://msdn.microsoft.com/en-us/library/ms633541(VS.85).aspx" rel="noreferrer">Win32 SetParent() function</a>, via <a href="http://www.pinvoke.net/default.aspx/user32/SetParent.html" rel="noreferrer">P/Invoke in C#</a>, but then my .NET Form gets confined into the Win32App and that's not what I want.</p>
|
<p>I think you're looking for is to P/Invoke <code>SetWindowLongPtr(win32window, GWLP_HWNDPARENT, formhandle)</code></p>
<p><a href="http://www.google.com/search?q=setwindowlongptr+parent" rel="noreferrer">Google Search</a></p>
|
<p>It has now been 12 years since this question was asked so I thought I would provide an updated answer from <a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra" rel="nofollow noreferrer">here</a>.</p>
<blockquote>
<p>Do not call SetWindowLongPtr with the GWLP_HWNDPARENT index to change the parent of a child window. Instead, use the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setparent" rel="nofollow noreferrer">SetParent</a> function.</p>
</blockquote>
| 16,116
|
<p>I have a .NET (C#) multi-threaded application and I want to know if a certain method runs inside the Finalizer thread. </p>
<p>I've tried using Thread.CurrentThread.Name but it doesn't work (returns null).</p>
<p>Anyone knows how can I query the current thread to discover if it's the Finalizer thread?</p>
|
<p>The best way to identify a thread is through its managed id:</p>
<pre><code>Thread.CurrentThread.ManagedThreadId;
</code></pre>
<p>Since a finalizer always runs in the GC's thread you can create a finalizer that will save the thread id (or the thread object) in a static valiable.</p>
<p>Sample:</p>
<pre><code>public class ThreadTest {
public static Thread GCThread;
~ThreadTest() {
ThreadTest.GCThread = Thread.CurrentThread;
}
}
</code></pre>
<p>in your code just create an instance of this class and do a garbage collection:</p>
<pre><code>public static void Main() {
ThreadTest test = new ThreadTest();
test = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(ThreadTest.GCThread.ManagedThreadID);
}
</code></pre>
|
<p>I don't think that is possible even using the debugging APIs, see <a href="http://blogs.msdn.com/jmstall/archive/2006/03/02/expose-finalizer-thread.aspx" rel="nofollow noreferrer">this</a> blog post for more info.</p>
| 41,155
|
<p>We have a third party dll that is used in our web service hosted in IIS6. The problem is that once this dll is loaded into memory, the exception <a href="http://msdn.microsoft.com/en-us/library/system.accessviolationexception.aspx" rel="nofollow noreferrer">AccessViolationException</a> gets thrown if a thread different then the one that created it tries to execute any code within the dll. The worker process is multi threaded and each call to the web service will get a random thread from the pool. We tried to unload it from memory and reload it each time we needed it, but I guess only the front end is .Net and the rest is unmanaged so it never actually gets completely unloaded from memory. We are using VB and .Net 2.0. Any suggestions?</p>
<p>(Response to Rob Walker)</p>
<p>We thought about creating a new thread and using it to call the dll, but how do we make the thread sit and wait for calls? How do you delegate the call to the thread without having the Dispatcher class supplied by .Net 3.0? Creating a hidden form and putting it in a message loop might work. And then we could call the Invoke() method of the form. But I can see many problems occurring if we create a form inside an IIS hosted web service.</p>
|
<p>I have read about a class in .net 3.0 called <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx" rel="nofollow noreferrer">Dispatcher</a> that allows you to put a thread in a loop and then call the method Invoke() using a delegate to execute a method using the thread. But this solution will not work if you cannot update to .Net 3.0. Another solution would be to host the third party dll in another application on the server and use some form of <a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.aspx" rel="nofollow noreferrer">Remoting</a> to access it. But you may still have a problem with the Remoting because it behaves similar to IIS and will also pick a random thread to execute the code . To get around this, you could put a wrapper around the dll and use it to delegate the calls to the UI thread by using the Invoke() method of the form.</p>
|
<p>You could create a service that hosts the extra DLL. Via remoting you access the service, this will dispatch the calls the the thread that manages the DLL.</p>
<p>This way you have control over the thread that calls the DLL, and over the lifetime of the thread.</p>
| 6,630
|
<p>I've got a problem similar to,but subtly different from, that described <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">here</a> (Loading assemblies and their dependencies).</p>
<p>I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? </p>
<p>Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?</p>
<p>Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?</p>
|
<p>I finally have an answer for this that appears to work.</p>
<p>Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from.</p>
<p>The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like:</p>
<pre><code>static void Main(String[] argv)
{
// Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit
// sub-directories.
AppDomainSetup objADS = new AppDomainSetup();
System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
switch (System.IntPtr.Size)
{
case (4): assemblyDir += "\\win32\\";
break;
case (8): assemblyDir += "\\x64\\";
break;
}
objADS.ApplicationBase = assemblyDir;
// We set the PrivateBinPath to the application directory, so that we can still
// load the platform neutral assemblies from the app directory.
objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
AppDomain objAD = AppDomain.CreateDomain("", null, objADS);
if (argv.Length > 0)
objAD.ExecuteAssembly(argv[0]);
else
objAD.ExecuteAssembly("MyApplication.exe");
AppDomain.Unload(objAD);
}
</code></pre>
<p>You end up with 2 exes - your normal app and a second switching app that chooses which bits to load.
Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him</p>
|
<p>I encountered a similar scenario a while back. A toolkit I was using did not behave well in a 64-bit environment and I wasn't able to find a way to dynamically force the assemblies to bind as 32 bit.</p>
<p>It is possible to force your assemblies to work in 32 bit mode, but this requires patching the CLR header, (there is a tool that does that in the Framework) and if your assemblies are strongly-named, this does not work out.</p>
<p>I'm afraid you'll need to build and publish two sets of binaries for 32 and 64 bit platforms.</p>
| 4,232
|
<p>How can one load custom (not an image, nor a sound file) resource file from /res within .jar using MIDP 2.0?</p>
|
<p>I'm working with MIDP 2.1, but I hope this is in 2.0 too.</p>
<p>Class.getResource(path_to_resource) should give you an InputStream to the file.</p>
|
<pre><code>getResourceAsStream("/res/yourresource");
</code></pre>
| 14,693
|
<p>What's the best way of adding spaces between strings</p>
<pre><code>myString = string.Concat("a"," ","b")
</code></pre>
<p>or</p>
<pre><code>myString = string.Concat("a",Chr(9),"b")
</code></pre>
<p>I am using stringbuilder to build an XML file and looking for something efficient.</p>
<p>Thanks</p>
<p>Edit ~ Language VB.NET</p>
|
<p>Create your XML file with the XmlDocument class. Your wasting your time creating a string from scratch.</p>
|
<p>The simplest way is to use an aggregate function to combine the elements.</p>
<pre><code>string[] input = new string[]{"a", "b"};
var withSpaces = input.Aggregate( (x,y) => x + " " + );
</code></pre>
| 23,684
|
<p>I want to compress some files (into the <a href="http://en.wikipedia.org/wiki/ZIP_%28file_format%29" rel="nofollow noreferrer">ZIP</a> format) and encrypt them if possible using C#. Is there some way to do this?</p>
<p>Can encryption be done as a part of the compression itself?</p>
|
<p>For compression, look at the <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.aspx" rel="nofollow noreferrer"><code>System.IO.Compression</code></a> namespace and for encryption look at <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx" rel="nofollow noreferrer"><code>System.Security.Cryptography</code></a>.</p>
|
<p>Here is a useful topic:</p>
<p><a href="https://stackoverflow.com/questions/71000/help-in-creating-zip-files-from-net-and-reading-them-from-java">Help in creating Zip files from .Net and reading them from Java</a></p>
<p>System.IO.Packaging namespace gives you useful classes to compress data in zip format and <a href="http://msdn.microsoft.com/en-us/library/ms580548.aspx" rel="nofollow noreferrer">support</a> rights management.</p>
| 9,652
|
<p>I am developing a web site and need to see how it will look at different resolutions. The catch is that it must work on our Intranet.</p>
<p>Is there a free solution?</p>
|
<p>For Firefox, Web Developer Toolbar (<a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="noreferrer">https://addons.mozilla.org/en-US/firefox/addon/60</a>)</p>
|
<p>Also on Internet Explorer 7 is <a href="http://www.ie7pro.com/" rel="nofollow noreferrer">IE7Pro</a>. It also provides some gadgets that aren't in the Developer Toolbar. I have both installed, and use both quite often.</p>
| 8,760
|
<p>I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.</p>
<p>Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1).</p>
<p>So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?</p>
|
<p>You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that can lead to divide by zero errors.</p>
<pre><code>dx = x1-x2
dy = y1-y2
dist = sqrt(dx*dx + dy*dy)
dx /= dist
dy /= dist
x3 = x1 + (N/2)*dy
y3 = y1 - (N/2)*dx
x4 = x1 - (N/2)*dy
y4 = y1 + (N/2)*dx
</code></pre>
|
<p>If you want to avoid a sqrt, do the following:</p>
<pre><code>in: line_length, cap_length, rotation, position of line centre
define points:
tl (-line_length/2, cap_length)
tr (line_length/2, cap_length)
bl (-line_length/2, -cap_length)
br (line_length/2, -cap_length)
rotate the four points by 'rotation'
offset four points by 'position'
drawline (midpoint tl,bl to midpoint tr,br)
drawline (tl to bl)
drawline (tr to br)
</code></pre>
| 16,200
|
<p>Are there any tools for just browsing SQL Server? I ask because sometimes SSMS is a little heavy weight when I just want to look through the database and find one record, and SQLCMD doesn't really seem like a good choice when browsing through a lot of different records or a lot of large records.</p>
|
<p>Yes, <a href="http://www.albahari.com/queryexpress.aspx" rel="noreferrer">QueryExpress</a> is a great, lightweight tool (which also can be used from a USB stick) for browsing and querying SQL Server databases.</p>
|
<p>I'm using and I really like <a href="http://www.linqpad.net/" rel="nofollow noreferrer">LINQPad</a></p>
| 23,221
|
<p>I have a fairly large codebase that depends on MooTools v1.11 and am about to convert to version 1.2. Since this is a pretty major overhaul, I've toyed with the idea of converting to jQuery. </p>
<p>Anyone have advice on whether to update to jQuery or just stick with MooTools?</p>
<p>I mostly use MooTools for Ajax, drag and drop, and some minor effects.</p>
|
<p>If it's not broken. Don't fix it.</p>
<p>jQuery might have X or Y but if everything is dependent on MooTools, you might have a lot of work ahead of you to convert from MooTools.</p>
<p>Keep MooTools if you used it extensively through out your site. However, if you only have 2-3 pages with minor effects... the change might be worth it.</p>
|
<p>JQuery is a smaller codebase with wider support. If it meets your needs it might be a good switch. I would say that the trade off that you need to decide on is whether the migration effort and learning curve are worth the effort versus the wider feature set, smaller code size and popularity and support for JQuery.</p>
<p>If the change between versions of MooTools is really that steep then the migration might well be justified.</p>
| 20,416
|
<p>I want to print multiple objects in a single G-code file on my Maker Select Plus 3D Printer.</p>
<p>On the Cura "Machine>Machine Settings..." menu, what are the correct settings for "Printer head size" in the upper right quadrant?</p>
<p>My best guess is below:</p>
<p><a href="https://i.stack.imgur.com/hJkip.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hJkip.png" alt="Machine Settings Dialog"></a></p>
<p>Note 1: I'm particularly concerned that I got the min and max directions correct. For instance, I just swapped my Y min and Y max values because when I tried them the other way, the print head impacted the first object when printing the second.</p>
<p>Note 1.5: I added 10 mm to my settings because I was concerned that Cura wasn't accounting for the width of the raft that I usually use when I print.</p>
<p>Note 2: From what I've read online before posting this question, this printer may be physically the same as the WanHao Duplicator i3.</p>
|
<h3>TL;DR</h3>
<p>The settings that you seem to need can be found here: <a href="https://www.thingiverse.com/groups/i3/topic:6818" rel="noreferrer">Print One At a time settings? CURA</a>:</p>
<blockquote>
<p>You actually can!</p>
<p>Providing that none of your object is too tall (taller than the Gantry
clearance). Also the objects cannot be too close from each other (when
you activate the option and move objects on the bed, you see a gray
box around them showing this limit).</p>
<p>The reason you cannot use it at the moment is probably because you
didn't filled the printer head size parameters (Menu "Machine ->
Machine Settings..."). You will have to measure them, but on mine
(Australian clone of the i3) I use those values and it works fine:</p>
<ul>
<li>Head size toward X min: 30 </li>
<li>Head size toward Y min: 70 </li>
<li>Head size toward X max: 60 </li>
<li>Head size toward Y max: 50 </li>
<li>Printer gantry height: 35 </li>
</ul>
<p>Those are "conservative" values (a little bigger than the actual
values). It means I'm losing a little bed space, but I prefer that to
the risk of having the print head knocking out previous prints if one
of the measurements is too low :o).</p>
<p>PS: The option will automatically disable itself if some object
dimension are too big to avoid collisions</p>
</blockquote>
<p>To be fair, the rest of the thread is people debating whether you can successfully achieve <em>sequential printing</em>, or not, with the Wanhao Duplicator I3. </p>
<p>However, the setting above seem to be the settings that you are looking for. Apart from <em>Head size toward X max</em>, they also correlate, pretty much, to the settings that you have already determined. As the poster notes, their settings are, somewhat, on the conservative side, which would explain the difference.</p>
<hr>
<h3>Extra detail</h3>
<p>If this is so that you can achieve <em>sequential printing</em><sup>1</sup>, then this may not be suitable for your printer, unfortunately. Sequential printing works best for printers with a long nozzle with nothing (fans, X-axis gantry, etc.) around it, for example a delta printer with a low hanging nozzle would be ideal. Your printer type has a wide head with attachments, as well as an X-axis gantry, and so the clearance is less than that of an (ideal) delta.</p>
<p>See <a href="https://groups.google.com/forum/#!topic/wanhao-printer-3d/giqKBkZAjBM" rel="noreferrer">WanHao Duplicator i3 Printer Head Size Settings for Cura</a> for more details.</p>
<p>If you wish to go ahead and still try it, then from the <a href="https://groups.google.com/forum/#!topic/wanhao-printer-3d/giqKBkZAjBM" rel="noreferrer">same link</a>:</p>
<blockquote>
<p>The way to measure is lower the nozzle to the bed.</p>
<p>Then measure the space taken up around the nozzle by the heater block, fans, mounting, the motor, and finally, the distance between the X axis rods and the bed "WHEN the nozzle is touching the bed".</p>
<p>That gives you some idea of the clearance you have where an ALREADY printed object can exist on the bed and NOT get slammed into the gantry or moving head when printing a second sequential part.</p>
<p>Just a visual with a moving bed printer and it's not promising.
Not impossible, but in a 200mm square build area, you might really only get 4 objects at a time in the 4 quadrants.</p>
<p>Even that is height limited because the gantry will slam into it at a certain height.</p>
<p>Maybe some weird staggering pattern.</p>
</blockquote>
<p>Also, of use, for obtaining your own measurements, from <a href="https://ultimaker.com/en/community/7451-cura-1407-printer-head-size" rel="noreferrer">Ultimaker - Cura 14.07 Printer Head Size</a>:</p>
<blockquote>
<p>If I'm not mistaken all measurements are taken from the nozzle tip. So, for the first one, measure the size of your head from the nozzle tip towards the direction in X to where your machine homes.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>There's a tooltip when you mouse over these settings which describes what they mean.</p>
<p>Gantry height is the vertical clearance between the build plate and your x-y gantry (on the Ultimaker, these are the 6mm shafts which hold the head).</p>
<p>If you print two objects - one after another - then the first object must be shorter in height than the gantry height. Otherwise, the gantry would crash into the first part while printing the second part.</p>
</blockquote>
<p>In more detail, paying attention to the placing of the objects can aid with any issues that you have with a low gantry:</p>
<blockquote>
<p>If you place multiple parts in a diagonal line across the build-plate so the gantry and head never intersects earlier parts after printing them, you can set the gantry height to an artificially high value, to ignore it, without problems.</p>
<p>I place pieces along a diagonal from right-front to left-rear, to avoid conflict when the head homes after finishing the print. I can fit 3 to 4 small but tall pieces on the build plate that way for sequential printing.</p>
</blockquote>
<p>The purpose of these <em>Printer head size</em> settings is to enable Cura to determine the order in which the objects are printed:</p>
<blockquote>
<p>... none of those settings are important as long as you only print one STL file at a time. It's when you want to print multiple objects "one at a time" that these numbers have a purpose - it allows Cura to figure out which order to print them in and if it can do them one at a time or if it has to print them all at once.</p>
</blockquote>
<hr>
<h3>Footnote</h3>
<p><sup>1</sup> <em>Sequential Printing</em> is where one object is <em>completely</em> printed, before moving on to the next object, instead of the usual method of printing all objects <em>simultaneously</em> one layer at a time. This method can give superior quality prints, but not always. The main advantage appears to be reduced "stringing" of filament between objects, and a cleaner surface finish, due to reduced print head movement between objects. The process is detailed in <a href="https://www.simplify3d.com/support/articles/multi-part-printing/" rel="noreferrer">Multi-part printing</a>.</p>
|
<p>Like the OP, I'm confused by this as well. I figured I'd need measurements from the center of the nozzle to the left, right, front, and back of the print head, as well as a height from the print surface to the gantry while the head was homed. I've carefully measured, but things aren't going quite as I expected. In trying to understand this, I see examples like the one here:</p>
<ul>
<li>Head size toward X min: 30</li>
<li>Head size toward Y min: 70</li>
<li>Head size toward X max: 60</li>
<li>Head size toward Y max: 50</li>
</ul>
<p>How is 70 a minimum and 50 a maximum? What do these numbers really mean?</p>
<p>Also, I see the shading in the slicer (presumably one is a shadow, the middle one is a minimum, and the darker one is a maximum?) and changing my values don't affect these shadows in the way I'd expect.</p>
| 607
|
<p>I'm wondering if anyone has good resources to read or code to experiment for "autcomplete" </p>
<p>I would like to know what's the theory behind autocompletion, where to start what are the commonn mistakes etc. </p>
<p>I found fascinating the way products like Enso, Launchy, Google chrome and even tcsh perform their auto complete, I started my self just for curiosity some sample code and I got to the conclusion this must be a field widely explored before.</p>
<p>I would appreciate if someone shares any good technical resource on how to implement this.</p>
<p>Thanks in advance.</p>
|
<ul>
<li><a href="http://humanized.com/weblog/2007/03/30/what_makes_a_good_autocomplete/" rel="noreferrer">http://humanized.com/weblog/2007/03/30/what_makes_a_good_autocomplete/</a> -- </li>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/2ccb37b9-c7e1-4113-86ac-ad3d33b4b4b1/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/2ccb37b9-c7e1-4113-86ac-ad3d33b4b4b1/</a> -- in the .Net world </li>
<li>A <em>nasty</em> patent on autocompletion approach (still possibly worth reading for the <em>theory</em>) <a href="http://www.patentstorm.us/patents/5845300/description.html" rel="noreferrer">http://www.patentstorm.us/patents/5845300/description.html</a> </li>
<li><a href="http://ask.metafilter.com/91068/Fuzzy-text-completion-algorithm" rel="noreferrer">http://ask.metafilter.com/91068/Fuzzy-text-completion-algorithm</a> for a high level discussion on strategies to take.</li>
</ul>
|
<p>Autocomplete is usually implemented using one of the following:</p>
<ul>
<li><strong>Trees</strong>. By indexing the searchable text in a tree structure (prefix tree, suffix tree, dawg, etc..) one can execute very fast searches at the expense of memory storage. The tree traversal can be adapted for approximate matching.</li>
<li><strong>Pattern Partitioning</strong>. By partitioning the text into tokens (ngrams) one can execute searches for pattern occurrences using a simple hashing scheme.</li>
<li><strong>Filtering</strong>. Find a set of potential matches and then apply a sequential algorithm to check each candidate.</li>
</ul>
<p>A couple of papers about the subject:</p>
<ul>
<li>Bořivoj Melichar. Approximate String Matching by Finite Automata;</li>
<li>Gonzalo Navarro. A Guided Tour to Approximate String Matching;</li>
<li>Leonid Boytsov. Indexing Methods for Approximate Dictionary Searching: Comparative Analysis;</li>
<li>Marios Hadjieleftheriou and Divesh Srivastava. Approximate String Processing;</li>
<li>Surajit Chaudhuri and Raghav Kaushik. Extending Autocompletion To Tolerate Errors;</li>
</ul>
<p>Take a look at <a href="https://github.com/fmmfonseca/completely" rel="nofollow">completely</a>, a Java autocomplete library.</p>
| 28,073
|
<p>I am trying to create an application like the one here:</p>
<p><a href="http://www.eigenfaces.com/" rel="nofollow noreferrer">http://www.eigenfaces.com/</a></p>
<p>Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:</p>
<pre><code>import sys, random, time
import pygame
from pygame.locals import *
from pygame import draw
rand = random.randint
pygame.init( )
W = 320
H = 320
size = (W, H)
screen = pygame.display.set_mode(size)
run = True
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE :
run = not run
else:
sys.exit()
if run:
xc = rand(1, W)
yc = rand(1, H)
rc = rand(1, 25)
red = rand(1, 255)
grn = rand(1, 255)
blu = rand(1, 255)
draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0)
pygame.display.flip()
</code></pre>
|
<p>I got it to work by drawing to a surface that is not the display and combining the set colorkey and set alpha functions.</p>
<pre><code>import pygame
from pygame.locals import *
TRANSPARENT = (255,0,255)
pygame.init()
screen = pygame.display.set_mode((500,500))
surf1 = pygame.Surface((200,200))
surf1.fill(TRANSPARENT)
surf1.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf1, (0,0,200,100),(100,100), 100)
surf2 = pygame.Surface((200,200))
surf2.fill(TRANSPARENT)
surf2.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf2, (200,0,0,100),(100,100), 100)
surf1.set_alpha(100)
surf2.set_alpha(100)
while True:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
screen.blit(surf1, (100,100,100,100))
screen.blit(surf2, (200,200,100,100))
pygame.display.flip()
</code></pre>
<p>P.S
There's also the blend flags that you can put in the blit() arguments:
<a href="http://www.pygame.org/docs/ref/surface.html#Surface.blit" rel="noreferrer">Pygame.org - Surface.blit</a></p>
|
<p>I am Dave. Creator of the images at eigenfaces.com. Good luck with your experiments. I posted the code here:</p>
<p><a href="http://www.eigenfaces.com/" rel="nofollow noreferrer">http://www.eigenfaces.com/</a></p>
<p>Let me know if it's of use.</p>
<p>By the way.. I have also experimented with movies... Here is about 20 frames with about 1000 generations each:</p>
<p><a href="http://www.eigenfaces.com/img/morphs/anim-100x20.gif" rel="nofollow noreferrer">http://www.eigenfaces.com/img/morphs/anim-100x20.gif</a></p>
| 46,011
|
<p>I am working on an application where i need to transfer mails from a mailbox to anoter one.I can not send these mails using smtp because this willchange the header information .I am using C# and out look api to process mails . is thre any way i can transfer mails to other mail box without changing mail header.</p>
<hr>
<p>By Transfer I mean, I need to take a mail from one mail box and move this to another mailbox without changing any header information. If I use smtp , header information will be changed. I have heared that using MAPI mail can be moved from one mail box to another mail box. any pointers.</p>
|
<p>If you cannot load all relevant mailboxes into a single Outlook profile, then this cannot be solved using the Outlook API. It should however be possible to run a standalone application from an administrative account that accesses the Exchange information store directly via Extended MAPI. You can then open the source mailboxes sequentially and move the relevant mail items to the target mailbox.</p>
<p>This would allow you to run a batch job harvesting all mailboxes from a central location in a single giant operation. If however your task is to move messages as they appear then maybe addressing this in a more decentralized fashion via Outlook addins installed on the source machines might be a more sensible approach after all. Maybe if you told us a little bit more about your motivation for moving those items we can come up with an even better solution.</p>
<p>If you go for the centralized harvester approach I strongly recommend using a helper library like <a href="http://dimastr.com/redemption/" rel="nofollow noreferrer">Redemption</a> for this though as otherwise it will probably take a couple of months before you have gathered enough knowledge to address the task. The <a href="http://dimastr.com/redemption/rdo/" rel="nofollow noreferrer">RDO</a> framework (Redemption Data Objects) should be especially well suited to get you running ASAP.</p>
|
<p>If you use the Outloook API I'm sure there is support for backup and restore. So backup your mails from one account and restore it on the other. This would be my first try. PS: I'm not familiar with the API.</p>
| 46,791
|
<p>How do you impose a character limit on a text input in HTML?</p>
|
<p>There are 2 main solutions:</p>
<p>The pure HTML one:</p>
<pre><code><input type="text" id="Textbox" name="Textbox" maxlength="10" />
</code></pre>
<p>The JavaScript one (attach it to a onKey Event):</p>
<pre><code>function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</code></pre>
<p>But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.</p>
|
<p>you can set maxlength with jquery which is very fast</p>
<pre><code>jQuery(document).ready(function($){ //fire on DOM ready
setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})
</code></pre>
| 13,843
|
<p>I'm pretty sure the answer to this question is no, but in case there's some PHP guru</p>
<p>is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of <code>'@'</code></p>
<p>Much like empty and isset do. You can pass in a variable you just made up and it won't error.</p>
<pre><code>ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
</code></pre>
|
<p>Summing up, the proper answer is <strong>no, you shouldn't</strong> (see caveat below). </p>
<p>There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.</p>
<p>Summarizing an interesting comment discussion with <a href="https://stackoverflow.com/users/109561/gerry">Gerry</a>: Passing the variable by reference is indeed valid if you <strong>check for the value of the variable inside the function</strong> and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).</p>
|
<p>And going further up the abstraction tree, what are you using this for?</p>
<p>You could either initialize those values in each class as appropriate or create a specific class containing all the default values and attributes, like:</p>
<pre><code>class Configuration {
private var $configValues = array( 'cool' => 'Defaultcoolval' ,
'uncool' => 'Defuncoolval' );
public setCool($val) {
$this->configValues['cool'] = $val;
}
public getCool() {
return $this->configValues['cool'];
}
}
</code></pre>
<p>The idea being that, when using defaultValue function everywhere up and down in your code, it will become a maintenance nightmare whenever you have to change a value, looking for all the places where you've put a defaultValue call. And it'll also probably lead you to repeat yourself, violating DRY.</p>
<p>Whereas this is a single place to store all those default values. You might be tempted to avoid creating those setters and getters, but they also help in maintenance, in case it becomse pertinent to do some modification of outputs or validation of inputs.</p>
| 7,877
|
<p>Am just wondering if any conclusions can be drawn from this:</p>
<p><a href="https://i.stack.imgur.com/0RNE3.png" rel="nofollow noreferrer" title="Photo of poor adhesion"><img src="https://i.stack.imgur.com/0RNE3.png" alt="Photo of poor adhesion" title="Photo of poor adhesion"></a></p>
<p>Three corners are solid, but not the one in the centre of the plate.</p>
<p>The bed was levelled before printing (and checked afterwards also). Even though the photo may <em>appear</em> to show a slant or lower corner (where the print is coming off), there is not. The bed is level, relative to the extruder, at room temperature.</p>
<p>The temperature of the bed is about 70 °C. I get inconsistent readings (with laser thermometer) but to the finger it feels about the same everywhere.</p>
<p>It's a glass bed, presumably with some coating. Is it degraded? Local temperature variation? Any ideas anyone?</p>
|
<p>From here: <a href="https://io3dprint.com/review-anycubic-i3-mega-ultrabase/" rel="nofollow noreferrer">https://io3dprint.com/review-anycubic-i3-mega-ultrabase/</a></p>
<blockquote>
<p>Ultrabase Bed
The Anycubic i3 Mega Ultrabase is the latest version in the Anycubic i3 family. As hinted in the name, the main upgrade from the previous version is the Ultrabase bed. This is a textured coating on the Borosilicate glass bed that means you don’t need to apply any glue or tape to the bed to make your prints stick to it.</p>
<p>Ultrabase is similar to the popular BuildTak beds except unlike BuildTak it doesn’t wear off and the most significant benefit is that parts are exceptionally easy to remove once the bed has cooled.</p>
<p>The Ultrabase surface has a Moh’s hardness of over 7. This means you can safely use metal scrapers and blades to clean it without risk of it scratching!</p>
</blockquote>
<p>Perhaps it was just not cleaned sufficiently from a prior print.</p>
|
<p>From here: <a href="https://io3dprint.com/review-anycubic-i3-mega-ultrabase/" rel="nofollow noreferrer">https://io3dprint.com/review-anycubic-i3-mega-ultrabase/</a></p>
<blockquote>
<p>Ultrabase Bed
The Anycubic i3 Mega Ultrabase is the latest version in the Anycubic i3 family. As hinted in the name, the main upgrade from the previous version is the Ultrabase bed. This is a textured coating on the Borosilicate glass bed that means you don’t need to apply any glue or tape to the bed to make your prints stick to it.</p>
<p>Ultrabase is similar to the popular BuildTak beds except unlike BuildTak it doesn’t wear off and the most significant benefit is that parts are exceptionally easy to remove once the bed has cooled.</p>
<p>The Ultrabase surface has a Moh’s hardness of over 7. This means you can safely use metal scrapers and blades to clean it without risk of it scratching!</p>
</blockquote>
<p>Perhaps it was just not cleaned sufficiently from a prior print.</p>
| 1,403
|
<p>I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?</p>
|
<p>If you're having problems with syntax, you could try an editor with syntax highlighting. Until you get the feel for a language, simple errors won't just pop out at you.</p>
<p>The simplest form of debugging is just to insert some print statements. A more advanced (and extensible) way to do this would be to use the <a href="http://docs.python.org/library/logging.html#module-logging" rel="noreferrer">logging</a> module from the std lib.</p>
<p>The interactive interpreter is a wonderful tool for working with python code, and <a href="http://ipython.org" rel="noreferrer">IPython</a> is a great improvement over the built-in REPL (Read Eval Print Loop).</p>
<p>If you actually want to step through your code, the python debugger is called <a href="http://docs.python.org/library/pdb.html#module-pdb" rel="noreferrer">pdb</a>, which can be called from the command line, or embedded in your code.</p>
<p>If you're used to a fully integrated IDE, I would recommend using Eclipse with pydev, and PyCharm has a great commercial offering, with autocomplete, quick access to docs, and numerous shortcuts, among many other interesting features.</p>
|
<p>Eric4 IDE also has a great built-in debugger.</p>
| 38,408
|
<p>Can there be buffer overflow/overrun vulnerabilities in completely managed asp.net web portal.If yes how can this be tested.</p>
|
<p>Not unless you exploit the webserver or .NET/ASP.NET stack itself.</p>
|
<p>I had a tool (HP Dev Inspect) detect a possible "Possible Parameter Buffer Overflow" within my ASP.NET app and it was because we didn't have a MaxLength="20" in one of our TextBoxes...</p>
| 18,924
|
<p>In our current database development evironment we have automated build procceses check all the sql code out of svn create database scripts and apply them to the various development/qa databases.</p>
<p>This is all well and good, and is a tremdous improvement over what we did in the past, but we have a problem with rerunning scripts. Obviously this isn't a problem with some scripts like altering procedures, because you can run them over and over without adversly affecting the system. Right now to add metadata and run statements like create/alter table statements we add code to check and see if the objects exists, and if they do, don't run them.</p>
<p>Our problem is that we really only get one shot to run the script, because once the script has been run, the objects are in the environment and system won't run the script again. If something needs to change once it's been deployed, we have a difficult process of running update scripts agaist the update scripts and hoping that everything falls in the correct order and all of the PKs line up between the environments (the databases are, shall we say, "special").</p>
<p>Short of dropping the database and starting the process from scratch (the last most current release), does anyone have a more elegant solution to this? </p>
|
<p>I'm not sure how best to approach the problem in your specific environment, but I'd suggest reading up on Rail's migrations feature for some inspiration on how to get started. </p>
<p><a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations" rel="nofollow noreferrer">http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations</a></p>
|
<p>if you want to have re-runnability in your scripts, then you can't have them as definitions... what I mean by this is that you need to focus on change scripts rather than here is my Table script.</p>
<p>let's say you have a table Customers:</p>
<pre><code>create table Customers (
id int identity(1,1) primary key,
first_name varchar(255) not null,
last_name varchar(255) not null
)
</code></pre>
<p>and later you want to add a status column. Don't modify your original table script, that one has already run (and can have the if(! exists) syntax to prevent it from causing errors while running again).</p>
<p>Instead, have a new script, called add_customer_status.sql</p>
<p>in this script you'll have something like:</p>
<pre><code>alter table Customers
add column status varchar(50) null
update Customers set status = 'Silver' where status is null
alter table Customers
alter column status varchar(50) not null
</code></pre>
<p>Again you can wrap this with an if(! exists) block to allow re-running, but here we've leveraged the notion that this is a change script, and we adapt the database accordingly. If there is data already in the customers table then we're still okay, since we add the column, seed it with data, then add the not null constraint.</p>
<p>Both of the migration frameworks mentioned above are good, I've also had excellent experience with <a href="http://code.google.com/p/migratordotnet" rel="nofollow noreferrer">MigratorDotNet</a>.</p>
| 7,220
|
<p>Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python?</p>
<p>I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal.</p>
|
<p>See <a href="http://wiki.python.org/moin/Audio/" rel="noreferrer">http://wiki.python.org/moin/Audio/</a> and <a href="http://wiki.python.org/moin/PythonInMusic" rel="noreferrer">http://wiki.python.org/moin/PythonInMusic</a>, maybe some of the projects listed there can be of help.</p>
<p>Also, <a href="http://www.google.com/search?q=python+audio+library" rel="noreferrer">Google is your friend</a>.</p>
|
<p>I've never used it, but check out <a href="http://code.google.com/p/ounk/" rel="nofollow noreferrer">ounk</a>.</p>
| 6,723
|
<p>I have a Tronxy X5S and I am having issues calibrating my X and Y axis. When I print a 20 mm<sup>3</sup> cube it comes out 19.9 mm x 20.4 mm x 20 mm. I have already made the belt tensions as even as I can get them but it did not change the calibration cube size.</p>
<p>I have added <a href="https://www.thingiverse.com/thing:2815168" rel="nofollow noreferrer">this</a> upgrade to my printer for the idlers and motor mounts:</p>
<p><a href="https://i.stack.imgur.com/QG60X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QG60X.jpg" alt="idlers and motor mounts"></a></p>
<p>I have also upgraded the hotend to a V6 clone, after this change is when I noticed the discrepancy in the calibration print.</p>
<p><strong>What else can cause the X and Y axis to be uneven in a CoreXY printer besides uneven tension in the belts?</strong></p>
<p>UPDATE:</p>
<p>Its seems Oscar was correct in his <a href="https://3dprinting.stackexchange.com/questions/7002/corexy-calibration-issue#7003">assessment</a> that my printer is not printing square. I printed <a href="https://www.thingiverse.com/thing:2563185" rel="nofollow noreferrer">this</a> calibration square to measure the diagonals and I got: <span class="math-container">$ \overline{AC} = 141.82 $</span>, <span class="math-container">$ \overline{BD} = 141.35 $</span>. I believe the correct value for these diagonals should be <span class="math-container">$ \sqrt{2} \times 100 \approx 141.42 $</span>. </p>
<p><a href="https://cdn.thingiverse.com/renders/16/e6/d8/c1/f0/9bb6e035af9cc431b0bb4fa60281c967_preview_featured.jpg" rel="nofollow noreferrer"><img src="https://cdn.thingiverse.com/renders/16/e6/d8/c1/f0/9bb6e035af9cc431b0bb4fa60281c967_preview_featured.jpg" alt="calibration square"></a></p>
<p>Oscar also mentioned that I can adjust my firmware to correct this but I would rather fix the problem than apply a band-aid. Does this indicate that I did not assemble the printer frame correctly?</p>
|
<p>Indeed, <strong>even belt tension is important</strong>, what helped me enormously to set the same tension in the belts on my self build CoreXY is a tool like <a href="https://www.thingiverse.com/thing:2589577" rel="nofollow noreferrer">this</a>:</p>
<p><a href="https://i.stack.imgur.com/vmQKB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vmQKB.jpg" alt="Belt tension measurement tool"></a></p>
<p>Furthermore, be sure that you <strong>do not have any binding on the Y carriages</strong> over the whole range. This causes inaccurate printing, e.g. outer walls not adhering to the inner walls (as I encountered myself in the beginning when tuning the printer), and thus inaccurate dimensions.</p>
<p>Also make sure that the <strong>print is not skew</strong>, i.e. are you sure that the printer prints squares? This can be easily checked by printing a large square and measure the diagonals; I used <a href="https://www.thingiverse.com/thing:2280529" rel="nofollow noreferrer">this</a> as it will also help you find the center of the bed and the level of the bed all at once:</p>
<p><a href="https://i.stack.imgur.com/rcl8Bm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rcl8Bm.jpg" alt="Calibration square"></a></p>
<p>but many calibration prints can be found on the internet, e.g. <a href="https://www.thingiverse.com/thing:2563185" rel="nofollow noreferrer">this one</a> but this requires way more filament to print). Schematically this results in something like depicted below:</p>
<p><a href="https://i.stack.imgur.com/c3CRQm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3CRQm.jpg" alt="Schematic overview of a skew print"></a></p>
<p>If it is not square, you can adjust this by using a different firmware like e.g. Marlin Firmware which has options for skewness compensation that can be addressed in the <a href="http://marlinfw.org/" rel="nofollow noreferrer">Marlin</a> <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">Configuration.h</a> file. A "cube" that is printed by stacking parallelograms also shows different dimensions is X and Y (one being smaller, the other being larger).</p>
<p><strong><em>Edit</em></strong><br>
You mention that you changed the hotend; it is recommended to <a href="https://3dprinting.stackexchange.com/a/6484/5740">calibrate the extruder</a> after changing. Note that a few tenths of a mm are very common, usually X and Y should be in the range of 20.1 mm ± 0.1 mm for such a calibration cube.</p>
|
<p>Indeed, <strong>even belt tension is important</strong>, what helped me enormously to set the same tension in the belts on my self build CoreXY is a tool like <a href="https://www.thingiverse.com/thing:2589577" rel="nofollow noreferrer">this</a>:</p>
<p><a href="https://i.stack.imgur.com/vmQKB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vmQKB.jpg" alt="Belt tension measurement tool"></a></p>
<p>Furthermore, be sure that you <strong>do not have any binding on the Y carriages</strong> over the whole range. This causes inaccurate printing, e.g. outer walls not adhering to the inner walls (as I encountered myself in the beginning when tuning the printer), and thus inaccurate dimensions.</p>
<p>Also make sure that the <strong>print is not skew</strong>, i.e. are you sure that the printer prints squares? This can be easily checked by printing a large square and measure the diagonals; I used <a href="https://www.thingiverse.com/thing:2280529" rel="nofollow noreferrer">this</a> as it will also help you find the center of the bed and the level of the bed all at once:</p>
<p><a href="https://i.stack.imgur.com/rcl8Bm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rcl8Bm.jpg" alt="Calibration square"></a></p>
<p>but many calibration prints can be found on the internet, e.g. <a href="https://www.thingiverse.com/thing:2563185" rel="nofollow noreferrer">this one</a> but this requires way more filament to print). Schematically this results in something like depicted below:</p>
<p><a href="https://i.stack.imgur.com/c3CRQm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3CRQm.jpg" alt="Schematic overview of a skew print"></a></p>
<p>If it is not square, you can adjust this by using a different firmware like e.g. Marlin Firmware which has options for skewness compensation that can be addressed in the <a href="http://marlinfw.org/" rel="nofollow noreferrer">Marlin</a> <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">Configuration.h</a> file. A "cube" that is printed by stacking parallelograms also shows different dimensions is X and Y (one being smaller, the other being larger).</p>
<p><strong><em>Edit</em></strong><br>
You mention that you changed the hotend; it is recommended to <a href="https://3dprinting.stackexchange.com/a/6484/5740">calibrate the extruder</a> after changing. Note that a few tenths of a mm are very common, usually X and Y should be in the range of 20.1 mm ± 0.1 mm for such a calibration cube.</p>
| 1,048
|
<p>Ok time to show my complete lack of knowladge for all things web forms but here goes. I am extending the Panel control and OnPreRender sticking some additional controls inside of it (lets just say 1 textbox for simplicity). From here I am just letting the Panels Render method do its thing. </p>
<p>The issue I am having is that obviously every time this control is rerendered it is just sticks that same TextBox in the panel again with the value I am coding in the OnPreRender method. Now I dont actually want to repopulate the panel every time, </p>
<p>I want to stick the textbox contorl in there on first load and have them reloaded from the control/viewstate caches. In this case with my example of just sticking a single textbox in the panel, if the value of the textbox changes and a postback occurs I want that value to to remain the changed value. </p>
<p>Really basic webforms stuff I know, but I have never had to create custom controls in my time. ANy help appreciated. </p>
<p>Chris. </p>
|
<p>You need to (re)create the child control (the textbox) in OnInit - so that it's there when LoadViewState and ProcessPostBackData is called.</p>
<p>See the <a href="http://www.digcode.com/default.aspx?page=ed51cde3-d979-4daf-afae-fa6192562ea9&article=d3ba7954-6235-446f-9801-584539cbb6bf" rel="nofollow noreferrer">server control lifecycle</a> for more info.</p>
|
<p>Inside your code you will need to manage the restore of viewstate information should you need the services of viewstate.</p>
<p>A good example here is this <a href="http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx" rel="nofollow noreferrer">View State example</a> by Microsoft. There are a few other items referenced in the code sample, but it should get you along the right path.</p>
| 45,563
|
<p>How useful, if at all, is for the testers on a product team to know about the internal code details of a product. This does not mean they need to know every line of code but a good idea of how the code is structured, what is the object model, how the various modules are inter-linked, what are the inter-dependencies between various features etc.? This can argubaly help them in finding related issues or defects once they hit one. On the other side, this can potentially 'bias' their "user-centric" approach towards evaluating and certifying the product and can effect the testing results in the end.</p>
<p>I have not heard of any specific model for such interaction. (Lets assume a product that users, potentially non-technical consume, and not a framework or API that the testers are testing - in the latter case the testers may need to understand the code to test that because the user is another programmer). </p>
|
<p>That entirely depends upon the type of testing being done.</p>
<p>For functional system testing, the testers can and probably should be oblivious to the details of the implementation -- if they know the details they may inadvertently account for that in their test strategy and not properly test the product.</p>
<p>For performance and scalability testing it's often helpful for the testers to have some high-level knowledge of the structure of the codebase, as it's beneficial in identifying potential performance hotspots, and therefore writing targetted test cases. The reason this is important is that generally performance testing is a broad open-ended process, so anything that can be done to focus the testing to get results is beneficial to everybody.</p>
|
<p>I would say they don't need to know the internal code details at all. However they do need to know the required functionality and system rules in full detail - like an analyst. Otherwise they won't test all the functionality, or won't realise when the system misbehaves.</p>
| 28,887
|
<p>I'd like to zoom and unzoom in ways the base class doesn't support.</p>
<p>For instance, upon receiving a double tap.</p>
|
<p>I'm answering my own question, after playing with things and getting it working.</p>
<p>Apple has a very-simple example of this in their documentation on how to handle double taps.</p>
<p>The basic approach to doing programmatic zooms is to do it yourself, and then tell the UIScrollView that you did it.</p>
<ul>
<li>Adjust the internal view's frame and bounds.</li>
<li>Mark the internal view as needing display. </li>
<li>Tell the UIScrollView about the new content size.</li>
<li>Calculate the portion of your
internal view that should be
displayed after the zoom, and have
the UIScrollView pan to that
location.</li>
</ul>
<p>Also key: once you tell the UIScrollView about your new contents size it seems to reset its concept of the current zoom level. You are now at the new 1.0 zoom factor. So you'll almost certainly want to reset the minimum and maximum zoom factors.</p>
|
<p>Darren, can you provide a link to said Apple example? Or the title so that I may find it? I see <a href="http://developer.apple.com/iphone/library/samplecode/Touches/index.html" rel="nofollow noreferrer">http://developer.apple.com/iphone/library/samplecode/Touches/index.html</a> , but that doesn't cover the zooming.</p>
<p>The problem I'm seeing after a programatic zoom is that a gesture-zoom snaps the zoom back to what it was before the programatic zoom occurred. It seems that UIScrollView keeps state internally about the zoom factor/level, but I don't have conclusive evidence.</p>
<p>Thanks,
-andrew</p>
<p>EDIT: I just realized, you are working around the fact that you have little control over UIScrollView's internal zoom factor by resizing and changing the meaning of zoom-factor 1.0. A bit of a hack, but it seems like all Apple's left us with. Perhaps a custom class could encapsulate this trick...</p>
| 20,760
|
<p>Recently I was trying to make a calendar application that will display the current year-month-date to the user. The problem is, if the user is gonna keep my application running even for the next day, how do I get notified ?? How shall I change the date displayed ? I don't wanna poll the current date to update it. Is this possible in c#. </p>
<p>Note: I tried out the <strong>SystemEvent.TimeChanged</strong> event, but it works only if the user manually changes the time / date from the control panel.</p>
|
<p>Can you simply work out the number of seconds until midnight, and then sleep for that long?</p>
|
<p>How about a thread that checks for change in date. The thread can have some events that the controls that need this information can subscribe to.</p>
| 37,723
|
<p>Is it possible to have both</p>
<ul>
<li>NetTcp bound endpoints, and</li>
<li>basicHttp bound endpoints with SSL</li>
</ul>
<p>within a single deployment, either using Windows Service or IIS6?</p>
|
<p>Yes, a single service host can expose multiple endpoints with different bindings. However, normal IIS restrictions apply to IIS, so IIS 6 doesn't support NetTcp bindings to begin with.</p>
|
<p>Beginning with IIS 7.0 you <em>can</em> use the net.tcp binding with IIS. And <em>Yes</em> you can expose multiple bindings (i.e. wsHttpBinding and net.tcp) in a single WCF service installation. The following (2) links should help:</p>
<p><strong>Multiple Endpoints:</strong><br>
<a href="http://msdn.microsoft.com/en-us/library/ms751515.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms751515.aspx</a></p>
<p><strong>IIS 7 : Support for non-HTTP Protocols:</strong><br>
<a href="http://blogs.msdn.com/b/swiss_dpe_team/archive/2008/02/08/iis-7-support-for-non-http-protocols.aspx" rel="nofollow">http://blogs.msdn.com/b/swiss_dpe_team/archive/2008/02/08/iis-7-support-for-non-http-protocols.aspx</a></p>
| 24,845
|
<p>I'm just talking about JavaScript here, not CSS or implementation of the DOM.</p>
<p>I know getters and setters are now available in the latest release of all major browsers except IE. What other JavaScript features are available cross-browser if we have the latest versions of the other browsers and forget about IE for a minute?</p>
|
<p>With Gecko-engined browsers, you get:</p>
<ul>
<li><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6" rel="nofollow noreferrer">https://developer.mozilla.org/en/New_in_JavaScript_1.6</a></li>
<li><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7" rel="nofollow noreferrer">https://developer.mozilla.org/en/New_in_JavaScript_1.7</a></li>
<li><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.8" rel="nofollow noreferrer">https://developer.mozilla.org/en/New_in_JavaScript_1.8</a></li>
</ul>
<p>In terms of other browsers implementing these features, I'm only aware of Webkit implementing <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6#Array_extras" rel="nofollow noreferrer">Array Extras</a>, but it's actually quite easy to <a href="http://erik.eae.net/archives/2005/06/05/17.53.19/" rel="nofollow noreferrer">monkeypatch support for those in all browsers</a> since they're just additional methods.</p>
<p>Gecko, Opera and Webkit also support the <a href="https://developer.mozilla.org/en/Canvas_tutorial" rel="nofollow noreferrer"><code>canvas</code> element</a>, which although being a new HTML element, is used via JavaScript, so I'm not sure if that fits your criteria. Having said that, there are <a href="http://blog.vlad1.com/2008/07/30/no-browser-left-behind/" rel="nofollow noreferrer">independent efforts underway</a> to bring it to IE.</p>
|
<p>I would recommend you visit <a href="http://www.quirksmode.org" rel="nofollow noreferrer">www.quirksmode.org</a> for a lot of detailed comparisons of different browsers/versions.</p>
| 43,229
|
<p>I would like to get Binding object from web.config or app.config.</p>
<p>So, this code works:</p>
<pre><code>wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
</code></pre>
<p>but I would like to do the following:</p>
<pre><code>Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
</code></pre>
<p>I am interested in DoSomething() method, of course.</p>
|
<p>You can instantiate a binding giving a binding configuration name from App.config/Web.config.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms575163.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms575163.aspx</a></p>
<blockquote>
<p>Initializes a new instance of the WSHttpBinding class with a binding specified by its configuration name.</p>
<p>The following example shows how to initialize a new instance of the
WSHttpBinding class with a string argument.</p>
<pre><code>// Set the IssuerBinding to a WSHttpBinding loaded from config
b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer");
</code></pre>
</blockquote>
|
<p>One cheeky option might be to create an instance with the default constructor, to use as a template:</p>
<pre><code>Binding defaultBinding;
using(TestServiceClient client = new TestServiceClient()) {
defaultBinding = client.Endpoint.Binding;
}
</code></pre>
<p>Then tuck this away and re-use it. Any help?</p>
| 46,347
|
<p>I'm writing a C# program that acts as a PowerPoint 2007 plugin. On some machines, some calls to the PowerPoint object model throw a <code>COMException</code> with the message <code>RPC_E_SYS_CALL_FAILED</code>. I couldn't find any specific advice on what to do regarding this error, or how to avoid it. From Googling it looks like something to do with the message queue or Single-Threaded Apartments. Or am I way off?</p>
<p>Example of the error message is:</p>
<blockquote>
<p>System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))<br>
at Microsoft.Office.Interop.PowerPoint._Presentation.get_FullName()</p>
</blockquote>
<p>Unfortunately, the problem is occurring on a client's machine, so I have no easy way to debug it! Should I just retry the calls whenever I get this error?</p>
<p>Any advice to help me resolve this problem would be greatly appreciated!</p>
|
<p>I don't know it is related to your problem, but all your COM calls must come from within the same thread your add-in was created on. If you created new threads you must take special care. Details are described in these two articles:</p>
<ul>
<li><a href="http://blogs.msdn.com/andreww/archive/2008/11/19/implementing-imessagefilter-in-an-office-add-in.aspx" rel="nofollow noreferrer">Implementing IMessageFilter in an Office add-in</a> and </li>
<li><a href="http://blogs.msdn.com/andreww/archive/2008/08/11/why-your-comaddin-object-should-derive-from-standardolemarshalobject.aspx" rel="nofollow noreferrer">Why your COMAddIn.Object should derive from StandardOleMarshalObject</a></li>
</ul>
|
<p>are you making the call from a thread with its ApartmentState set? if not, that might be the culprit - COM interop is pretty finicky about that sort of thing</p>
| 12,448
|
<p>I have a console app in which I want to give the user <em>x</em> seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response.</p>
<p>What is the most straightforward way of approaching this?</p>
|
<p>I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems:</p>
<ul>
<li>A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input).</li>
<li>Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior).</li>
<li>Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem.</li>
</ul>
<p>I believe my solution will solve the original problem without suffering from any of the above problems:</p>
<pre><code>class Reader {
private static Thread inputThread;
private static AutoResetEvent getInput, gotInput;
private static string input;
static Reader() {
getInput = new AutoResetEvent(false);
gotInput = new AutoResetEvent(false);
inputThread = new Thread(reader);
inputThread.IsBackground = true;
inputThread.Start();
}
private static void reader() {
while (true) {
getInput.WaitOne();
input = Console.ReadLine();
gotInput.Set();
}
}
// omit the parameter to read a line without a timeout
public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) {
getInput.Set();
bool success = gotInput.WaitOne(timeOutMillisecs);
if (success)
return input;
else
throw new TimeoutException("User did not provide input within the timelimit.");
}
}
</code></pre>
<p>Calling is, of course, very easy:</p>
<pre><code>try {
Console.WriteLine("Please enter your name within the next 5 seconds.");
string name = Reader.ReadLine(5000);
Console.WriteLine("Hello, {0}!", name);
} catch (TimeoutException) {
Console.WriteLine("Sorry, you waited too long.");
}
</code></pre>
<p>Alternatively, you can use the <code>TryXX(out)</code> convention, as shmueli suggested:</p>
<pre><code> public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) {
getInput.Set();
bool success = gotInput.WaitOne(timeOutMillisecs);
if (success)
line = input;
else
line = null;
return success;
}
</code></pre>
<p>Which is called as follows:</p>
<pre><code>Console.WriteLine("Please enter your name within the next 5 seconds.");
string name;
bool success = Reader.TryReadLine(out name, 5000);
if (!success)
Console.WriteLine("Sorry, you waited too long.");
else
Console.WriteLine("Hello, {0}!", name);
</code></pre>
<p>In both cases, you cannot mix calls to <code>Reader</code> with normal <code>Console.ReadLine</code> calls: if the <code>Reader</code> times out, there will be a hanging <code>ReadLine</code> call. Instead, if you want to have a normal (non-timed) <code>ReadLine</code> call, just use the <code>Reader</code> and omit the timeout, so that it defaults to an infinite timeout.</p>
<p>So how about those problems of the other solutions I mentioned?</p>
<ul>
<li>As you can see, ReadLine is used, avoiding the first problem.</li>
<li>The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input.</li>
<li>And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources.</li>
</ul>
<p>The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to <code>Reader.ReadLine</code> anyway.</p>
|
<p>Another cheap way to get a 2nd thread is to wrap it in a delegate.</p>
| 8,196
|
<p>I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons?</p>
|
<p>There isn't any built in support for mod_python logging to Apache currently. If you really want to work within the Apache logs you can check out this thread (make sure you get the second version of the posted code, rather than the first):</p>
<ul>
<li><a href="http://www.dojoforum.com/node/13239" rel="nofollow noreferrer">http://www.dojoforum.com/node/13239</a></li>
<li><a href="http://www.modpython.org/pipermail/mod_python/2005-October/019295.html" rel="nofollow noreferrer">http://www.modpython.org/pipermail/mod_python/2005-October/019295.html</a></li>
</ul>
<p>If you're just looking to use a more structured logging system, the Python standard logging module referred to by Blair is very feature complete. Aside from the Python.org docs Blair linked, here's a more in-depth look at the module's features from onLamp: </p>
<ul>
<li><a href="http://www.onlamp.com/pub/a/python/2005/06/02/logging.html" rel="nofollow noreferrer">http://www.onlamp.com/pub/a/python/2005/06/02/logging.html</a></li>
</ul>
<p>And for a quickie example usage: </p>
<ul>
<li><a href="http://hackmap.blogspot.com/2007/06/note-to-self-using-python-logging.html" rel="nofollow noreferrer">http://hackmap.blogspot.com/2007/06/note-to-self-using-python-logging.html</a></li>
</ul>
|
<p>I concur with Blair Conrad's post about the Python logging module. The standard log handlers sometimes drop messages however. It's worth using the logging module's SocketHandler and building a receiver to listen for messages and write them to file.</p>
<p>Here's mine: <a href="http://www.djangosnippets.org/snippets/1116/" rel="nofollow noreferrer">Example SocketHandler receiver</a>.</p>
| 20,554
|
<p>If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.</p>
<p>Today our signal handler looks as follows:</p>
<pre><code>void catchSignal (int reason) {
std :: cerr << "Caught a signal: " << reason << std::endl;
exit (1);
}
</code></pre>
<p>I can hear the screams of horror with the above, as I have read from this <a href="http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&q=deadlock#" rel="nofollow noreferrer">thread</a> that it is evil to call a non-reentrant function from a signal handler.</p>
<p>Is there a portable way to handle the signal and provide information to users?</p>
<p><strong>EDIT:</strong> Or at least portable within the POSIX framework?</p>
|
<p>This <a href="http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948" rel="nofollow noreferrer">table</a> lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.</p>
<p>By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick:</p>
<pre><code>#include <csignal>
#ifdef _WINDOWS_
#define _exit _Exit
#else
#include <unistd.h>
#endif
#define PRINT_SIGNAL(X) case X: \
write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \
break;
void catchSignal (int reason) {
char s[] = "Caught signal: (";
write (STDERR_FILENO, s, sizeof(s) - 1);
switch (reason)
{
// These are the handlers that we catch
PRINT_SIGNAL(SIGUSR1);
PRINT_SIGNAL(SIGHUP);
PRINT_SIGNAL(SIGINT);
PRINT_SIGNAL(SIGQUIT);
PRINT_SIGNAL(SIGABRT);
PRINT_SIGNAL(SIGILL);
PRINT_SIGNAL(SIGFPE);
PRINT_SIGNAL(SIGBUS);
PRINT_SIGNAL(SIGSEGV);
PRINT_SIGNAL(SIGTERM);
}
_Exit (1); // 'exit' is not async-signal-safe
}
</code></pre>
<p><strong>EDIT:</strong> Building on windows.</p>
<p>After trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'.</p>
<pre><code>#include <io.h>
#define STDIO_FILENO 2
</code></pre>
<p><strong>EDIT:</strong> 'exit' should not be called from the signal handler either!</p>
<p>As pointed out by <a href="https://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413">fizzer</a>, calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig_atomic_t" type can be used to notify the main program that it should exit.</p>
<p>The following I found useful in my searches.</p>
<ol>
<li><a href="http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html" rel="nofollow noreferrer">Introduction To Unix Signals Programming</a> </li>
<li><a href="http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html" rel="nofollow noreferrer">Extending Traditional Signals</a></li>
</ol>
|
<p>Write a launcher program to run your program and report abnormal exit code to the user.</p>
| 12,883
|
<p>I'm tinkering with Silverlight 2.0.</p>
<p>I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?</p>
<p>Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?</p>
|
<p>In the code behind or a value converter you can do </p>
<pre><code> Uri uri = new Uri("http://testsvr.com/hello.jpg");
YourImage.Source = new BitmapImage(uri);
</code></pre>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.interop.silverlighthost.source(VS.95).aspx" rel="nofollow noreferrer">SilverlightHost.Source</a> will provide you the URL that was used to load the XAP file. You can use this to then construct a relative URL for your images.</p>
<p>So if for example your XAP is hosted on <a href="http://foo.bar/ClientBin/bas.xap" rel="nofollow noreferrer">http://foo.bar/ClientBin/bas.xap</a> and your images were stored in <a href="http://foo.bar/Images/" rel="nofollow noreferrer">http://foo.bar/Images/</a> you can simply use the Source to grab the host name and protocol to construct the new URI.</p>
| 28,751
|
<p>In my WCF service, I have methods that are currently public, but I want to hide them from the outside world but be able to use them in my WCF service.</p>
<p>Is internal what I'm looking at?</p>
|
<p>You can use the := syntax to assign the parameters to a Sub or Function by name, rather than strictly by position. For example:</p>
<pre><code>Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TestRoutine(Y:="TestString", X:=12)
End Sub
Private Sub TestRoutine(ByVal X As Long, Optional Y As String = "")
' Do something with X and Y here... '
End Sub
End Class
</code></pre>
<p>Note that TestRoutine specifies X as the first parameter, and Y as the second, but the call in Form1_Load has them in the opposite order, naming each parameter with the := operator.</p>
<p>Here's a link to an MSDN article on the subject:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/51wfzyw0.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/51wfzyw0.aspx</a></p>
<p>I don't see this used very often, except in VBA macros generated by Excel's macro recorder, which uses it <strong><em>a lot</em></strong>.</p>
|
<p>VB uses that operator for attribute value assignments:</p>
<p><a href="http://www.ondotnet.com/pub/a/dotnet/excerpt/vbnut_8/index1.html" rel="nofollow noreferrer">http://www.ondotnet.com/pub/a/dotnet/excerpt/vbnut_8/index1.html</a></p>
| 38,844
|
<p>Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project?</p>
<p>What do other people do?</p>
|
<p>store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case</p>
<p>Edit for 2017:
This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on .net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example <a href="https://www.sonatype.com/nexus-repository-oss" rel="noreferrer">Sonatype Nexus</a> or <a href="https://www.jfrog.com/open-source/" rel="noreferrer">JFrog Artifcatory</a>, among many others.</p>
|
<p>store everything you'll need to build the project, so you can check it out and build without doing anything.</p>
<p>(and, as someone who has experienced the pain - please keep a copy of everything needed to get the controls installed and working on a dev platform. I once got a project that could build - but without an installation file and reg keys, you couldn't make any alterations to the third-party control layout. That was a fun rewrite)</p>
| 7,167
|
<p>If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this:</p>
<pre><code>public void EndEdit()
{
// BeginEdit would set _editInProgress and update *Editing fields;
if (_editInProgress)
{
_line1 = _line1Editing;
_line2 = _line2Editing;
_city = _cityEditing;
_state = _stateEditing;
_postalCode = _postalCodeEditing;
_editInProgress = false;
}
}
</code></pre>
<p>If there is an exception updating <strong><em>_state</em></strong>, for example, then all 5 properties should reset. This atomic update issue probably isn't limited to EndEdit.</p>
|
<p>First off, Kent is correct in wondering why setting a field would throw an exception.<br>
Ignoring that question; you could just use a simple:</p>
<pre><code>try {
//do stuff
}
catch (Exception ex) {
//reset
//rethrow exception
throw;
}
</code></pre>
<p>The complications come in with regards to what constitutes the reset value for each field? </p>
<ul>
<li>The last value</li>
<li>A default value</li>
<li>Some token value denoting an invalid state</li>
<li>A mix of the above</li>
</ul>
<p>If you need to "reset" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong. Check out the <a href="http://www.primos.com.au/primos/Default.aspx?PageContentID=8&tabid=63" rel="nofollow noreferrer">Momento Pattern</a> on a nifty way to deal with that problem.</p>
|
<p>I don't use fields for storing values. Instead I use a hash table that the properties can read and write. This gives me a really simple design.</p>
<pre><code>Friend Sub BeginEdit()
m_Backup = New Dictionary(Of String, Object)(m_DataPoints, StringComparer.OrdinalIgnoreCase)
End Sub
Friend Sub CancelEdit()
If m_Backup IsNot Nothing Then m_DataPoints = m_Backup
End Sub
Friend Sub EndEdit()
m_Backup = Nothing
End Sub
</code></pre>
| 21,613
|
<p>I am programming in C against a third party library (in HP/Mercury Loadrunner) that allows a varargs-style variable size argument list for one of it's functions. I want to call this function but I do not know up front how many arguments I will have. </p>
<p>There is a function made by one of my predecessors that serves somewhat but the problem here is that this function assumes the worst case scenario (over 3000 arguments) and hand-codes for that.</p>
<p>To illuminate, here's the (beginning of) the code. The function we call is <code>web_submit_data()</code>. It will HTTP post a set of form data. This implementation came about when dealing with dynamically generated forms with an arbitrary number of fields.
(Cleaned up a fair bit from the original, which hand coded indexes by hand as well..)</p>
<hr>
<pre><code>web_submit_data_buffer_gazillion_items( const char *bufferName, const char *bufferValue)
{
const int size = 129;
int i = 0;
int j = 11;
web_submit_data(&bufferName[i++ * size], //"some form"
&bufferName[i++ * size], //"Action=https://blah.blah/form");
&bufferName[i++ * size], //"Method=POST");
&bufferName[i++ * size], //"TargetFrame=");
&bufferName[i++ * size], //"RecContentType=text/html");
&bufferName[i++ * size], //"Referer=https://blah.blah/index.html");
&bufferName[i++ * size], //"Snapshot=t1.inf");
&bufferName[i++ * size], //"Mode=HTML");
ITEMDATA, // missing in action: indexes 8 through 10
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
..
(repeat the last 3 lines ad nauseum)
..
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size]);
}
</code></pre>
<p>Now I have found an external library that might work (<a href="http://www.dyncall.org" rel="noreferrer">http://www.dyncall.org</a>) but I would much rather not a) be completely processor dependant and b) attempt to teach Loadrunner about linking in external sources..</p>
<p>Edit:
The original function used hardcoded indexes instead of using a variable. Can still revert to that if it turns out to be too unpredictable. However, as I am unlikely to run this with a different compiler or hardware / OS I doubt that really is worth it.</p>
<p>Also: I don't have control over the implementation of web_submit_data(). So just pushing the problem down one level isn't going to cut it..</p>
<p>Another thing to note: The spec for <code>web_submit_data()</code> uses a constant called LAST to mark the end of the argument list. The original implementation doesn't use it. Presumably the callsite does ..</p>
|
<p>In CamelBones I use <a href="http://sourceware.org/libffi/" rel="noreferrer">libffi</a> to call objc_msgSend(), which is a varargs function. Works a treat.</p>
|
<p>I know this is an old thread, but I just ran across it. The proper way to handle variable length submit form data in LoadRunner is to use a web_custom_request(). You build the name|value pair structure for the variable length of the arguments as a string and pass it in as a part of the function. </p>
<p>Record the one call as a web_custom_request() and the structure of the argument string for the name|value pairs will become obvious. Simply use any C string handling functions you wish to construct the string in question and include it as a part of the argument list for the web_custom_request().</p>
| 35,539
|
<p>What's the best strategy to use when writing JMeters tests against a web application where the values of certain query-string and post variables are going to change for each run.</p>
<p>Quick, common, example</p>
<ol>
<li>You go to a Web Page</li>
<li>Enter some information into a form</li>
<li>Click Save</li>
<li>Behind the scenes, a new record is entered in the database</li>
<li>You want to edit the record you just entered, so you go to another web page. Behind the scenes it's passing the page a parameter with the Database ID of the row you just created</li>
</ol>
<p>When you're running step 5 of the above test, the page parameter/Database ID is going to change each time. </p>
<p>The workflow/strategy I'm currently using is</p>
<ol>
<li>Record a test using the above actions</li>
<li>Make a note of each place where a query string variable may change from run to run</li>
<li>Use a XPath or Regular Expression Extractor to pull the value out of a response and into a JMeter variable</li>
<li>Replace all appropriate instances of the hard-coded parameter with the above variable.</li>
</ol>
<p>This works and can be automated to an extent. However, it can get tedious, is error prone, and fragile. Is there a better/commonly accepted way of handling this situation? (Or is this why most people just use JMeter to play back logs? (-;)</p>
|
<p>Sounds to me like your on the right track. The best that can be achieved by JMeter is to extract page variables with a regular expression or xpath post processor. However your absolutely correct in that this is not a scalable solution and becomes increasingly tricky to maintain or grow. </p>
<p>If you've reached is point then you may want to consider a tool which is more specialised for this sort of problem. Have a look web testing tool such as Watir, it will automatically handle changing post parameters; but you would still need to extract parameters if you need to do a database update but using Watir allows for better code reuse making the problem less painful.</p>
|
<p>We have had great success in testing similar scenarios with JMeter by storing parameters in JMeter Variables within a JDBC assertion. We then do our http get/post and use a BSF Assertion and javascript do complex validation of the response. Hope it helps</p>
| 38,546
|
<p>That is, all text and subtags, without the tag of an element itself?</p>
<p>Having</p>
<pre><code><p>blah <b>bleh</b> blih</p>
</code></pre>
<p>I want </p>
<pre><code>blah <b>bleh</b> blih
</code></pre>
<p>element.text returns "blah " and etree.tostring(element) returns:</p>
<pre><code><p>blah <b>bleh</b> blih</p>
</code></pre>
|
<p>ElementTree works perfectly, you have to assemble the answer yourself. Something like this...</p>
<pre><code>"".join( [ "" if t.text is None else t.text ] + [ xml.tostring(e) for e in t.getchildren() ] )
</code></pre>
<p>Thanks to JV amd PEZ for pointing out the errors.</p>
<hr>
<p>Edit.</p>
<pre><code>>>> import xml.etree.ElementTree as xml
>>> s= '<p>blah <b>bleh</b> blih</p>\n'
>>> t=xml.fromstring(s)
>>> "".join( [ t.text ] + [ xml.tostring(e) for e in t.getchildren() ] )
'blah <b>bleh</b> blih'
>>>
</code></pre>
<p>Tail not needed.</p>
|
<p>No idea if an external library might be an option, but anyway -- assuming there is one <code><p></code> with this text on the page, a jQuery-solution would be:</p>
<pre><code>alert($('p').html()); // returns blah <b>bleh</b> blih
</code></pre>
| 49,874
|
<p>I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the <em>rendered</em> HTML.</p>
<p>To clarify, I want to be able to see the side-by-side diffs <em>as</em> rendered output. So if I delete a paragraph, the side by side view would know to space things correctly.</p>
<hr>
<p>@Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter.</p>
|
<p>There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs.</p>
<p>Side-by-side rendered HTML will make it very difficult for your diff to line up vertically. Vertical alignment is crucial for comparing side-by-side diffs. In order to improve the vertical alignment of a side-by-side diff, you can insert invisible HTML elements in each version of the diff at "checkpoints" where the diff should be vertically aligned. Then you can use a bit of client-side JavaScript to add vertical spacing around checkpoint until the sides line up vertically.</p>
<p>Explained in a little more detail:</p>
<p>If you want to use this technique, run your diff algorithm and insert a bunch of <code>visibility:hidden</code> <code><span></code>s or tiny <code><div></code>s wherever your side-by-side versions should match up, according to the diff. Then run JavaScript that finds each checkpoint (and its side-by-side neighbor) and adds vertical spacing to the checkpoint that is higher-up (shallower) on the page. Now your rendered HTML diff will be vertically aligned up to that checkpoint, and you can continue repairing vertical alignment down the rest of your side-by-side page.</p>
|
<p>I believe a good way to do this is to <a href="http://weblogs.mozillazine.org/roc/archives/2005/05/rendering_web_p.html" rel="nofollow noreferrer">render the HTML to an image</a> and then use some <a href="http://www.scootersoftware.com/" rel="nofollow noreferrer">diff tool that can compare images</a> to spot the differences. </p>
| 5,165
|
<p>I have a batch file (in windows XP, with command extension activated) with the following line:</p>
<pre><code>for /f %%s in ('type version.txt') do set VERSION=%%s
</code></pre>
<p>On some computer, it works just fine (as illustrated by <a href="https://stackoverflow.com/questions/130116/dos-batch-commands-to-read-first-line-from-text-file">this SO question</a>), but on other <strong>it kills cmd</strong> (the console window just closes)</p>
<p>Why ?</p>
<hr>
<p>Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY_CURRENT_USER\Software\Microsoft\Command Processor...</p>
|
<p>I got a first empiric answer:</p>
<pre><code>for /f %%s in (version.txt) do ...
</code></pre>
<p>works just fine, on every computer.</p>
<p>It seems <code>for /f</code> works with a filename, not with any dos command like 'type filename'.</p>
<p>However, it is not true for all my client's computer (on some, the 'type filename' works fine)</p>
<p>If you want 15 (easy ?) points ;-), you can leave an answer to the question:<br>
<strong>why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?</strong></p>
<hr>
<p>Edit: 3 years later(!), <a href="https://stackoverflow.com/users/385907/barlop">barlop</a> faced a similar situation, detailed in the question "<a href="https://stackoverflow.com/questions/7236499/for-f-closes-cmd-prompt-immediately"><code>for /f</code> closes cmd prompt immediately?</a>". His conclusion was:</p>
<blockquote>
<p><code>COMSPEC</code> did get listed when doing <code>SET</code>+<kbd>ENTER</kbd>.<br>
So, I opened the environment variables window, and saw <code>COMSPEC</code> was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine. </p>
</blockquote>
<p>This <a href="http://ss64.org/viewtopic.php?id=504" rel="nofollow noreferrer">thread on ss64 forum</a>, mentioned by <a href="https://stackoverflow.com/users/297408/andriy-m">Andriy M</a> in his answer to barlop's question, contains the details.</p>
<blockquote>
<p>The shelling out in the "<code>for</code>" loop to complete '<code>dir</code>' (or whatever command you've asked to complete) requires <code>ComSpec</code> to be set in order to reload the <code>cmd</code> window.</p>
</blockquote>
<pre><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\ComSpec=
%SystemRoot%\system32\cmd.exe
</code></pre>
|
<p>Is it that the file doesn't have an extension and thus the cmd treats it like a directory that doesn't exist?</p>
| 32,664
|
<p>I have a local Git repository I've been developing under for a few days: it has eighteen commits so far. Tonight, I created a private Github repository I was hoping to push it to; however, when I did so, it only ended up pushing eight of the eighteen commits to Github. I deleted the Github repo and retried, with the same result.</p>
<p>Any thoughts on why this might be happening? I've done this procedure before without a few times successfully, so I'm a bit stumped.</p>
<p><strong>Update</strong>: There is, and has always been, only the master branch in this repo. Just to address a few of the posted answers...</p>
|
<p>I took a look at the repository in question and here's what was going on:</p>
<ul>
<li>At some point, rpj had performed <code>git checkout [commit id]</code>. This pointed HEAD at a loose commit rather than a recognized branch. I believe this is the "dangling HEAD" problem that CesarB is referring to.</li>
<li>Not realizing this problem, he went on making changing and committing them, which bumped HEAD up every time. However, HEAD was just pointing at a dangling chain of commits, not at a recognized branch.</li>
<li>When he went to push his changes, git pushed everything up to the top of master, which was only about halfway through the current tree he was on.</li>
<li>Confusion ensued</li>
</ul>
<p>This diagram should make it more clear:</p>
<pre><code> -- D -- E -- F
/ ^
A -- B -- C - |
^ ^ HEAD
| |
remote master
</code></pre>
<p>When he tried to push his changes, only <code>A</code> through <code>C</code> were pushed and <code>remote</code> moved up to <code>C</code>. He couldn't get commits <code>D</code> through <code>F</code> to push because they aren't referenced by a known branch.</p>
<p>Here's what you see when you're in this state:</p>
<pre><code>$ git branch
* (no branch)
master
</code></pre>
<p>The solution is to move <code>master</code> up to <code>F</code> in the dangling chain of commits. Here's how I did it.</p>
<ul>
<li><p>Create a legitimate branch for the current state:</p>
<p><code>git checkout -b tmp</code></p>
<ul>
<li>The <code>tmp</code> branch is now pointing at commit <code>F</code> in the diagram above</li>
</ul></li>
<li><p>Fast-forward <code>master</code> to <code>tmp</code></p>
<p><code>git checkout master</code></p>
<p><code>git merge tmp</code></p>
<ul>
<li><code>master</code> is now pointing at commit <code>F</code>. </li>
</ul></li>
<li><p>Throw away your temporary branch</p>
<p><code>git branch -d tmp</code></p></li>
<li><p>You can happily push to the remote repository and it should send all of your changes.</p></li>
</ul>
|
<p>So, it turns out that both: the commit hash in .git/refs/heads/master was incorrect and the information in .git/logs/refs/heads/master was incomplete; in that I mean it only went up to and included the commit hash specified in .git/refs/heads/master.</p>
<p>Once I fixed these files (by hand), and pushed them back to Github, everything was gravy again. I still have <strong>no idea</strong> what happened to get things in this state, but I'm glad I've at least figured out the fix.</p>
<p>In case anyone is wondering: to fix .git/refs/heads/master, I just replaced the content of that file with the latest commit hash (HEAD), and to fix .git/logs/refs/heads/master, I simply copied the contents of .git/logs/HEAD into .git/logs/refs/heads/master. Easy peasy... NOT.</p>
| 29,386
|
<p>Is it possible to protect flv files from download? I'd like to protect my files from download but I don't have the money for a streaming server which I think provides some sort of protection. The files are streamed via PHP and are located in an upload folder on my server.</p>
<p>I've used PHP to ensure that only subscribers can view the video but I basically want to go a step further and prevent subscribers from, upon login, downloading my videos with downloaders such as Sothink Flv Downloader for Firefox.</p>
|
<p>I fully agree with the DRM consensus of other answers. But would like to add...</p>
<p>There are a couple of <em><strong><a href="http://en.wikipedia.org/wiki/Obfuscation" rel="noreferrer">obfuscation</a></strong></em> techniques that may meet you needs. <em>"Good enough"</em>, as they say. These aren't full proof mechanisms, but very well may prevent 80%-99% of people trying to copy your <code>FLV</code> streams/files. A dedicated hacker will get to it, but most folks are just script kiddies (or their FireFox plug-in loving cousins.) Plus, some of these techniques are really easy:</p>
<ul>
<li><strong>Change/remove the MIME type</strong> the server is responding with. Flash players blissfully ignore it anyway. E.g.: image/jpeg</li>
<li><strong>Change the file extension</strong> from .flv to something else, like .jpg. Again, Flash players blissfully ignore it anyway. Additionally, once the file is saved to disk, a non-FLV player will open it (and complain about it being an invalid file format.)</li>
<li><strong>Set aggressive 'don't cache' headers</strong> for all your <code>FLV</code> content. (This, naturally, means more traffic and bandwidth consumed. Maybe this is not an issue for you?)</li>
<li><strong>Stream over UDP-based protocols</strong> (like RTSP). While my read is that UDP protocols are on the way out for large scale streaming of on demand content, it is much more difficult to copy. E.g.: Real Downloader cannot currently pilfer these streams.</li>
<li><strong>Break up content into two or more pieces</strong> of partial content, and play them back to back.</li>
<li><strong>Hide your FLV content behind a simple, custom one-time authentication mechanism</strong>
<ul>
<li>Player requests authorization key for content A</li>
<li>Server returns an <em>authorization1</em> key: <em>SHA1</em>(content key + <em>salt1</em>)</li>
<li>Server stores content key, <em>authorization1</em> key, <em>authorization2</em> key (which is <em>SHA1</em>(<em>authorization1</em> + <em>salt2</em>))
<ul>
<li>one time use</li>
<li>limited validity (E.g.: 2 seconds)</li>
</ul>
</li>
<li>Player creates <em>authorization2</em></li>
<li>Player requests content a with <em>authorization2</em></li>
<li>Server sends ´FLV´ content to client if and only if
<ul>
<li>authorization key matches to content key in server side store</li>
<li>authorization key has not expired</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>I've actually implemented that last idea, the authorization mechanism, myself and can vouch for it's practical effectiveness. No, it is not totally secure. But it is good enough. Not even a power users is capable of beating it.</p>
<p>Defeating it requires</p>
<ol>
<li>reverse engineering the process,</li>
<li>decompiling your Flash player,</li>
<li>putting it all back together again.</li>
</ol>
<h1>Good enough.</h1>
<hr />
<p>It is amazing how many <em>"plz sends me teh codez"</em> emails this post has generated from the <em>"simple, custom one-time authentication mechanism"</em> suggestion. Don't bother, I can't--it was for a proprietary project for my employer, <a href="http://xtendx.com" rel="noreferrer">xtendx AG</a>. If interested in purchasing the system, email sales@xtendx.com.</p>
|
<p>No protection can beat a simple use of WireShark + NetMiner.</p>
<p>Period.</p>
<p>Oh and by the way, about youtube, if you use Chrome check out this extension:</p>
<p><a href="http://hosting.gmodules.com/ig/gadgets/file/113621719436589749332/ZiTube.crx" rel="nofollow noreferrer">http://hosting.gmodules.com/ig/gadgets/file/113621719436589749332/ZiTube.crx</a></p>
<p>It just creates a download button under youtube videos ;)</p>
| 38,565
|
<p>In a multi-threaded program running on a multi-cpu machine do I need to access shared state ( _data in the example code below) using volatile read/writes to ensure correctness.</p>
<p>In other words, can heap objects be cached on the cpu?</p>
<p>Using the example below and assuming multi-threads will access the GetValue and Add methods, I need ThreadA to be able to add data (using the Add Method) and ThreadB to be able to see/get that added data immediately (using the GetValue method). So do I need to add volatile reads/writes to _data to ensure this? Basically I don’t want to added data to be cached on ThreadA’s cpu.</p>
<p>/ I am not Locking (enforcing exclusive thread access) as the code needs to be ultra-fast and I am not removing any data from _data so I don’t need to lock _data.</p>
<p>Thanks.</p>
<p>**** Update ****************************</p>
<p>Obviously you guys think going lock-free using this example is bad idea. But what side effects or exceptions could I face here?</p>
<p>Could the Dictionary type throw an exception if 1 thread is iterating the values for read and another thread is iterating the values for update? Or would I just experience “dirty reads” (which would be fine in my case)?</p>
<p>**** End Update ****************************</p>
<pre><code>public sealed class Data
{
private volatile readonly Dictionary<string, double> _data = new Dictionary<string, double>();
public double GetVaule(string key)
{
double value;
if (!_data.TryGetValue(key, out value))
{
throw new ArgumentException(string.Format("Key {0} does not exist.", key));
}
return value;
}
public void Add(string key, double value)
{
_data.Add(key, value);
}
public void Clear()
{
_data.Clear();
}
}
</code></pre>
<hr>
<p>Thanks for the replies. Regarding the locks, the methods are pretty much constantly called by mulitple threads so my problem is with contested locks not the actual lock operation.</p>
<p>So my question is about cpu caching, can heap objects (the _data instance field) be cached on a cpu? Do i need the access the _data field using volatile reads/writes?</p>
<p>/Also, I am stuck with .Net 2.0.</p>
<p>Thanks for your help.</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer">MSDN docs</a> for <code>Dictionary<TKey, TValue></code> say that it's safe for multiple <em>readers</em> but they don't give the "one writer, multiple readers" guarantee that some other classes do. In short, I wouldn't do this.</p>
<p>You say you're avoiding locking because you need the code to be "ultra-fast" - have you <em>tried</em> locking to see what the overhead is? Uncontested locks are very cheap, and when the lock is contested that's when you're benefiting from the added safety. I'd certainly profile this extensively before deciding to worry about the concurrency issues of a lock-free solution. <code>ReaderWriterLockSlim</code> may be useful if you've actually got multiple readers, but it sounds like you've got a single reader and a single writer, at least at the moment - simple locking will be easier in this case.</p>
|
<p>Volatile is not locking, it has nothing to do with synchronization. It's generally safe to do lock-free reads on read-only data. Note that just because you don't remove anything from _data, you seem to call _data.Add(). That is NOT read-only. So yes, this code will blow up in your face in a variety of exciting and difficult to predict ways. </p>
<p>Use locks, it's simple, it's safer. If you're a lock-free guru (you're not!), AND profiling shows a bottleneck related to contention for the lock, AND you cannot solve the contention issues via partitioning or switching to spin-locks THEN AND ONLY THEN can you investigate a solution to get lock-free reads, which WILL involve writing your own Dictionary from scratch and MAY be faster than the locking solution.</p>
<p>Are you starting to see how far off base you are in your thinking here? Just use a damn lock!</p>
| 45,438
|
<p>I am looking for some recommendations on good places to find libraries of controls/templates/styles for WPF. I know about the usual places like Infragistics, but it seems to me that there should be some kind of community effort by now to share nice, clean, well written controls for WPF controls.</p>
<p>I am not big on the design side, and it would be nice to fill out my personal libraries with some nice examples from people who are better at design.</p>
<p>Any ideas or recommendations?</p>
|
<p>I strongly recommend the <a href="http://mahapps.com/" rel="noreferrer">MahApps</a> it's simply awesome! </p>
|
<p>Check out <a href="http://www.nukeation.com/reuxables.aspx" rel="nofollow noreferrer">Reuxables</a> although it comes at a cost.</p>
| 14,801
|
<p>In Linux environment, when getting "glibc detected *** free(): invalid pointer" errors, how do I identify which line of code is causing it?</p>
<p>Is there a way to force an abort? I recall there being an ENV var to control this?</p>
<p>How to set a breakpoint in gdb for the glibc error?</p>
|
<p>I believe if you setenv <code>MALLOC_CHECK_</code> to 2, glibc will call <code>abort()</code> when it detects the "free(): invalid pointer" error. Note the trailing underscore in the name of the environment variable.</p>
<p>If <code>MALLOC_CHECK_</code> is 1 glibc will print "free(): invalid pointer" (and similar printfs for other errors). If <code>MALLOC_CHECK_</code> is 0, glibc will silently ignore such errors and simply return. If <code>MALLOC_CHECK_</code> is 3 glibc will print the message and then call <code>abort()</code>. I.e. its a bitmask.</p>
<p>You can also call <code>mallopt(M_CHECK_ACTION, arg)</code> with an argument of 0-3, and get the same result as with <code>MALLOC_CHECK_</code>.</p>
<p>Since you're seeing the "free(): invalid pointer" message I think you must already be setting <code>MALLOC_CHECK_</code> or calling <code>mallopt()</code>. By default glibc does not print those messages.</p>
<p>As for how to debug it, installing a handler for <code>SIGABRT</code> is probably the best way to proceed. You can set a breakpoint in your handler or deliberately trigger a core dump.</p>
|
<p>In general, it looks like you might have to recompile glibc, ugh.</p>
<p>You don't say what environment you're running on, but if you can recompile your code for OS X, then its version of libc has a free() that listens to this environment variable:</p>
<pre><code>MallocErrorAbort If set, causes abort(3) to be called if an
error was encountered in malloc(3) or
free(3) , such as a calling free(3) on a
pointer previously freed.
</code></pre>
<p>The man page for free() on OS X has more information. </p>
<p>If you're on Linux, then try <a href="http://valgrind.org/" rel="nofollow noreferrer">Valgrind</a>, it can find some impossible-to-hunt bugs.</p>
| 18,232
|
<p>I've been trying to design a database schema for a side project but I havent been able to produce anything that I'm comfortable with. I'm using ASP.Net with LINQ for my data access:</p>
<p>I'm going to allow users to specify up to 10 "items" each with 2 numeric properties, and 1 referential property, the item name.</p>
<p>If I were to put this entry into 1 row, it would easily equal out to some 30+ columns (minimum), e.g.
item_1_name (ref)
item_1_weight
item_1_volume
item_2_name... etc...</p>
<p>And I can't simply turn these columns into referential tables as each property can essentially range from 1 to 400+.</p>
<p>I also figured that if a user only decides to put 1 item into their entry, the method of which I create the object for that data will be static as with LINQ I'd have to check whether the properties and whatnot are NULL and work accordingly. Also, if I ever wanted to increase the number of items allowed in an entry, it'd be a headache to work with.</p>
<p>The other option I've thought of is simply creating a row for each item and tying it with an entry id. So I'd essentially never have null entries, but my table would grow astronomically deep but not very wide, as there would only be some 5 odd columns.</p>
<p>Is there something I'm overlooking in my design/is there a much better and efficient way of doing this?</p>
<p>EDIT: When I say that it will grow astronomically, I mean it in this sense: A user can create an entry, and each entry will most likely have a group of items. So say they make 1 entry a day to the site, they could have 3 groups of items, with the max number of items (10), which would equate to 30 items for that sole entry. Make an entry everyday for a week at that rate and you could have 210 rows for that single user.</p>
|
<p>I'd recommend the latter design you mention, create one dependent table with five columns:</p>
<pre><code>CREATE TABLE Items (
user_id INTEGER NOT NULL,
item_id INTEGER NOT NULL DEFAULT 1,
numeric_property1 INTEGER,
numeric_property2 INTEGER,
referential_property INTEGER,
PRIMARY KEY (user_id, item_id),
FOREIGN KEY (user_id) REFERENCES Users(user_id)
ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES num_items(item_id),
FOREIGN KEY (referential_property) REFERENCES some_other_table(some_column)
);
</code></pre>
<p>I show a table <code>num_items</code> above, which contains the numbers 1 through 10 if you want to restrict users to 10 items at most:</p>
<pre><code>CREATE TABLE num_items (item_id INTEGER NOT NULL );
INSERT INTO num_items (item_id)
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
</code></pre>
<p>Advantages of this design is that it's easy to <code>COUNT()</code> how many items a given user has, it's easy to compute things like <code>MIN()</code> and <code>MAX()</code> for a given property, you can enforce a foreign key for the referential property, etc.</p>
<p>Some databases have a feature to declare the second part of a compound primary key (<code>item_id</code> in this case) as auto-incrementing, so if you specify the value for <code>entity_id</code> but omit <code>item_id</code> it automatically gets the next unused value (but does not fill gaps if you delete one). You don't state which brand of database you're using so I'll leave it to you to figure out this feature.</p>
<p><strong>edit:</strong> As Tony Andrews says in his answer, the number of rows is not a problem. You don't state which brand of database you're intending to use, but unless you choose an especially feeble product like MS Access, you can rely on the database to process millions of rows easily. If you choose indexes well, and write queries that use those indexes, efficiency shouldn't be a problem.</p>
|
<p>use a single item table: </p>
<p>userId, itemIndex, isReference, numericValue, referenceValue</p>
<p>this way the value for item_3_name for user 999 translates to</p>
<p>999,3,true,null,value</p>
<p>You will have to enforce certain constraints yourself, s.a. the maximal number of items per user, etc.</p>
| 32,830
|
<p>A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.</p>
<p>The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).</p>
<p>This works better, in any case much better than having all those objects need some global <em>Settings</em> object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.</p>
<p><strong>So the general question is</strong>: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...</p>
<p>(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)</p>
|
<p>You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:</p>
<pre><code>class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
</code></pre>
<p>Your production code then initializes the service locator like this:</p>
<pre><code>ServiceLocator::load(new ServiceLocator());
</code></pre>
<p>In your test-code, you insert your mock-settings like this:</p>
<pre><code>ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
</code></pre>
<p>It's a repository for singletons that can be exchanged for testing purposes.</p>
|
<p>Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting when neeed.</p>
<p>.NET has this built in with the ConfigurationManager classes, but it's quite easy to implement, just read text files, or load XML into DOM or parse them by hand in code.</p>
<p>Having config files in the database is ok, but it does tie you to the database, and creates an extra dependancy for your app that ini/xml files solve.</p>
| 3,322
|
<p>I am trying to install SQL server express 2008 on my machine. I get an error message that says that older version of VS 2008 in installed on the computer. Upgrade to VS2008 SP1 before installing Sql server 2008. </p>
<p>I tried to install sp1 but I get an error message that a compatible version of vs2008 is not detected on the system. the upgrade is not compatible with express editions. </p>
<p>I am having trouble installing sql server 2008 express installed on my machine and I am having problems. Please help me. </p>
|
<p>You need to have the full version of Visual Studio 2008 installed in order to upgrade to Service Pack 1. You should have a look on the MS site for an SP1 specific to the Express editions of Visual Studio.</p>
<p>In fact I'm not certain but try redownloading Visual Studio express and it should have SP1 already integrated. Here's a <a href="http://www.microsoft.com/express/vb/default.aspx" rel="nofollow noreferrer">link</a>.</p>
<p>Best of luck!</p>
|
<p>It isn't compulsory to install the full version of Visual Studio 2008 to upgrade to Service Pack 1. You can install any of the express editions with sp1, ideally Visual C++ and C#. If you already have them installed on your PC, re-install and remove any old versions of SQL Server Express(2000 or 2005 in Add/Remove Programs). Finally, install SQL Server 2008 Express; this should solve the problem. </p>
<p>Best of luck! </p>
| 34,868
|
<p>Is there a way to change the default pages used to edit/create/view a Sharepoint list item without using SharePoint designer? Since I've already created the aspx files on the development machine, it seem's a bit silly to have to install SharePoint designer on the customers server just to set a few default pages.</p>
|
<p>Take a look at <a href="http://www.red-gate.com/products/SQL_Prompt/index.htm" rel="noreferrer">Red Gate's SQL Prompt</a>.</p>
|
<p>It's not Management Studio, but <a href="http://www.toadworld.com/Products/ToadforSQLServer/tabid/217/Default.aspx" rel="nofollow noreferrer">Toad</a> has a freeware version with autocomplete.</p>
| 30,369
|
<p>I am looking for a powerful meta-language to describa behaviour for an application i intend to use in offline mode (google-gears + javascript) and server side sqlite + (php/ruby/java etc) and looking for a good format to describe the model's behaviour which can be easily converted to the target languages.
Am I completely off track, and there is a much better way?</p>
|
<p>Have you looked at <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">Google Web Toolkit</a>? GWT allows you to write server side Java objects which get translated into Javascript for you. This allows you to not deal with the browser quirks at all.
I'm not sure how well integrated the Gears and GWT projects are, however. If it isn't integrated yet, I'm sure it will be in fairly short order.</p>
<p>Edit: This is probably more of an alternate way of doing what you're looking for, rather than a suggestion for a meta language.</p>
|
<p>Maybe you should consider using <a href="http://www.codeplex.com/scriptsharp" rel="nofollow noreferrer">Script#</a>?</p>
| 6,416
|
<p>Consider the following use of template template parameters...</p>
<pre><code>#include <iostream>
template <typename X>
class A
{
X _t;
public:
A(X t)
:_t(t)
{
}
X GetValue()
{
return _t;
}
};
template <typename T, template <typename T> class C >
class B
{
C<T> _c;
public:
B(T t)
:_c(t)
{
}
T GetValue()
{
return _c.GetValue();
}
};
using namespace std;
int main()
{
B<int, A> b(10);
cout<<b.GetValue();
return 0;
}
</code></pre>
<p>Is there a way by which the template parameter T can be removed? For example is there a way to make the following work?</p>
<pre><code>//Does not compile
template <template <typename T> class C >
class B
{
C _c;
public:
B(T t)
:_c(t)
{
}
T GetValue()
{
return _c.GetValue();
}
};
int main()
{
B< A<int> > b(10);
cout<<b.GetValue();
return 0;
}
</code></pre>
|
<p>I assume you're after X, as well as A, in your code. </p>
<p>The usual pattern is to have</p>
<pre><code>template<typename C>
struct B
{
C c;
};
</code></pre>
<p>and then, inside classes eligible for substitution:</p>
<pre><code>template<typename X>
class A
{
typedef X type_name;
X t;
};
</code></pre>
<p>Then you can access the template parameter using <code>C::type_name</code>.</p>
|
<p>What is wrong with:</p>
<pre><code>template <typename C >
struct B
{
C c;
};
int main()
{
B< A<int> > b;
return 0;
}
</code></pre>
| 40,520
|
<p>How to add new item in existing string array in C#.net?</p>
<p>I need to preserve the existing data.</p>
|
<p>I would use a List if you need a dynamically sized array:</p>
<pre><code>List<string> ls = new List<string>();
ls.Add("Hello");
</code></pre>
|
<pre><code>private static string[] GetMergedArray(string[] originalArray, string[] newArray)
{
int startIndexForNewArray = originalArray.Length;
Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);
newArray.CopyTo(originalArray, startIndexForNewArray);
return originalArray;
}
</code></pre>
| 31,013
|
<p>So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.</p>
<p>The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.</p>
<p>I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?</p>
<p>Thanks!</p>
|
<p>This is my favorite trick :)</p>
<p>Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events.</p>
<p>The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the <code>LoadViewState()</code> call, but you must create the controls before that call to have the events fired correctly.</p>
<p>The trick is to override <code>LoadViewState()</code> and <code>SaveViewState()</code> so we can control things.</p>
<p><em>(note that the code below is rough, from memory and probably has issues)</em></p>
<pre><code>private string searchQuery = null;
private void SearchButton(object sender, EventArgs e)
{
searchQuery = searchBox.Text;
var results = DataLayer.PerformSearch(searchQuery);
CreateLinkButtonControls(results);
}
// We save both the base state object, plus our query string. Everything here must be serializable.
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
return new object[] { baseState, searchQuery };
}
// The parameter to this method is the exact object we returned from SaveViewState().
protected override void LoadViewState(object savedState)
{
object[] stateArray = (object[])savedState;
searchQuery = stateArray[1] as string;
// Re-run the query
var results = DataLayer.PerformSearch(searchQuery);
// Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.
CreateLinkButtonControls(results);
// Very important - load the rest of the ViewState, including our controls above.
base.LoadViewState(stateArray[0]);
}
</code></pre>
|
<p>A dirty hack I just came up with, is to create dummy LinkButtons with the same IDs as the real buttons.
So let's say you are going to create a LinkButton "foo" at Pre_Render (which is too late), then also create a dummy foo at Page_Load:</p>
<pre><code> var link = new LinkButton();
link.ID = "foo";
link.Click += fooEventHandler;
dummyButtons.Controls.Add(link);
</code></pre>
<p>(Where "dummyButtons" is just a PlaceHolder on the page with Visibility set to false.)
It's ugly, but it works.</p>
| 17,051
|
<p>I have a hidden field that i want to bind to either a function on the page's code behind. I don't quite recall the exact syntax and i can't find the answer via Google. Is the code below correct? Thank.</p>
<pre><code>print("<asp:HiddenField ID="dummy" Value='<%#Getdummy() %>' runat="server" />");
</code></pre>
|
<p>The code you've put looks pretty good ...</p>
<p>The two step process is ... add the hidden field to the markup</p>
<pre><code><asp:HiddenField ID="hdnId" runat="server" Value='<%# GetValue() %>'/>
</code></pre>
<p>Then create the specified method signature ...</p>
<pre><code>protected string GetValue()
{
return "something";
}
</code></pre>
<p>Hope this helps ...</p>
|
<p>If you have the hidden field with runat=server, you could write code to assign value in the code behind (rather than in the markup).</p>
| 39,001
|
<p>I'm new to 3D Printing and recently purchased an Ender 3D PRO I'm having an issue with the filament guide tube getting pushed out of the nozzle on the feeding mechanism. The assembly instructions don't include a whole lot of detail about installing this guide tube but there are blue clips that were included along with the spare nozzle. There are no instructions on where to use these blue clips and I have a hunch this might be the problem. </p>
|
<p>The blue clips stick in the connector on the extruder end of the feed tube. They are to keep it from opening as the printer extrudes and retracts filament.</p>
<p>To install them, push them in between the white part of the fitting on the feed tube (not the hot end). You should only need one or two, and they are all of varying thicknesses. If you're not familiar with these fittings, I found a <a href="https://www.youtube.com/watch?v=6BummHzgf5c" rel="nofollow noreferrer">YouTube video</a> on how to use them.</p>
<p><a href="https://i.stack.imgur.com/JsuQ4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JsuQ4.jpg" alt="Fitting clips on a Creality Ender-3 feed tube"></a></p>
|
<p>The clips or collet clips as they are called are to secure the Bowden tube more solidly to improve printer extrusion; more specifically: extruder retraction performance.</p>
<p>E3D has explained this very nicely on their site under <a href="https://e3d-online.com/blog/2017/10/27/bowden-tube-physics/" rel="nofollow noreferrer">Bowden tube physics</a>:</p>
<blockquote>
<p>For the bowden couplings (which can have some wiggle room in them) we are introducing collet clips, which slide under the toothed collet part of the coupling that physically holds the tube and locks it into place with a little pre-tension to boot. This reduces coupling lash to near zero as the collet and tube it is holding are locked into place.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/YobdM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YobdM.png" alt="Bowden collet clips principle"></a></p>
<p>From the <a href="https://i.imgur.com/RTWnzB5.gif" rel="nofollow noreferrer">animated gif from the E3D website</a> (animated gifs are not allowed on SE) it can be seen that without clips, the tube can move in the tube coupling:
<a href="https://i.stack.imgur.com/YfzfWm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YfzfWm.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/2OpuTm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2OpuTm.png" alt="enter image description here"></a></p>
| 1,624
|
<p>I had experience with struts, and briefly experimented with tiles. I know that within a layout each tile is a separate jsp page. Suppose I hit a button on each of four tiles, and each tile was (indirectly) calling a different web service. Would the tiles refresh asynchronously as results came in at different times?</p>
|
<p>Tiles are just fragments of one html page. There's no notion of ajax unless you manually add it. Therefor: Pressing 4 buttons on one page would be the same as clicking 4 links on any html page. The browser will send the appropriate request to the server. When the server answers very quickly, you wouldn't even have time to press the second button. When it's slow enough, the first request (browser to server) would be cancelled and the second (third, fourth) would be sent (and cancelled with the next button pressed).</p>
<p>The rest depends upon the backend implementation: At some point in time the server will notice that it cannot send back data for 3 of the 4 requests. What will be served/displayed in the last (open) response also depends upon your implementation. If there's some server side state holding the web services response, all 4 results might show up. If one web service hasn't returned yet, only 3 results and one old tile might show up.</p>
|
<p>I think it would depend on the code in the background. You say that the tiles were indirectly calling web services. I would think it would refresh asynchronously unless you specified in your code for it not to do so. Say you push button 1 and then button 2. Action 1 comes back and your code says that the screen needs to be updated and the page will refresh. Once action 2 gets back, your code would again update the screen. I believe this is how it works, but having never tried it, I can't be sure.</p>
<p>Why not just throw together a two tiled test page with buttons and try it out. That should give you a definitive answer.</p>
| 36,192
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.