instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'd like to create a script that will configure the Visual Studio IDE the way I like it. Nothing vastly complicated, just a few Tools/Options settings, adding some External Tools, that kind of thing. </p> <p>I know that this can be done inside VS with Import/Export Settings, but I'd like to be able to automate it from outside of VS. Is this possible, and if so, how?</p> <hr> <p>Edited to add: doing it from <em>outside</em> of VS is important to me -- I'm hoping to use this as part of a more general "configure this newly-Ghosted PC just the way I like it" script.</p> <hr> <p>Edited again: the solution seems to be to hack CurrentSettings.vssettings, or use <a href="http://www.autoitscript.com/" rel="noreferrer">AutoIt</a>. Details below.</p>
<p>Answering my own question, in two ways:</p> <ol> <li><p>In VS2005/8, the things I mentioned (Tools/Options, External Tools) are all stored in the CurrentSettings.vssettings file, in the folder "Visual Studio 200{5|8}\Settings". This file is just XML, and it can be edited programmatically by anything that knows how to parse XML. You can also just paste a new vssettings file over the top of the default one (at least, this works for me).</p></li> <li><p>The larger question of configuring a virgin PC. It turns out that not everything I want to change has an API, so I need some way of pretending to be a user who is actually sitting there clicking on things. The best approach to this seems to be <a href="http://www.autoitscript.com/" rel="nofollow noreferrer">AutoIt</a>, whose scripting language I will now have to learn in my Copious Free Time.</p></li> </ol>
<p>On my machine Visual Studio stores it's local settings in a file called VCComponents.dat. Its a text file, so perhaps you could find a way of placing your settings directly in there.</p> <p>The file is stored in my users local AppData\Local\Microsoft\VC folder</p>
6,419
<p>Does anyone know of a good code static code analyser for vb.net? </p> <p>I've seen plenty for c#, and I think VS 2008 some one built in. But we're currently only using vs 2005...</p>
<p><a href="http://en.wikipedia.org/wiki/FxCop" rel="noreferrer">FxCop</a> does just that.</p> <p>Specific for VB.NET is <a href="http://en.wikipedia.org/wiki/Project_Analyzer" rel="noreferrer">Project Analyzer</a>.</p>
<p>You can use the tool <a href="http://www.NDepend.com" rel="nofollow noreferrer">NDepend</a> which analysis all .NET code (C#, VB.NET, F#...). For VB.NET code you'll miss 2 metrics on source code comment and source code cyclomatic complexity (but you still have CC computed from IL code).</p> <p>See all feature of NDepend here <a href="http://www.ndepend.com/Features.aspx" rel="nofollow noreferrer"><a href="http://www.ndepend.com/Features.aspx" rel="nofollow noreferrer">http://www.ndepend.com/Features.aspx</a></a>: <br> - Code Query and Rule over LINQ (CQLinq) <br> - Compare Builds <br> - 82 code metrics <br> - Manage Complexity and Dependencies <br> - Detect Dependency Cycles <br> - Harness Test Coverage Data <br> - Enforce Immutability and Purity <br> - Warnings about the health of your Build Process <br> - Generate custom report from your Build Process <br> - Diagrams <br> - Facilities to cope with real-world environment</p>
44,523
<p>I am dropping something in a ListView in WPF. I need to know the item in the (X,Y) position I am dropping. How can I do this?</p> <hr> <p>The WPF ListView doesn't have GetItemAt. I return to my original problem.</p>
<p>Done! Thanks to this article <a href="http://www.codeproject.com/KB/WPF/WPF_Drag_And_Drop_Sample.aspx" rel="noreferrer">http://www.codeproject.com/KB/WPF/WPF_Drag_And_Drop_Sample.aspx</a></p> <pre><code>private int GetCurrentIndex(GetPositionDelegate getPosition) { int index = -1; for (int i = 0; i &lt; clasesListView.Items.Count; ++i) { ListViewItem item = GetListViewItem(i); if (this.IsMouseOverTarget(item, getPosition)) { index = i; break; } } return index; } private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition) { Rect bounds = VisualTreeHelper.GetDescendantBounds(target); Point mousePos = getPosition((IInputElement)target); return bounds.Contains(mousePos); } delegate Point GetPositionDelegate(IInputElement element); ListViewItem GetListViewItem(int index) { if (clasesListView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return null; return clasesListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; } </code></pre>
<p>You want to use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.getitemat.aspx" rel="nofollow noreferrer">GetItemAt</a> function. You may also need to call the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoclient.aspx" rel="nofollow noreferrer">PointToClient</a> function before the GetItemAt since you need to work with <a href="http://msdn.microsoft.com/en-us/library/ms229598.aspx" rel="nofollow noreferrer">client coordinates</a>.</p>
47,336
<p>I have 2 tables event + event_artist</p> <h2>event</h2> <pre><code>eventId | eventName ------------------- 1 , gig1 2, gig2 </code></pre> <h2>event_artist</h2> <pre><code>eventId, artistName ------------------- 1, Led Zip 1, The Beatles </code></pre> <p>ie Led Zep and the Beatles are both playing @ Gig1</p> <p>I need to create the SQl to bind to a gridview ( you necessarily need to know about gridviews to answers this )</p> <p>The results that i want would look like this<br> eventId = 1, EventName = Gig1. ArtistLineup = Led Zep, The beatles</p> <p>So i need to create an alias ArtistLineup that would list all the artist. Via an inner select i think.</p> <p>Any thoughts on what this would look like. </p>
<p>Saw this in SQL Server Magazine- not great, and the total list will have an upper length limit, but:</p> <pre><code>drop table event go drop table event_artist go create table event (eventid int, eventname varchar(255)) go create table event_artist (eventid int, artistname varchar(255)) go insert into event values (1, 'gig1') go insert into event values (2, 'gig2') go insert into event_artist values (1, 'Led Zip') go insert into event_artist values (1, 'The Beatles') go drop function Event_Display go create function Event_Display (@EventID int) returns varchar(2000) as begin declare @artistList varchar(2000) set @artistList='' select @artistList=@artistList + ', ' + isnull(artistname,'') from event_artist where eventid=@EventID return substring(@artistList,3,2000) --eliminate initial comma end go select event.eventid, event.eventname, dbo.Event_Display(event.eventid) from event </code></pre> <pre> 1 gig1 Led Zip, The Beatles 2 gig2 </pre>
<p>SQL Server doesn't have anything built in to concatenate values in one statement like that. You could build the strings, but it has to be done one at a time.</p> <p>However, you can get around this by building your own <a href="https://stackoverflow.com/questions/43940/custom-aggregate-functions-in-ms-sql-server">custom aggregate function</a> (requires messy games with ActiveX objects in SQL Server 2000)</p>
37,799
<p>Is there an <strong>efficient</strong> way to create a file with a given size in Java?</p> <p>In C it can be done with <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> (see <a href="https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#245239">that answer</a>). </p> <p>Most people would just write <strong>n</strong> dummy bytes into the file, but there must be a faster way. I'm thinking of <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> and also of <a href="http://en.wikipedia.org/wiki/Sparse_file" rel="noreferrer">Sparse files</a>…</p>
<p>Create a new <a href="https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html" rel="noreferrer">RandomAccessFile</a> and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.</p> <p>The following program</p> <pre><code>import java.io.*; class Test { public static void main(String args[]) throws Exception { RandomAccessFile f = new RandomAccessFile("t", "rw"); f.setLength(1024 * 1024 * 1024); } } </code></pre> <p>on a Linux machine will allocate the space using the ftruncate(2)</p> <pre><code>6070 open("t", O_RDWR|O_CREAT, 0666) = 4 6070 fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0 6070 lseek(4, 0, SEEK_CUR) = 0 6070 ftruncate(4, 1073741824) = 0 </code></pre> <p>while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.</p> <pre><code>/2: open64("t", O_RDWR|O_CREAT, 0666) = 14 /2: fstat64(14, 0xFE4FF810) = 0 /2: llseek(14, 0, SEEK_CUR) = 0 /2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0 </code></pre> <p>In both cases this will result in the creation of a sparse file.</p>
<p>You can open the file for writing, seek to offset (n-1), and write a single byte. The OS will automatically extend the file to the desired number of bytes.</p>
30,422
<p>How do I inner join multiple columns from the same tables via Linq? </p> <p>For example: I already have this...</p> <pre><code>join c in db.table2 on table2.ID equals table1.ID </code></pre> <p>I need to add this...</p> <pre><code>join d in db.table2 on table2.Country equals table1.Country </code></pre>
<p>This is the only way I was able to get it to work (in c#).</p> <pre><code>var qry = from t1 in table1 join t2 in table2 on new {t1.ID,t1.Country} equals new {t2.ID,t2.Country} ... </code></pre>
<p>In VB:</p> <pre><code> dim qry = FROM t1 in table1 _ JOIN t2 in table2 on t2.ID equals t1.ID _ AND t2.Country equals t1.Country </code></pre>
44,945
<p>Linux provides the stime(2) call to set the system time. However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.</p> <p>Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals. However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.</p> <p>How do you ensure that the hardware clock gets updated when you set the system time?</p>
<p>Check out the rtc man-page for details, but if you are logged in as root, something like this: </p> <pre><code>#include &lt;linux/rtc.h&gt; #include &lt;sys/ioctl.h&gt; struct rtc_time { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; /* unused */ int tm_yday; /* unused */ int tm_isdst;/* unused */ }; int fd; struct rtc_time rt; /* set your values here */ fd = open("/dev/rtc", O_RDONLY); ioctl(fd, RTC_SET_TIME, &amp;rt); close(fd); </code></pre>
<p>If the text editor is different than kubuntu (kate is the default in editor), use your own with the <code>sudo</code> command in terminal.</p> <ol> <li>run terminal</li> <li>copy and paste this command <code>sudo kate /etc/default/rcS</code> press <kbd>Enter</kbd></li> <li>enter user password (your login password) press <kbd>Enter</kbd></li> <li>text editor will open on the desktop</li> <li>change the line <code>UTC=yes</code> to <code>UTC=no</code></li> <li>and click save (at top of text editor tab bar)</li> <li>reboot</li> </ol>
24,700
<p>While most operating systems and web browsers have very good support for <a href="http://en.wikipedia.org/wiki/Bi-directional_text" rel="nofollow noreferrer">bidirectional text</a> such as Hebrew and Arabic, most commercial and open-source software does not:</p> <ul> <li>Most text editors, besides the original notepad and the visual studio editor, does a very poor job. (And I tried dozens of them).</li> <li>I could not find any file compare tool doing a decent job - No even Beyond-Compare.</li> <li>Same thing for software and packages dealing with charting and reporting.</li> </ul> <p>Some questions I have:</p> <ul> <li>Do you share the same pain I do?</li> <li>Is the software you write bidirectional compliant? Do you have bug reports about it?</li> <li>Do you even know what are the issues involved? Do you test for them?</li> <li>Any suggestions on how to make the software world a better place for bidirectional language speakers?</li> </ul>
<blockquote> <p>Do you share the same pain I do?</p> </blockquote> <p>No. And that's probably the answer: most people have no idea how bidirectional languages work. I for example have some troubles working with that. Because I'm interested in that topic quite a bit I was reading pango sources a while back, and that's probably the second reason why the support sucks: it's damn hard to get right.</p> <p>I think the GNOME project has one of the best support for bidirectional user interfaces thanks to Pango (of course I can't verify that because I wouldn't be able to spot the problems).</p> <p>But because you said "open source": I think the globalization support in open source projects is generally outstanding. Linux sucks are pretty much everything, but internationalization is something they get right.</p> <p>gettext is still one of the few translation systems that has a (I know half baked but) working pluralization system.</p> <blockquote> <p>Is the software you write bidirectional compliant? Do you have bug reports about it?</p> </blockquote> <p>Probably not. I'm working on a web publishing software currently and that's one of the things I haven't tested at all so far :-(</p> <blockquote> <p>Do you even know what are the issues involved? Do you test for them?</p> </blockquote> <p>Bi-directional support is not no the direct roadmap. So no tests for them, where the issues are I know from the translation interface I wrote for Plurk.</p> <blockquote> <p>Any suggestions on how to make the software world a better place for bidirectional language speakers?</p> </blockquote> <p>For an open source project: ask guys to help you that know where the issues are. For closed source? Hire someone who knows.</p>
<p>A note regarding some of the answers - There are no "bidirectional languages". a language is either left to right or right to left (or top to bottom...). A Text or a String can be bidirectional if it contains both say Hebrew and English.</p> <p>Regarding the question, Firefox seem to work swell for me. Also MSWord and that's pretty much everything I use Hebrew in.</p>
15,083
<p>I want to extend an existing application I made to make it set mixer volume by wheel-scrolling over it's notification area icon.</p> <p>As far as I know, the notification area doesn't receive any WM_MOUSEWHEEL messages, but still I found an application that does exactly what I want to achieve (<a href="http://www.actualsolution.com/power_mixer/" rel="nofollow noreferrer">http://www.actualsolution.com/power_mixer</a>). Using WinspectorSpy I've noticed some strange messages the application's form receives: 0x000003d0 and 0x000003d1, but I found no references about them.</p> <p>Does anyone have any idea on how I could achieve the desired functionality?</p>
<p>If you want to capture mouse/keyboard events outside of your application you will need <a href="http://msdn.microsoft.com/en-us/library/ms997537.aspx" rel="nofollow noreferrer">Low-level Hooks</a>.</p> <p>A nice beginners article about installing a mouse hook in Delphi is <a href="http://delphi.about.com/od/windowsshellapi/a/mousehook.htm" rel="nofollow noreferrer">How to Hook the Mouse to Catch Events Outside of your application</a> on About.com written by Zarko Gajic.</p> <p>The user which starts your application will need administrative rights to install a hook.</p> <p>After you capture the message you should determine if it's above your icon in the notification bar (which can be difficult because there is no exact api to get your position on the bar) and than process the scroll event.</p>
<p>Not sure if this will solve the problem but it might be worth a try as a starting point. You could create a top level transparent window that you then position over the top of the taskbar icon. That top level window will receive mouse notifications when the mouse is over it. You can then process them as required. How to find the screen location of the taskbar icon is something I do not know and so that might be an issue.</p>
11,577
<p>I'd like to output html controls using xslt, but I need to be able to name the controls so that I can get at them when the form posts back.</p> <p>I'd like to be able to name the radio button <code>"action_" + _case_id</code>.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="data.xsl"?&gt; &lt;NewDataSet&gt; &lt;Cases&gt; &lt;Case&gt; &lt;case_id&gt;30&lt;/case_id&gt; &lt;/Case&gt; &lt;Cases&gt; &lt;/NewDataSet&gt; &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="/"&gt; &lt;div class="your_action"&gt; Your action:&lt;br /&gt; &lt;input type="radio" name="?" value="No" checked ="true"/&gt; nothing to report&lt;br /&gt; &lt;input type="radio" name="?" value="Yes" /&gt; memo to follow &lt;/div&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
<p>Use: <strong><pre> &lt;input type="radio" name="{concat('action_', /*/*/*/case_id)}" value="No" checked ="true"/> </pre></strong></p> <p>In case your xml document changes it may be necessary to substitute the "*" chars above with more detailed location steps.</p>
<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="data.xsl"?&gt; &lt;NewDataSet&gt; &lt;Cases&gt; &lt;Case&gt; &lt;case_id&gt;30&lt;/case_id&gt; &lt;/Case&gt; &lt;Cases&gt; &lt;/NewDataSet&gt; &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="/"&gt; &lt;xsl:variable name="actionid"&gt;action_&lt;xsl:value-of select="Cases/Case/case_id"/&gt;&lt;/xsl:variable&gt; &lt;div class="your_action"&gt; Your action:&lt;br /&gt; &lt;input type="radio" name="{actionid}" value="No" checked ="true"/&gt; nothing to report&lt;br /&gt; &lt;input type="radio" name="{actionid}" value="Yes" /&gt; memo to follow &lt;/div&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>NOTE: Not tested. You probably want add a matcher specifically for the Case node not just matching on the root node.</p>
43,750
<p>I want to retrieve a list of the files that has been added or deleted from our Subversion repository over, for example, the last month.</p> <p>I'd prefer to have the file names, and not just a count.</p> <p>Is this possible from the Subversion command line, or would I need to use a script to trawl the log?</p>
<p>I don't think you can do it with just the command-line tools, but outputting it with an XML format and doing some grepping or filtering would probably give you what you want.</p> <p>Try this for a start:</p> <pre><code>svn log -v --xml | grep 'action="[A|D]"' </code></pre>
<p>I use a mishmash of the SVN log command and grep to get just the deletions. e.g.</p> <pre><code>% svn log -v -r \{2013-09-01\}:\{2013-10-31\}|grep ' D' </code></pre> <p>Will list the files deleted from the current branch in September-October, 2013 (Or... anything else with "space, space, dee" in it)</p>
34,903
<p>I am about to start a new project and would like to document its development in a very simple blog.</p> <p>My requirements are:</p> <ul> <li>self-hosted on my Gentoo-based LAMP stack (that seems to rule out blogger)</li> <li>Integration in a django based website (as in www.myproject.com/about, www.myproject.com/blog etc rather than www.myproject.com and a totally different site at blog.myproject.com)</li> <li>very little or no learning curve <i>that's specific to the blog engine</i> (don't want to learn an API just to blog, but having to get deeper into Django to be able to roll my own would be OK) According to the answers so far, there is a chance that this excludes Wordpress</li> </ul> <p>Should I</p> <p>a) install blog engine X (please specify X)</p> <p>b) use django to hand-roll a way to post new entries and a page on my website to display the posts in descending chronological order</p>
<p><strong>If you're the perfectionist kind, roll your own</strong>.</p> <ul> <li>It isn't that hard</li> <li>You learn something useful</li> <li>You'll get <em>exactly</em> what you want and need</li> </ul> <p>Be warned that you may run into a quagmire fighting comment spam, fixing security holes, etc. But it'll probably be a fun project.</p> <p><strong>If you are the practical type and ready to face some integration pain</strong>, use an existing engine like <a href="http://vss.73rus.com/wadcomblog/" rel="noreferrer">WadcomBlog</a> (Python) or <a href="http://pyblosxom.sourceforge.net/" rel="noreferrer">PyBlosxom</a>, or something completely different like MovableType or WordPress.</p> <p>Here's a simple <a href="http://www.rossp.org/blog/2006/jun/08/django-blog-redux/" rel="noreferrer">Django blog example</a> to get you started.</p> <p>Some pros and cons of rolling your blog engine <a href="http://haacked.com/archive/2006/10/06/Rolling_Your_Own_Blog_Engine.aspx" rel="noreferrer">this article</a> by Phil Haack.</p> <p>Jeff Croft apparently <a href="http://jeffcroft.com/blog/2006/may/02/django-non-programmers/" rel="noreferrer">rolled his own</a> as well.</p>
<p>I Haven't tried it myself yet (other than the demo), but I've bookmarked <a href="http://chyrp.net" rel="nofollow noreferrer">Chyrp</a> so that if I ever need to set up a quick &amp; simple blog (kind of like you're describing) I could try this. So check it out, might be a good option for you.</p>
7,435
<p>I've got a console application that compiles and executes fine with Visual C++ 6.0, except that it will then only get as far as telling me about missing command line parameters. There doesn't seem to be anywhere obvious to enter these. How do I run or debug it with command line parameters?</p>
<p>I assume you're talking about setting the command line parameters for running in the IDE.</p> <p>Open the Project/Settings property page and go to the Debug tab.</p> <p>There's a "Program arguments" field you can put them into.</p>
<p>In VS2010: Right click the project. Select Properties. Select Debug tab. Start Options -> Command line arguments: Enter the arguments here.</p>
34,872
<p>Ok let me be honest, I haven't written more than 10 unit tests in my life probably.</p> <p>I am embarking on a new project, and being the sole programmer means <b>I should be scared ... very scared</b>. </p> <p>The idea that I can <b>pseudo guarantee</b> that my software works brings about a sense of joy.</p> <p>Sure I will miss a ton of cases where I should have tested, but that's where I will learn as time goes on.</p> <p><b>Unit testing will help me sleep better at night</b>, which is better for my health.</p> <p><b>My code will fail, but at least I will have a better idea when it will</b>.</p> <p>How has unit testing made your life better (or has it?), despite the rest of your team <b>not jumping on the bandwagon</b>?</p>
<p>The far biggest value that unit test have on my project is <strong>confidence</strong>. With that confidence it's much easier to add new features that weren't planned at the beginning and to tear code apart to change something or turn this around.</p> <p><strong>With test I know</strong> I (or anyone else!) haven't broke something that already worked. </p> <p><strong>Without test you are brave</strong> (or stupid) when you make big changes and deploy them in production in the next minute.</p>
<p>I'm currently in the process of trying to jump on the bandwagon. Work mates are already doing it before they've written a line of functional code. I'm still writing a full program before I've even run it through the main, let alone unit test it :/</p> <p>I'll get there in the end I'm sure. But at the moment, I am of ill health through spending 90% of my life debugging :(</p>
44,348
<p>I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;script type="text/javascript" src="scripts/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/scripts.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; welcome &lt;form id="SubmitForm" action="/" method="POST"&gt; &lt;input type="file" name="vsprojFiles" /&gt; &lt;br/&gt; &lt;input type="submit" id="SubmitButton"/&gt; &lt;/form&gt; &lt;div id="Testing"&gt; {{thebest}} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's the script in scripts.js:</p> <pre><code>$(function() { $("#SubmitForm").click(submitMe); }); var submitMe = function(){ //alert('no way'); var f = $('#SubmitForm'); var action = f.attr("action"); var serializedForm = f.serialize(); $.ajax( { type: 'post', data: serializedForm, url: form_action, success: function( result ) { $('#SubmitForm').after( "&lt;div&gt;&lt;tt&gt;" + result + "&lt;/tt&gt;&lt;/div&gt;" ); } } ); }; </code></pre> <p>And here's my controller code:</p> <pre><code>from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api.urlfetch_errors import * import cgi import wsgiref.handlers import os import sys import re import urllib from django.utils import simplejson class MainPage(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'Index.html') template_values={'thebest': 'thebest'} tmplRender =template.render(path, template_values) self.response.out.write(tmplRender) pass def Post(self): print &gt;&gt;sys.__stderr__,'me posting' result = 'grsgres' self.response.out.write(simplejson.dumps(result)) </code></pre> <p>As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.</p> <p>Now I want to display the content of the 'result' variable right after the form, how can I do it?</p>
<p>Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:</p> <pre><code>//... success: function( result ) { console.log( result ); $('#SubmitForm').after( "&lt;div&gt;&lt;tt&gt;" + // ... </code></pre> <p>You can also use the Net panel of Firebug to see what is being passed back and forth.</p> <p>Also, what does "simplejson.dumps(result)" result in?</p>
<p>here is an example of my success function </p> <pre><code>success: function(json){ $('#gallons_cont').html(json['gallons']); $('#area_cont').html(json['area']); $('#usage_cont').html(json['usage']) $('#results_json').show('slow'); }, </code></pre> <p>please note that you do have to debug using firebug or something similar as there might be some issue serializing which will throw and error but will not be vieweable unless you use something like firebug or implement .ajax error</p>
25,646
<p>Looking for a way to read the unique ID / serial# of a USB thumb drive; please note that<br> - I am looking for the value of the manufacturer, not the one Windows allocates for it.<br> - I need to support multiple OS (Windows, Unix, Mac), thus needs to be a Java solution</p> <p>The idea is to be able to distinguish between different USB thumb drives.</p>
<p>I've never tried using it (it's been on my todo list for a good few months now), but there is the "marge" project on java.net:</p> <p><a href="http://marge.java.net/" rel="nofollow noreferrer">http://marge.java.net/</a></p> <p>This should let you connect to bluetooth devices (although I don't think it is 100% feature complete, there is demo code on there), and then the ClientDevice class has a "getBluetoothAddress" method which I <em>believe</em> should be unique to that device</p> <p><a href="http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html" rel="nofollow noreferrer">http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html</a></p> <p>As I say though, I've never tried it...</p>
<p>I have never investigated this thoroughly, but from memory the <a href="http://users.frii.com/jarvi/rxtx/" rel="nofollow noreferrer">RXTX</a> library implementation of the javax.comm packages are supposedly very good and now have USB support.</p>
9,896
<p>How to use batch file to check if an application still running or not? If the application still running, this process will loop again and again. Else, there will be error message.</p> <p>Thank you very much</p>
<p>in windows you kan use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx" rel="noreferrer">pstools</a> pslist to check if a process name is running by using a .cmd script like the following. Pslist will return ERRORLEVEL 0 if the process is running, 1 if not.</p> <pre><code>@echo off CommandYouWillRun.exe rem waiting for the process to start :startcmd sleep 1 c:\path\to\pslist.exe CommandYouWillRun &gt; NUL IF ERRORLEVEL 1 goto startcmd rem the process has now started :waitforcmd sleep 1 c:\path\to\pslist.exe CommandYouWillRun &gt; NUL IF ERRORLEVEL 1 got finished goto waitforcmd :finished echo "This is an error message" </code></pre>
<p>Perhaps you mean tasklist? You can run that from the command line to get all running processes in windows...for the rest of what you are asking I think you will need to be more specific. </p>
36,392
<p>I have noticed that some browsers (in particular, Firefox and <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="noreferrer">Opera</a>) are very zealous in using cached copies of <strong>.css</strong> and <strong>.js</strong> files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.</p> <p>What is the most elegant way of forcing the user's browser to reload the file when it has changed?</p> <p>Ideally, the solution would not force the browser to reload the file on every visit to the page.</p> <hr/> <p>I have found <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921">John Millikin's</a> and <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901">da5id's</a> suggestion to be useful. It turns out there is a term for this: <strong>auto-versioning</strong>.</p> <p>I have posted a new answer below which is a combination of my original solution and John's suggestion.</p> <p>Another idea that was suggested by <strong>SCdF</strong> would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143">submitted by <em>pi.</em></a>.)</p> <p>However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)</p>
<p>This solution is written in PHP, but it should be easily adapted to other languages.</p> <p>The original <code>.htaccess</code> regex can cause problems with files like <code>json-1.3.js</code>. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)</p> <p>First, we use the following rewrite rule in .htaccess:</p> <pre><code>RewriteEngine on RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L] </code></pre> <p>Now, we write the following PHP function:</p> <pre class="lang-php prettyprint-override"><code>/** * Given a file, i.e. /css/base.css, replaces it with a string containing the * file's mtime, i.e. /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path (i.e. * starting with slash). */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', &quot;.$mtime.\$1&quot;, $file); } </code></pre> <p>Now, wherever you include your CSS, change it from this:</p> <pre class="lang-html prettyprint-override"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;/css/base.css&quot; type=&quot;text/css&quot; /&gt; </code></pre> <p>To this:</p> <pre><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;&lt;?php echo auto_version('/css/base.css'); ?&gt;&quot; type=&quot;text/css&quot; /&gt; </code></pre> <p>This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.</p> <p>This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.</p>
<p>Changing the filename will work. But that's not usually the simplest solution.</p> <p>An HTTP cache-control header of 'no-cache' doesn't always work, as you've noticed. The HTTP 1.1 spec allows wiggle-room for user-agents to decide whether or not to request a new copy. (It's non-intuitive if you just look at the names of the directives. Go read the actual <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" rel="nofollow noreferrer">HTTP 1.1 spec for cache</a>... it makes a little more sense in context.)</p> <p>In a nutshell, if you want iron-tight cache-control use</p> <pre><code>Cache-Control: no-cache, no-store, must-revalidate </code></pre> <p>in your response headers.</p>
14,468
<p>I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following </p> <p>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <p>that points to here . It's in site.master of asp.net mvc </p> <pre><code>&lt;div id="logindisplay"&gt; &lt;% Html.RenderPartial("LoginUserControl"); %&gt; &lt;/div&gt; </code></pre> <p>usually to avoid this error, we give </p> <pre><code>&lt;pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" &gt; </code></pre> <p>but, it doesn't work for me.</p>
<p>Before reading further, please exclude the following preconditions:</p> <ol> <li>You aren't using a web farm.</li> <li>It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.</li> <li>It appears if you have a large page which loads slowly for any reason.</li> </ol> <p>If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.</p> <p>When this happens, if you just try setting the <strong>page property "EnableViewStateMac" to false</strong>, it does not solve the problem, it just changes the error message in same navigation behavior:</p> <blockquote> <p>The state information is invalid for this page and might be corrupted.</p> </blockquote> <p>This exception appears because Controls using DataKeyNames <strong>require Viewstate to be encrypted</strong>. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the &lt;form&gt; tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.</p> <p>And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered &lt;form&gt; tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.</p> <p>The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.</p> <p><strong>Workaround</strong></p> <p>Set <strong>enableEventValidation to false and viewStateEncryptionMode to Neve</strong>r as follows:</p> <pre><code>&lt;pages enableeventvalidation="false" viewstateencryptionmode="Never"&gt; </code></pre> <p>This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.</p> <p>For more information and other workaround see this <a href="http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx" rel="nofollow noreferrer">blog entry</a>.</p>
<p>This happened to me just a few minutes ago. Luckily, I found <a href="http://www.dotneat.net/2008/12/13/ASPNETMVCValidationOfViewstateMACFailedError.aspx" rel="nofollow noreferrer">this blog post</a> on the subject. The upshot (for me, at least), was that I had two forms, one on the page and one on the control. </p> <p>I didn't need the one on the page, so I removed it, and the error went away.</p>
26,431
<p>I'm trying to write some C# code that calls a method from an unmanaged DLL. The prototype for the function in the dll is:</p> <pre><code>extern "C" __declspec(dllexport) char *foo(void); </code></pre> <p>In C#, I first used:</p> <pre><code>[DllImport(_dllLocation)] public static extern string foo(); </code></pre> <p>It seems to work on the surface, but I'm getting memory corruption errors during runtime. I think I'm pointing to memory that happens to be correct, but has already been freed.</p> <p>I tried using a PInvoke code gen utility called "P/Invoke Interop Assistant". It gave me the output:</p> <pre><code>[System.Runtime.InteropServices.DLLImportAttribute(_dllLocation, EntryPoint = "foo")] public static extern System.IntPtr foo(); </code></pre> <p>Is this correct? If so, how do I convert this IntPtr to a string in C#?</p>
<p>You must return this as an IntPtr. Returning a System.String type from a PInvoke function requires great care. The CLR must transfer the memory from the native representation into the managed one. This is an easy and predictable operation.</p> <p>The problem though comes with what to do with the native memory that was returned from <code>foo()</code>. The CLR assumes the following two items about a PInvoke function which directly returns the string type</p> <ol> <li>The native memory needs to be freed</li> <li>The native memory was allocated with CoTaskMemAlloc</li> </ol> <p>Therefore it will marshal the string and then call <code>CoTaskMemFree(...)</code> on the native memory blob. Unless you actually allocated this memory with CoTaskMemAlloc this will at best cause a crash in your application.</p> <p>In order to get the correct semantics here you must return an IntPtr directly. Then use Marshal.PtrToString* in order to get to a managed String value. You may still need to free the native memory but that will dependent upon the implementation of foo.</p>
<p>Current answers are not complete so I just wanted to post full solution in one place. Returning IntPtr instead of string doesn't solve any problem at all as you still have to free native memory allocated in C script. The best possible solution is to allocate bytes buffer on managed side and pass the memory to C script that will write string into that buffer not allocating memory at all.</p> <p>Returning a string from C is exactly like this:</p> <pre><code>//extern &quot;C&quot; __declspec(dllexport) uint32_t foo(/*[out]*/ char* lpBuffer, /*[in]*/ uint32_t uSize) uint32_t __stdcall foo(/*[out]*/ char* lpBuffer, /*[in]*/ uint32_t uSize) { const char szReturnString[] = &quot;Hello World&quot;; const uint32_t uiStringLength = strlen(szReturnString); if (uSize &gt;= (uiStringLength + 1)) { strcpy(lpBuffer, szReturnString); // Return the number of characters copied. return uiStringLength; } else { // Return the required size // (including the terminating NULL character). return uiStringLength + 1; } } </code></pre> <p>C# code:</p> <pre><code>[DllImport(_dllLocation, CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Ansi)] private static extern uint foo(IntPtr lpBuffer, uint uiSize); private static string foo() { // First allocate a buffer of 1 byte. IntPtr lpBuffer = Marshal.AllocHGlobal(1); // Call the API. If the size of the buffer // is insufficient, the return value in // uiRequiredSize will indicate the required // size. uint uiRequiredSize = foo(lpBuffer, 1); if (uiRequiredSize &gt; 1) { // The buffer pointed to by lpBuffer needs to be of a // greater size than the current capacity. // This required size is the returned value in &quot;uiRequiredSize&quot; // (including the terminating NULL character). lpBuffer = Marshal.ReAllocHGlobal(lpBuffer, (IntPtr)uiRequiredSize); // Call the API again. foo(lpBuffer, uiRequiredSize); } // Convert the characters inside the buffer // into a managed string. string str = Marshal.PtrToStringAnsi(lpBuffer); // Free the buffer. Marshal.FreeHGlobal(lpBuffer); lpBuffer = IntPtr.Zero; // Display the string. Console.WriteLine(&quot;GetString return string : [&quot; + str + &quot;]&quot;); return str; } </code></pre> <p>There is simpler way to manage memory allocation/deallocation on C# side using StringBuilder:</p> <pre><code>[DllImport(&quot;TestDLL.dll&quot;, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] private static extern uint foo(StringBuilder lpBuffer, UInt32 uiSize); private static string foo() { StringBuilder sbBuffer = new StringBuilder(1); uint uiRequiredSize = foo(sbBuffer, (uint)sbBuffer.Capacity); if (uiRequiredSize &gt; sbBuffer.Capacity) { // sbBuffer needs to be of a greater size than current capacity. // This required size is the returned value in &quot;uiRequiredSize&quot; // (including the terminating NULL character). sbBuffer.Capacity = (int)uiRequiredSize; // Call the API again. foo(sbBuffer, (uint)sbBuffer.Capacity); } return sbBuffer.ToString(); } </code></pre> <p>There's a <a href="https://limbioliong.wordpress.com/2011/11/01/using-the-stringbuilder-in-unmanaged-api-calls/" rel="nofollow noreferrer">good topic</a> explaining different ways of returning string from C/C++ code.</p>
48,339
<p>Are there SLA printable resins that can be printed with optical clarity and whose index of refraction make them potentially useful for optical applications? I would assume the surface may need polishing, and that's okay - I'm just asking whether the materials and process are otherwise suitable.</p>
<p>No, at least not at a consumer level. The layering created by the printing process would create imperfections, and clear resin frequently yellows if not cured properly and then protected form strong UV light. Resins that do not yellow tend to have a blue cast to them.</p> <p>You would be better off using a commercial grade casting resin and a pressure chamber to remove bubbles. Even then it would be inferior to silicates for even basic lenses.</p>
<h1>Clear Resin isn't clear everywhere</h1> <p>Any light-curing resin has a specific bandwidth to which it is totally opaque just to be able to cure. This is typically a blue color, but at this and adjacent wavelength, the lens will not allow light to pass through it, no matter if you can manage to get imperfections down.</p> <h1>Resins change color</h1> <p>Then there is the problem of resins changing coloration. Most cast resins become yellow, and some go blue, but in either case, they do absorb some spectrum to appear as this color.</p>
2,153
<p>Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.</p> <p>I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.</p> <p>The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?</p>
<p>A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).</p> <pre><code>package { public class Singleton { private static var _instance:Singleton; public function Singleton(enforcer:SingletonEnforcer) { if( !enforcer) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function get instance():Singleton { if(!Singleton._instance) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{} </code></pre>
<p>The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:</p> <pre><code>public class Foo { private static var instance : Foo; public Foo() { if( instance != null ) { throw new Exception ("Singleton constructor called"); } instance = this; } public static getInstance() : Foo { if( instance == null ) { instance = new Foo(); } return instance; } } </code></pre>
15,915
<p>I have looked in vain for a good example or starting point to write a java based facebook application... I was hoping that someone here would know of one. As well, I hear that facebook will no longer support their java API is this true and if yes does that mean that we should no longer use java to write facebook apps??</p>
<p>Facebook stopped supporting the official Java API on 5 May 2008 according to their <a href="http://developers.facebook.com/blog/post/106" rel="nofollow noreferrer">developer wiki</a>.</p> <p>In no way does that mean you shouldn't use Java any more to write FB apps. There are several alternative Java approaches outlined on the wiki.</p> <p>You might also want to check <a href="http://code.google.com/p/facebook-java-webapp/" rel="nofollow noreferrer">this project</a> out; however, it only came out a few days ago so YMMV.</p>
<p>You might want to try <a href="http://www.springsource.org/spring-social" rel="nofollow">Spring Social</a>. It might be limited in terms of Facebook features, but lets you also connect to Twitter, LinkedIn, TripIt, GitHub, and Gowalla. </p> <p>The other side of things is that as Facebook adds features some of the old API's might break, so using a simpler pure FB api (that you can update when things don't work) might be a good idea.</p>
8,785
<p>I am creating a form within InfoPath which is to be integrated into a SharePoint 2007 Portal. Within this form there will be a textfield into which a user can enter the Name of a Person. </p> <p>How can I validate whether this Person exists or not?</p> <p>Instead of validating the user, is there a way to fill a dropdown List with <em>all</em> usernames of the portal? (which of cause would be users from the Active Directory)</p>
<p>I haven't done this specifically, so there may be a better way, but I've been pulling a lot of data out of SharePoint and into an InfoPath Form (deployed to a SharePoint forms library and accessible through SharePoint Forms Service with MOSS Enterprise) and also going the other way using the SharePoint web services - very quick to use, and the person web service is right there.</p>
<p>When doing something similar in an ASP.NET application, I've used the Sharepoint search and <a href="http://www.mobiusdevelopment.com/dev/Blog.asp?ArticleID=3235955046032961096" rel="nofollow noreferrer">searched the "People" Scope</a> for the specific user. You can also search across profile information so you can pull back everyone with a certain Job Title, or in a specific Department.</p>
35,501
<p>When I am stuck with a problem:</p> <ul> <li>I search Google for code snippets.</li> <li>I look at isolating the problem, so that I can better explain it to others in order to get answers.</li> </ul> <p>What search techniques do you use to find the solution to your problem?</p> <p>I started asking questions in Stack Overflow.</p> <p>What other techniques or methods do you follow, to fix the problem more quickly?</p>
<p>Go and do something else. No, really. I've found that putting the problem away in the back of my mind helps. I can't count the number of times I thought of a great solution to something I've been working on when I was working on something else, or watching TV, or eating. It seems your brain is still working on the problem in the background.</p> <p>If that fails to solve your problem, try talking to someone. You'd be surprised how often others can give solutions to your problem that are so simple you'd facepalm.</p>
<p>Go to the toilet. You move, so your brain gets oxygen. You relax, so you focus on other things.</p> <p>Peeing for innovation! :)</p>
42,591
<p>The pages in question contain a lot of javascript and CSS. How well are these supported by mobile platforms generally?</p> <p>Is there a browser emulator (or equivalent tool) to assist testing?</p>
<p><a href="http://www.opera.com" rel="nofollow noreferrer">Opera</a> has an option to view pages as through a mobile device. I've found it useful in the past.</p>
<p>You can install Opera Mini on an emulator like the Java WTK and test mobile rendering on a PC. One drawback is that Opera Mini still works through a proxy, so debugging local files/sites won't work - you have to upload your site to a world-accessible server.</p> <p>Just google it.</p>
12,581
<p>Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just <code>kill -9</code> to guarantee that a process will die.</p> <p>This also could be used for writing batch scripts and writing batch scripts is programming.</p> <p><strong>Is there some</strong> program or <strong>command that comes with Windows that will always kill a process?</strong> A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time.</p>
<p>"End Process" on the Processes-Tab calls <code>TerminateProcess</code> which is the most ultimate way Windows knows to kill a process.</p> <p>If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.</p> <p>Have a look at this blog-entry from wayback when: <a href="http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx" rel="noreferrer">http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx</a></p> <p>Unix based systems like Linux also have that problem where processes could survive a <code>kill -9</code> if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state <code>D</code>) at which point the processes sleep so well that they can't process incoming signals (which is what <code>kill</code> does - sending signals).</p> <p>Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (<code>vfork</code> without <code>exec</code>) can end up sleeping in <code>D</code> forever.</p>
<p>When ntsd access is denied, try:</p> <p>ZeroWave was designed to be a simple tool that will provide a multilevel termination of any kind of process.</p> <p>ZeroWave is also a easy-to-use program due to its simple installation and its very friendly graphical interface.</p> <p>ZeroWave has three termination modes and with the "INSANE" mode can terminate any kind of process that can run on Windows.</p> <p>It seems that ZeroWave can't kill avp.exe</p>
7,262
<p>I've been searching around, and I haven't found how I would do this from C#.</p> <p>I was wanting to make it so I could tell Google Chrome to go <strong>Forward</strong>, <strong>Back</strong>, <strong>Open New Tab</strong>, <strong>Close Tab</strong>, <strong>Open New Window</strong>, and <strong>Close Window</strong> from my C# application.</p> <p>I did something similar with WinAmp using</p> <pre><code>[DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything. </p> <p>So could someone show me how I would send those 6 commands to Chrome from C#? thanks</p> <p>EDIT: Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own.</p> <p>First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works.</p> <p>I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing:</p> <pre><code> [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam); [DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch); [DllImport("user32", EntryPoint = "FindWindowExA")] private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2); [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>Then the code I found to use this used these constants for the messages I send.</p> <pre><code> const int WM_COMMAND = 0x111; const int WA_NOTHING = 0; const int WA_PREVTRACK = 40044; const int WA_PLAY = 40045; const int WA_PAUSE = 40046; const int WA_STOP = 40047; const int WA_NEXTTRACK = 40048; const int WA_VOLUMEUP = 40058; const int WA_VOLUMEDOWN = 40059; const int WINAMP_FFWD5S = 40060; const int WINAMP_REW5S = 40061; </code></pre> <p>I would get the <em>hwnd</em> (the program to send the message to) by:</p> <pre><code>IntPtr hwnd = FindWindow(m_windowName, null); </code></pre> <p>then I would send a message to that program:</p> <pre><code>SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING); </code></pre> <p>I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for:</p> <p><strong>m_windowName</strong> and <strong>WM_COMMAND</strong></p> <p>and then, the values for the different commands, <strong>forward</strong>, <strong>back</strong>, <strong>new tab</strong>, <strong>close tab</strong>, <strong>new window</strong>, <strong>close window</strong>?</p>
<p>Start your research at <a href="http://dev.chromium.org/developers" rel="noreferrer">http://dev.chromium.org/developers</a></p> <hr> <p><strong>EDIT</strong>: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages.</p> <p>You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning <em>only</em> to Winamp. </p> <p>What you have to do in the first step is to find out <em>if</em> Chromium supports some kind of remote controlling and what those mechanisms are.</p>
<p>Ok, here's what I've got so far... I kinda know what I need to do, but it's just a matter of doing it now...</p> <p>Here's the window from Spy++, I locked onto the <strong><em>Chrome_RenderWidgetHostHWND</em></strong> and clicked the Back button on my keyboard. Here's what I got: <img src="https://i17.photobucket.com/albums/b92/xahrepap/MessagesToChrome.jpg" alt="alt text"></p> <p>So here's my assumptions, and I've been playing with this forever now, I just can't figure out the <em>values</em>.</p> <pre><code>IntPtr hWnd = FindWindow("Chrome_RenderWidgetHostHWND", null); SendMessage(hWnd, WM_KEYDOWN, VK_BROWSER_BACK, 0); SendMessage(hWnd, WM_KEYUP, VK_BROWSER_BACK, 0); </code></pre> <p>Now, I just don't know what I should make the WM_KEYDOWN/UP values or the VK_BROWSER_BACK/FORWARD values... I tried this:</p> <pre><code>const int WM_KEYDOWN = 0x100; const int WM_KEYUP = 0x101; const int VK_BROWSER_BACK = 0x6A; const int VK_BROWSER_FORWARD = 0x69; </code></pre> <p>The latter two values I got from the image I just showed, the ScanCodes for those two keys. I don't know if I did it right though. The former two values I got after searching google for the WM_KEYDOWN value, and someone used &amp;H100 and &amp;H101 for the two values. I've tried several other random ideas I've seen floating around. I just can't figure this out.</p> <p>Oh, and here's the SendMessage method </p> <pre><code> [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, uint lParam); </code></pre>
17,818
<p>I know there are several plugins that do asynchronous processing. Which one is the best one and why?</p> <p>The ones I know about are:</p> <ul> <li><a href="http://backgroundrb.rubyforge.org/" rel="noreferrer">BackgrounDRb</a></li> </ul>
<p>starling and workling seem pretty interesting (see the <a href="http://railscasts.com/episodes/128-starling-and-workling" rel="noreferrer">screencast</a>) if you might have several such process, and you want to queue them.</p> <p>you might also be interested by the <a href="http://railscasts.com/episodes/127-rake-in-background" rel="noreferrer">previous screencast</a> that use rake for background process, and by the future one that will probably be about another solution to the same question.</p>
<p>BackgrounDRb is not threaded, its completely process based. It only has a feature of thread pools which user can use, if he wants to handle IO bound tasks concurrently.</p> <p>Try 1.1 release and let me (on my blog) or on mailing list know about any issues.</p>
15,135
<p>I have a .Net app that will allow the users to attach files to a SQL Server 2005 database. I want to limit the filesize to 10MB, so from what I can tell, I have to declare the datatype varbinary(max), since the max size I can actually specify is 8000 bytes. But the ~2GB filesize varbinary(max) allows seems like overkill. Is there a way for me to limit it at 10MB in the database, or do I just need to check that they're not trying to attach something larger on the frontend.</p>
<p>Using varbinary(max) is totally okay, since it is varbinary, you will only use as much place as the content requires, up to 2 gigs. However, you could add a CHECK CONSTRAINT in the db, checking the datalength() of the upload. I would rather just check the upload in the application though. </p>
<p>I think you need to make it in the frontend. You can limit the HTTP request size in the web.config like that:</p> <pre><code>&lt;/configuration&gt; &lt;/system.web&gt; &lt;httpRuntime maxRequestLength="60000"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>You may also need to explicitly check the posted file size when the user try to upload a file more than the specified threshold.</p>
30,164
<p>I need to determine the current year in Java as an integer. I could just use <code>java.util.Date()</code>, but it is deprecated.</p>
<p>For Java 8 onwards:</p> <pre><code>int year = Year.now().getValue(); </code></pre> <p>For older version of Java:</p> <pre><code>int year = Calendar.getInstance().get(Calendar.YEAR); </code></pre>
<p>I use special functions in my library to work with days/month/year ints -</p> <pre><code>int[] int_dmy( long timestamp ) // remember month is [0..11] !!! { Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp ); return new int[] { cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR ) }; }; int[] int_dmy( Date d ) { ... } </code></pre>
16,506
<p><a href="http://hessian.caucho.com" rel="nofollow noreferrer">Hessian</a> is a custom binary serialization protocol, (which is open-source - I think), that forms the basis for a binary cross platform remoting framework. I'd like to know if anyone here has used it, and if so, what sort of performance can we expect from a solution that bridges a Java app on one side with a C# app on the other. (Let us consider that we are serializing simple classes, and may be arrays, lists, dictionaries of simple classes.)</p>
<p>Have you looked at the HessianC# project (<a href="http://www.hessiancsharp.org/" rel="nofollow noreferrer">http://www.hessiancsharp.org/</a>)?</p>
<p>This is the sort of problem that web services were designed to solve. Although no longer simple, the SOAP format allows you to serialize objects to an XML representation on a Java/C# application, transmit them across the wire and deserialize them in the corresponding Java/C# application (Java/C# may be replaced with virtually any language that can translate an XML document). Although "serialize" is used here, it is also common for this process to be referred as "marshalling".</p> <p>However, moving away from SOAP for web services is currently being considered by many. Find out more about web services from Wikipedia: <a href="http://en.wikipedia.org/wiki/Web_services" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Web_services</a></p>
8,845
<p>Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:</p> <pre><code>void divide(int dividend, int divisor, int&amp; quotient, int&amp; remainder); </code></pre> <p>A variation is to return one value and pass the other through a reference parameter:</p> <pre><code>int divide(int dividend, int divisor, int&amp; remainder); </code></pre> <p>Another way would be to declare a struct to contain all of the results and return that:</p> <pre><code>struct divide_result { int quotient; int remainder; }; divide_result divide(int dividend, int divisor); </code></pre> <p>Is one of these ways generally preferred, or are there other suggestions?</p> <p>Edit: In the real-world code, there may be more than two results. They may also be of different types.</p>
<p>For returning two values I use a <code>std::pair</code> (usually typedef'd). You should look at <code>boost::tuple</code> (in C++11 and newer, there's <code>std::tuple</code>) for more than two return results.</p> <p>With introduction of structured binding in C++ 17, returning <code>std::tuple</code> should probably become accepted standard.</p>
<p>Quick answer:</p> <pre><code>#include &lt;iostream&gt; using namespace std; // different values of [operate] can return different number. int yourFunction(int a, int b, int operate) { a = 1; b = 2; if (operate== 1) { return a; } else { return b; } } int main() { int a, b; a = yourFunction(a, b, 1); // get return 1 b = yourFunction(a, b, 2); // get return 2 return 0; } </code></pre>
41,540
<p>I have a simple program print barcodes. The label format is in a preloaded form. The value the barcode is passed by a parameter as follow.</p> <pre><code>^XA ^XFR:FORM.ZPL ^FN999^FDH654321+Y0001+OABC+^FS ^PQ2,0,1,N </code></pre> <p>And it print two barcodes</p> <pre><code>H654321+Y0001+OABC+ H654321+Y0001+OABC+ </code></pre> <p>What I want is the middle part as a serial number, and it will print barcodes like this</p> <pre><code>H654321+Y0001+OABC+ H654321+Y0002+OABC+ </code></pre> <p>I have tried the ^SN and ^SF</p> <pre><code>^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1%%%%%%^FS </code></pre> <p>But it was not success, two copies are the same. How can I do it in ZPL-II?</p>
<p>Ripped from a ZPL II manual:</p> <blockquote> <p>^AF^SN 0001, 1, Y^FS</p> <p>Define serialized field, starting value of 1, increment by 1, insert leading zeros</p> </blockquote> <p>I have no way of knowing if this will help you though, since I have only experience with EPL2 label definitions.</p>
<p>You should increment consider the symbol <code>%</code> as Zero, like this</p> <p><code>^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1%%%%%%^FS %%%%%%= 1000000</code>.</p> <p>Then <code>^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1000000^FS</code></p>
44,639
<p>For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:</p> <pre><code>find -type f | while read file do if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ] then echo "found BOM in: $file" fi done</code></pre> <p>Or, if you prefer short, unreadable one-liners:</p> <pre><code>find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done</code></pre> <p>It doesn't work with filenames that contain a line break, but such files are not to be expected anyway.</p> <p>Is there any shorter or more elegant solution?</p> <p>Are there any interesting text editors or macros for text editors?</p>
<p>What about this one simple command which not just finds but clears the nasty BOM? :)</p> <pre><code>find . -type f -exec sed '1s/^\xEF\xBB\xBF//' -i {} \; </code></pre> <p>I love "find" :)</p> <p><strong>Warning</strong> The above will <strong>modify</strong> binary files which contain those three characters.</p> <p>If you want just to show BOM files, use this one:</p> <pre><code>grep -rl $'\xEF\xBB\xBF' . </code></pre>
<p>If you are looking for UTF files, the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?file" rel="nofollow">file command</a> works. It will tell you what the encoding of the file is. If there are any non ASCII characters in there it will come up with UTF.</p> <pre><code>file *.php | grep UTF </code></pre> <p>That won't work recursively though. You can probably rig up some fancy command to make it recursive, but I just searched each level individually like the following, until I ran out of levels.</p> <pre><code>file */*.php | grep UTF </code></pre>
25,073
<p>I need help in</p> <ul> <li>figuring out how to iterate through currently open Excel add-in files <em>(.xla)</em> that have not been registered in Excel using the <code>Tools &gt; Add-ins</code> menu path.</li> <li>more specifically, I am interested in any workbook that doesn't appear in the Add-In dialog, but has <code>ThisWorkbook.IsAddin = True</code>.</li> </ul> <p>Demonstrating the issue:</p> <p>Trying to loop through workbooks as follows doesn't get workbooks with <code>.AddIn = True</code>:</p> <pre><code>Dim book As Excel.Workbook For Each book In Application.Workbooks Debug.Print book.Name Next book </code></pre> <p>Looping through add-ins doesn't get add-ins that are not registered:</p> <pre><code>Dim addin As Excel.AddIn For Each addin In Application.AddIns Debug.Print addin.Name Next addin </code></pre> <p>Looping through the VBProjects collection works, but only if user has specifically trusted access to the Visual Basic Project in the Macro Security settings - which is rarely:</p> <pre><code>Dim vbproj As Object For Each vbproj In Application.VBE.VBProjects Debug.Print vbproj.Filename Next vbproj </code></pre> <p>However, if the name of the workbook is known, the workbook can be referenced directly regardless of whether it is an add-in or not:</p> <pre><code>Dim book As Excel.Workbook Set book = Application.Workbooks("add-in.xla") </code></pre> <p>But how the heck to get reference to this workbook if the name is not known, and user's macro security settings cannot be relied on?</p>
<p>As of Office 2010, there is a new collection .AddIns2 which is the same as .AddIns but also includes the unregistered .XLA plug-ins.</p> <pre><code>Dim a As AddIn Dim w As Workbook On Error Resume Next With Application For Each a In .AddIns2 If LCase(Right(a.name, 4)) = ".xla" Then Set w = Nothing Set w = .Workbooks(a.name) If w Is Nothing Then Set w = .Workbooks.Open(a.FullName) End If End If Next End With </code></pre>
<p>I'm still on the lookout for a sane solution for this problem, but for the time being it seems that reading the window texts of all workbook windows gives a collection of all open workbooks, add-in or not:</p> <pre><code>Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long Public Function GetAllOpenWorkbooks() As Collection 'Retrieves a collection of all open workbooks and add-ins. Const EXCEL_APPLICATION_WINDOW As String = "XLDESK" Const EXCEL_WORKBOOK_WINDOW As String = "EXCEL7" Dim hWnd As Long Dim hWndExcel As Long Dim contentLength As Long Dim buffer As String Dim bookName As String Dim books As Collection Set books = New Collection 'Find the main Excel window hWndExcel = FindWindowEx(Application.hWnd, 0&amp;, EXCEL_APPLICATION_WINDOW, vbNullString) Do 'Find next window hWnd = FindWindowEx(hWndExcel, hWnd, vbNullString, vbNullString) If hWnd Then 'Create a string buffer for 100 chars buffer = String$(100, Chr$(0)) 'Get the window class name contentLength = GetClassName(hWnd, buffer, 100) 'If the window found is a workbook window If Left$(buffer, contentLength) = EXCEL_WORKBOOK_WINDOW Then 'Recreate the buffer buffer = String$(100, Chr$(0)) 'Get the window text contentLength = GetWindowText(hWnd, buffer, 100) 'If the window text was returned, get the workbook and add it to the collection If contentLength Then bookName = Left$(buffer, contentLength) books.Add Excel.Application.Workbooks(bookName), bookName End If End If End If Loop While hWnd 'Return the collection Set GetAllOpenWorkbooks = books End Function </code></pre>
36,512
<p>In Haskell, is there a way to restrict a monad <code>M a</code> so that <code>a</code> satisfy a type class constraint?</p> <p>I am translating the <a href="http://github.com/namin/spots/tree/master/probabilisticModeling/README.markdown" rel="noreferrer">probabilistic modeling example</a> from <a href="http://github.com/namin/spots/tree/master/probabilisticModeling/probabilisticModeling.fsx" rel="noreferrer">F#</a> to <a href="http://github.com/namin/spots/tree/6c5a3b78e8f5f559900bade7629fab0edcf225e8/probabilisticModeling/probabilisticModeling.hs" rel="noreferrer">Haskell</a>. However, in Haskell, I omitted <code>support</code> because it would change <code>data Distribution a</code> to <code>data (Ord a) =&gt; Distribution a</code>. With this change, I get the following error:</p> <pre><code>...probabilisticModeling.hs:42:13: Could not deduce (Ord a) from the context () arising from a use of `always' at ...probabilisticModeling.hs:42:13-18 Possible fix: add (Ord a) to the context of the type signature for `return' In the expression: always In the definition of `return': return = always In the instance declaration for `Monad Distribution' </code></pre> <p>Indeed, the type of <code>always</code>/<code>return</code> is: <code>(Ord a) =&gt; a -&gt; Distribution a</code>. Is there a way I can have a monad <code>Distribution</code>, but force the constraint <code>(Ord a)</code> on this monad? I tried:</p> <pre><code>instance Monad Distribution where (&gt;&gt;=) = bind return :: (Ord a) =&gt; a -&gt; Distribution a = always </code></pre> <p>But I get the error:</p> <pre><code>...probabilisticModeling2.hs:48:4: Pattern bindings (except simple variables) not allowed in instance declarations return :: (Ord a) =&gt; a -&gt; Distribution a = always Failed, modules loaded: none. </code></pre> <p>So it there a way to have a monad <code>M a</code>, but restrict the <code>a</code> with a constraint such as <code>Ord a</code>?</p> <p>Thanks.</p>
<p>My understanding of this is that you simply cannot, because a monad is meant to be generalized over all types, not some restricted subset of types such as <code>(Ord a)</code>.</p> <p>Instead of restricting the monadic type <code>M a</code>, you can simply restrict functions which use that monadic type, e.g.,</p> <pre>foo :: Ord a => Int -> M a</pre> <p>In fact, it is preferable to keep types as general as possible and use type classes only to restrict functions.</p> <p>etc.</p>
<p>Check out <a href="http://web.engr.oregonstate.edu/~erwig/pfp/" rel="nofollow noreferrer">Martin Erwig's library, PFP</a>:</p> <blockquote> <p>The PFP library is a collection of modules for Haskell that facilitates probabilistic functional programming, that is, programming with stochastic values. The probabilistic functional programming approach is based on a data type for representing distributions. A distribution represent the outcome of a probabilistic event as a collection of all possible values, tagged with their likelihood.</p> </blockquote>
49,725
<p>This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?</p> <p>And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:</p> <pre><code>private IWebBase FindWebBase() { if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet"); } </code></pre> <p>The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.</p> <p>I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.</p> <p>The compiler error is: Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.</p>
<p>No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request." </p> <p>In other words it is an HttpContext object, not a Page.</p> <p>You can get to the Page object via HttpContext using:</p> <pre><code>Page page = HttpContext.Current.Handler as Page; if (page != null) { // Use page instance. } </code></pre>
<p>Please see my answer : <br/> <a href="https://stackoverflow.com/questions/1054123/why-httpcontext-current-handler-is-null">Why HttpContext.Current.Handler is null?</a> <br/><br/> Maybe resolved your problem.<br/></p>
8,254
<p>When programmatically issuing HTTP POST requests, what timeout values would be sensible?</p> <p>In my case, I'm looking to set 'sensible' timeout values when making POST requests in PHP, however this applies to any language.</p> <p>I need to be able to issue a set of requests, each to a user-specified URL. If I do need to process requests consecutively instead of concurrently, I'd like to specify a sensible time beyond which a request is deemed to have timed out.</p> <p>PHP's <a href="https://stackoverflow.com/questions/170938/what-is-the-default-time-after-which-an-http-request-is-deemed-to-have-timed-out">default socket timeout</a> is 60 seconds. This seems an unnecessarily long time to wait before deciding a request is not going to be completed.</p> <p>As these are POST requests they should complete quickly - there's no data to be retrieved and returned as with a GET request.</p> <p>We should be able to assume, <em>most of the time</em>, that the failure to issue a response to a request within X seconds means the host is unlikely to issue a response within a reasonable time for values of X <em>significantly</em> less than 60.</p> <p>Surely hosts rarely take more than 60 seconds to respond to a simple POST request. Do they even rarely take more than 10 seconds? 5 seconds?</p> <p>What might be sensible values for X in practice? Justifications accompanying suggestions would be extremely beneficial.</p>
<p>I would recommend setting up a test, as there are too many factors involved to give a value that will always be sensible.</p> <p>A POST request sends data to be processed. How long with the processing take? This will be application/data specific.</p> <p>Where is the host? The user is supplying the URL, so that will be unknown. We can't know what traffic is like between your application and the host. We can't know the server load of the host.</p> <p>Essentially, there is no universal sensible timeout. You have to use your own best judgment based on your specific needs. Set up a test and use that to determine your limits.</p>
<p>Most libraries have a connect timeout and a read timeout. That is, the timeout between trying to connect to the remote server, and the timeout after sending the request, that they should wait for a response.</p> <p>If this is a local web service, I would set the connect timeout low, 1 second, or less if your library supports it. If the remote service you are connecting to is unavailable IMHO its better to return a response to the user immediately, than to allow all your worker threads to block on that remote service, causing other upstream errors.</p> <p>As for the read timeout, that is trickier, you need it to be low, so you don't exhaust your pool of workers who are waiting for the remote service to return, but you also don't want it so low that it closes the connection before reading a response. That is something you'll have to test, then track as a metric when your system is in production.</p>
20,635
<p>I am currently creating an overnight job that calls a Unix script which in turn creates and transfers a file using <code>ftp</code>. I would like to check all possible return codes. The man page for <code>ftp</code> doesn't list return codes. Does anyone know where to find a list? Anyone with experience with this? We have other scripts that grep for certain return strings in the log, and they send an email when in error. However, they often miss unanticipated codes. I am then putting the reason into the log and the email.</p>
<p>The <code>ftp</code> command does not return anything other than zero on most implementations that I've come across.</p> <p>It's much better to process the three digit codes in the log - and if you're sending a binary file, you can check that bytes sent was correct.</p> <p>The three digit codes are called 'series codes' and a list can be found <a href="http://www.ftpplanet.com/ftpresources/ftp_codes.htm" rel="nofollow noreferrer">here</a></p>
<p>Why not just store all output from the command to a log file, then check the return code from the command and, if it's not 0, send the log file in the email?</p>
16,940
<p>Anet A8 with Cura. First time use. The extrusion temperature is set at 190 °C for PLA but the temperature never quite gets that hot, e.g. 189.2 °C. So the printer never prints.</p> <p>The bed temperature is fine.</p> <p>Any suggestions on how to fix?</p>
<p>Two common problems to look out for in this situation:</p> <ul> <li>Make sure that your <strong>part fan</strong> (the fan that is supposed to cool the filament you just extruded, and that does not start spinning until the print starts) do <em>not</em> blow air on the hot end of your extruder.</li> <li>Make sure that your <strong>hot end is well insulated</strong>. If available for your printer, silicone sleeves are the best:</li> </ul> <p><a href="https://i.stack.imgur.com/7TKQM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7TKQM.jpg" alt="silicone sleeves"></a></p> <p>otherwise the most common, universal and low-cost solution are cotton pads:</p> <p><a href="https://i.stack.imgur.com/qcwSc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qcwSc.jpg" alt="enter image description here"></a></p>
<p>I had the same problem.</p> <p><em><strong>If</strong> your mains supply is 110 V</em>, then make sure that the voltage selector switch of your PSU is set to 110 V... it should then print.</p> <p>If the voltage selector switch is set to the default of 220 V, <em>and the mains supply is only 110 V</em>, then the PSU will not provide enough current.</p> <hr /> <p>Note: If your mains is 240 V then changing the voltage selector to 110 V will damage your PSU or worse.</p>
807
<p>I've got a section of code on a b2evo PHP site that does the following: </p> <pre><code>$content = preg_replace_callback( '/[\x80-\xff]/', create_function( '$j', 'return "&amp;#".ord($j[0]).";";' ), $content); </code></pre> <p>What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure. </p> <p>Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory. </p> <p>This is causing problems with my web application. Why am I losing memory, and how do I rewrite this so I don't get a memory leak?</p>
<p>Not really stripping, it replaces high-Ascii characters by their entities.</p> <p>See <a href="http://fr.php.net/manual/en/function.preg-replace-callback.php" rel="nofollow noreferrer" title="PHP: preg_replace_callback - Manual">preg_replace_callback</a>.<br> create_function is used to make an anonymous function, but you can use a plain function instead:</p> <pre><code>$content = 'Çà ! Nœm dé fîçhïèr tôrdù, @ pöür têstër... ? ~ Œ[€]'; $content = preg_replace_callback('/[\x80-\xff]/', 'CB_CharToEntity', $content); echo $econtent . '&lt;br&gt;'; echo htmlspecialchars($content) . '&lt;br&gt;'; echo htmlentities($content) . '&lt;br&gt;'; echo htmlentities($content, ENT_NOQUOTES, 'cp1252') . '&lt;br&gt;'; function CB_CharToEntity($matches) { return '&amp;#' . ord($matches[0]) . ';'; } </code></pre> <p>[EDIT] Found a cleaner, probably faster way to do the job! ^_^ Just use htmlentities with options fitting your needs.</p>
<p>It's a lot simpler to use <code>preg_replace</code> with the <code>/e</code> flag in your case:</p> <pre><code>$content = preg_replace( '/[\x80-\xff]/e', '"&amp;#".ord($0).";"', $content); </code></pre>
37,800
<p>How do I programatically (Using C#) find out what the path is of my My Pictures folder? </p> <p>Does this work on XP and Vista?</p>
<p>The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista)</p> <pre><code>Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); </code></pre>
<p>Using Microsoft.VisualBasic.FileIO.SpecialDirectories.MyPictures you can get that, works in vista and XP.</p>
14,145
<p>I'm using NHibernate 2 and PostgreSQL in my project. SchemaExport class does a great job generating DDL scheme for database, but it's great until the first application. </p> <p>Is there any way to generate "migration" DLL (batch of "ALTER TABLE"'s instead of DROP/CREATE pair) using NHibernate mapping files?</p>
<p>Look into <a href="http://morten.lyhr.dk/2008/03/nhibernates-schemaupdate-feature.html" rel="nofollow noreferrer">SchemaUpdate</a>. Very similiar API as SchemaExport but it only creates migrations.</p>
<p>While SchemaUpdate very much answers my needs, it still has several problems. For example it refuses to put a new restriction on existing database column even if it's not gonna conflict with existing data.</p> <p>I'm going froward to extend SchemaUpdate a little bit or, if fail, switch to one of that hand driven migration tools (for example Rails one).</p>
14,030
<p>I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "<em>svn update -r 2 A.txt</em>" because this will delete all the revisions after r2, namely r3 and r4. </p> <p>So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "<em>svn log A.txt</em>" after doing the update.</p>
<p>To make a new revision of A.txt that is equal to revision 2:</p> <pre><code>svn up -r HEAD svn merge -r HEAD:2 A.txt svn commit </code></pre> <p>Also see the description in <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo" rel="noreferrer">Undoing changes</a>.</p>
<p>Update won't delete any revisions on the server. The only changes it makes are to your local working copy:</p> <p><a href="http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.update.html" rel="nofollow noreferrer">SVN Update Command</a></p> <p>"brings changes from the repository into your working copy"</p> <p>"synchronizes the working copy to the revision given by the --revision switch"</p>
11,988
<p>It should also support SSH2 and public key auth for starters. secondly on Mac/Windows it should have a decent installer.</p>
<h2>As of 2011...</h2> <p>It's an old question, but still very relevant. Over the past few years I have had to work on projects on various platforms using just about every version control system out there. Although ultimately I find that nothing beats the safety and expedience of knowing the command line well, the reality is that a decent GUI really helps with visualization and a really good GUI helps you not make bonehead mistakes.</p> <p>I have always tried to make the most use of open source offerings, but there comes a time when you begin to appreciate a little extra polish in the product because you (a) get tired and really just want to focus on getting your own product out the door and (b) you get tired of explaining things to more junior team members and so just want the tooling experience to be as smooth and trouble-free as possible.</p> <p>While working on getting our own iPhone app out the door, we initially settled on <a href="http://www.sourcetreeapp.com/" rel="nofollow noreferrer" title="SourceTree">SourceTree</a> because it's an excellent GUI and it also supports Mercurial, which I love. In my opinion, SourceTree is well worth the price and you won't regret using it.</p> <p>However, having led a team that includes a range of experience from junior to very experienced developers on a cross-platform project that involves...</p> <ul> <li>iOS (XCode on Mac OS X)</li> <li>Windows Azure and ASP.NET backend (Visual Studio on Windows)</li> </ul> <p>...it became frustrating having to have separate configuration settings and translate mentally between SourceTree on the Mac and TortoiseGit on Windows.</p> <p><strong><em>And then we discovered <a href="http://www.syntevo.com/smartgit/index.html" rel="nofollow noreferrer">SmartGit</a>. And boy oh boy, do I love SmartGit.</em></strong></p> <p>SmartGit costs $70, but I believe it's well worth the price in terms of the productivity boost and hassles it will save for most team members. It is an outstanding Git client with a very slick, polished UI that stands on its own merits and has become my favorite -- but when you throw in the fact that it runs on Windows/Mac/Linux, the value proposition for the team increases exponentially. We love love love not having to use different clients for different platforms.</p> <p>There is one killer feature for SmartGit compared to any other GUI tool I've used for Git. We make heavy use of Git submodules. If you don't know or use submodules, then this won't apply to you. But if you do, then you will appreciate how brain-dead simple SmartGit makes it. No other GUI Git tool that I've used comes close.</p> <p>The are caveats:</p> <ol> <li>We had trouble with a repo that was initialized with TortoiseGit using RSA private keys. SmartGit can use the system ssh or it's own built in ssh client that requires OpenSSH private keys. Since we use GitHub for our remote repository, we just switched over to using the HTTPS URL for the repo and everything was fine. However, to get it to work with Xcode or MonoDevelop on the Mac, just make sure to generate DSA instead of RSA for the keys.</li> <li>SmartGit makes working with submodules extremely easy, but the one thing it doesn't seem to do is automatically initialize nested submodules. In other words, if your submodule itself references other submodules, you will have to right-click on each of those in view to initialize individually.</li> </ol> <p>Ultimately, however, I don't think there is any real competition right now for such a first-class cross-platform Git GUI tool like SmartGit.</p> <p>If you want to see my comparison of the two best Git GUI tools for OS X, read <a href="https://stackoverflow.com/questions/83789/what-is-the-best-git-gui-on-osx/6062972#6062972">this answer</a>.</p>
<p>Another reasonable solution should be <code>git-gui</code>, which requires a Tcl/Tk framework to be installed.</p>
12,769
<p>I was considering printing some pieces for my irrigation system, like tube connectors and such. I am aware that PLA is hydrophilic so I was wondering with what kind of product I could coat the pieces, non-toxicity is a requirement because it will water edible greens.</p> <p>So, what kind of non-toxic product can I use to coat PLA to make it hydrophobic?</p>
<p>Before worrying too much about the hydrophilic properties of PLA, it might be worthwhile to test a fitting.</p> <p>First, print a fitting and see that the freshly made print is strong enough to carry the pressure of the water, and the compression force of hose clamp you may need to connect the stiff irrigation hose to the printed fitting. </p> <p>Second, soak the printed fitting in water for month or two, perhaps at an elevated temperature to match the higher ground temperature in the summer. You could put the part in a closed mason jar and leave it in the sun. You might add a little salt and fertilizer to the water to simulate ground conditions.</p> <p>After this aging process, you could test to see if it withstands the pressure of the domestic water system.</p> <p>You might also measure the ground temperatures where you intend to use the fittings. I find that PLA has no structural strength above about 150 degrees Fahrenheit (65 degrees Centigrade), and the inability to resist slow plastic may start at an even lower temperature. [For example, I print structural PLA parts with negative clearances and then dip them in 160 degree F water to soften them.]</p> <p>If the printed fittings are strong enough but suffer from water absorption, I would either print them of ABS or coat them with an ABS coating. To make the coating, dissolve ABS in acetone until it is the consistency of thick cream, dip your fitting in the mixture, and allow them to dry. It will take longer than you think it should to dry, and the solution will take more ABS plastic than you might expect.</p> <p>ABS is not generally considered to be "food safe", but this isn't a potable water system. The FDA lists ABS as conditionally food safe, and I would be comfortable using it to irrigate my lawn and vegetables.</p>
<p>PLA will biodegrade over time. ABS would last longer, and stand up to higher temps.</p>
887
<p>With the introduction of .NET 3.5 and the <code>IQueryable&lt;T&gt;</code> interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using <code>IQueryable&lt;T&gt;</code> which may lead to some new patterns.</p> <p><strong>What patterns have emerged from the useful <code>IQueryable&lt;T&gt;</code> interface?</strong></p>
<p>It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository:</p> <pre><code>public class LinqToSqlRepository : IRepository { private readonly DataContext _context; public LinqToSqlRepository(DataContext context) { _context = context; } public IQueryable&lt;T&gt; Find&lt;T&gt;() { return _dataContext.GetTable&lt;T&gt;(); // linq 2 sql } /** snip: Insert, Update etc.. **/ } </code></pre> <p>and then use it with linq:</p> <pre><code>var query = from customers in _repository.Find&lt;Customer&gt;() select customers; </code></pre>
<p>It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository:</p> <pre><code>public class LinqToSqlRepository : IRepository { private readonly DataContext _context; public LinqToSqlRepository(DataContext context) { _context = context; } public IQueryable&lt;T&gt; Find&lt;T&gt;() { return _dataContext.GetTable&lt;T&gt;(); // linq 2 sql } /** snip: Insert, Update etc.. **/ } </code></pre> <p>and then use it with linq:</p> <pre><code>var query = from customers in _repository.Find&lt;Customer&gt;() select customers; </code></pre>
13,949
<p>If I am 3D printing on my Ender 3, and I pause the print, the extruder lets out more filament for like 2 seconds. This leaves a glob of dry filament on my print, which the could contact the nozzle tip, causing it to slide the build platform.</p> <p>I have fixed the build platform sliding problem by attaching the included clips. However, another problem remains. Once the glob is made, the filament dropped on top of it gets pushed up, making the print not be even, which ruins the print. I don't think I did anything wrong on the setup, but it might just be that the extruder doesn't stop in time? Did I do anything wrong is is this an issue among all Ender 3s?</p> <ul> <li>I use the Creality Ender 3</li> </ul>
<p>They're caused by filament being pulled during travel so they qualify as stringing.</p> <p>You need to look at your retraction and heat, speed as well makes a difference. You can try combing and other things or just pull them off.</p>
<p>You should provide a better picture, i.e. a finished print.</p> <p>Stringing is generally something you don't worry about - adjust your retraction settings a tiny bit to retract more. I didn't see what software you used, that will help with where the settings are.</p> <p>Also the plate is very different from the rest of the layers, it could just be a leveling issue.</p>
2,217
<p>Please don't reply I should use ddd, nemiver, emacs, vim, or any other front-end, I just prefer gdb as it is, but would like to see its output with some terminal colors.</p>
<h1>.gdbinit</h1> <p>You can tweak your <code>~/.gdbinit</code> to have colors. You can use mammon's <code>.gdbinit</code> which is available here:</p> <p><a href="https://github.com/gdbinit/gdbinit" rel="noreferrer">https://github.com/gdbinit/gdbinit</a></p> <p>You can tweak it as much as you want too. I found this thanks to <a href="https://stackoverflow.com/questions/5526432/gdb-in-backtrack">this SO answer</a>. Here's the kind of output that you can obtain:</p> <p><img src="https://i.stack.imgur.com/Nhuwf.png" alt=".gdbinit"></p> <p>A GitHub repository is also available: <a href="https://github.com/gdbinit/Gdbinit" rel="noreferrer">https://github.com/gdbinit/Gdbinit</a></p> <p>On a side note, the same idea was also <a href="https://github.com/deroko/lldbinit" rel="noreferrer">applied to lldb</a>.</p> <h1>GDB Dashboard</h1> <p>Following the same concept, <a href="https://github.com/cyrus-and/gdb-dashboard" rel="noreferrer">GDB Dashboard</a> provides a modular visual interface for GDB in Python.</p> <p><a href="https://i.stack.imgur.com/mHC8f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mHC8f.png" alt="GDB Dashboard"></a></p> <h1>(void)walker</h1> <p>Another similar project uses GDB's Python support to provide more extensibility, so this is worth checking out: <a href="https://github.com/dholm/voidwalker" rel="noreferrer">https://github.com/dholm/voidwalker</a></p> <p>@dholm also provides his own <a href="https://github.com/dholm/dotgdb" rel="noreferrer">.gdbinit</a> inspired from the previous one.</p> <p><img src="https://raw.githubusercontent.com/dholm/voidwalker/master/screenshot.png" alt="(void)walker"></p> <h1>pwndbg</h1> <p>Some projects provide a set of useful functions, including improved display. This is the case for <a href="https://github.com/longld/peda" rel="noreferrer">PEDA</a> or <a href="https://github.com/zachriggle/pwndbg" rel="noreferrer">pwndbg</a>. The latter gives the following description:</p> <blockquote> <p>A PEDA replacement. In the spirit of our good friend <code>windbg</code>, <code>pwndbg</code> is pronounced <code>pwnd-bag</code>.</p> <ul> <li>Speed</li> <li>Resiliency</li> <li>Clean code</li> </ul> </blockquote> <p>It provides commands to support debugging and exploit development similar to the ones from PEDA, and better display (although this is not the main focus of the project). The software is still under development, and has not been properly released yet.</p> <p><a href="https://i.stack.imgur.com/BuVHv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BuVHv.png" alt="pwndbg"></a></p> <h1>voltron</h1> <p>The <a href="https://github.com/snare/voltron" rel="noreferrer">project</a> description states:</p> <blockquote> <p>Voltron is an extensible debugger UI for hackers. It allows you to attach utility views running in other terminals to your debugger (LLDB or GDB), displaying helpful information such as disassembly, stack contents, register values, etc, while still giving you the same debugger CLI you're used to.</p> </blockquote> <p>You can modify your <code>.gdbinit</code> to automatically integrate it. However, the display itself is outside of GDB (e.g. in a tmux split).</p> <p><a href="https://i.stack.imgur.com/7eWF1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7eWF1.png" alt="voltron"></a></p> <h1>GEF</h1> <p><a href="https://github.com/hugsy/gef" rel="noreferrer">GEF</a> is another option, and it is described as:</p> <blockquote> <p>It is aimed to be used mostly by exploiters and reverse-engineers, to provide additional features to GDB using the Python API to assist during the process of dynamic analysis and exploit development.</p> </blockquote> <p><a href="https://i.stack.imgur.com/EpxEz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EpxEz.png" alt="GEF"></a></p>
<p>you can get whatever colors you want;</p> <pre><code># gdb (gdb) shell echo -en '\E[47;34m'"\033[1m" ... anything is now blue foreground and white background ... (gdb) shell tput sgr0 ... back to normal </code></pre>
25,717
<p>JSON text (<a href="http://www.ietf.org/rfc/rfc4627.txt?number=4627" rel="noreferrer">RFC 4627</a>) has unambigious representation of objects, arrays, strings, numbers, Boolean values (literally <code>true</code> or <code>false</code>) and <code>null</code>. However, it has nothing defined for representing time information like date and time of day, which is very common in applications. What are the current methods in use to represent time in JSON given the constraints and grammar laid out in <a href="http://www.ietf.org/rfc/rfc4627.txt?number=4627" rel="noreferrer">RFC 4627</a>?</p> <p>Note to respondents: The purpose of this question is to document the various methods known to be in circulation along with examples and relative pros and cons (ideally from field experience).</p>
<p>The only representation that I have seen in use (though, admittedly, my experience is limited to <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">DOJO</a>) is <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer">ISO 8601</a>, which works nicely, and represents just about anything you could possibly think of.</p> <p>For examples, you can visit the link above.</p> <p>Pros:</p> <ul> <li>Represents pretty much anything you could possibly throw at it, including timespans. (ie. 3 days, 2 hour)</li> </ul> <p>Cons:</p> <ul> <li>Umm... I don't know actually. Other than perhaps it might take a bit of getting used to? It's certainly easy enough to parse, if there aren't built in functions to parse it already.</li> </ul>
<p>I recommend using <a href="https://www.ietf.org/rfc/rfc3339.txt" rel="nofollow">RFC 3339</a> format, which is nice and simple, and understood by an increasing number of languages, libraries, and tools.</p> <p>Unfortunately, RFC 3339, Unix epoch time, and JavaScript millisecond time, are all still not quite accurate, since none of them account for leap seconds! At some point we're all going to have to revisit time representations yet again. Maybe the next time we can be done with it.</p>
11,685
<p>What's the difference between failover and disaster recovery?</p>
<p>Failover: When one machine fails, another machine (usually in the same location) takes over and resumes service</p> <p>Disaster recovery: When Godzilla destroys your data center, you do have alternative locations to keep providing your service and protocols/means for the other location to know how to keep delivering the service</p> <p>Depending on the particular needs of each service, disaster recovery might just be a backup tape in a safe in a different location. In other words, it's just having a defined protocol to recover from disaster. Likewise, failover might just be having a spare backup machine which makes you go to the data center for it to take over the place of the failed one, that is, having a defined protocol about what to do in case of machine failure.</p> <p>Summing up, failover answers the question 'what do I do in case a single machine fails?', disaster recovery answers 'what do I do in case a disaster happens (fire, floods, war, ISP goes bankrupt, whatever)?'</p> <p><a href="http://dasunhegoda.com/high-availability-deployment-architecture/1003/" rel="noreferrer">High Availability Deployment Architecture</a> </p>
<p>Since a disaster (like 9/11) can <strong>completely</strong> destroy a datacenter, does it mean that DR is the processes of rebuilding everything for that datacenter?</p>
14,614
<p>I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines).</p> <p>Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape.</p> <p>It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines.</p>
<p>The standard method would be to do the <strong>separating axis test</strong> (do a google search on that).</p> <p>In short:</p> <ul> <li>Two objects don't intersect if you can find a line that separates the two objects. e.g. the objects / all points of an object are on different sides of the line.</li> </ul> <p>The fun thing is, that it's sufficient to just check all edges of the two rectangles. If the rectangles don't overlap one of the edges will be the separating axis.</p> <p>In 2D you can do this without using slopes. An edge is simply defined as the difference between two vertices, e.g.</p> <pre><code> edge = v(n) - v(n-1) </code></pre> <p>You can get a perpendicular to this by rotating it by 90°. In 2D this is easy as:</p> <pre><code> rotated.x = -unrotated.y rotated.y = unrotated.x </code></pre> <p>So no trigonometry or slopes involved. Normalizing the vector to unit-length is not required either.</p> <p>If you want to test if a point is on one or another side of the line you can just use the dot-product. the sign will tell you which side you're on:</p> <pre><code> // rotated: your rotated edge // v(n-1) any point from the edge. // testpoint: the point you want to find out which side it's on. side = sign (rotated.x * (testpoint.x - v(n-1).x) + rotated.y * (testpoint.y - v(n-1).y); </code></pre> <p>Now test all points of rectangle A against the edges of rectangle B and vice versa. If you find a separating edge the objects don't intersect (providing all other points in B are on the other side of the edge being tested for - see drawing below). If you find no separating edge either the rectangles are intersecting or one rectangle is contained in the other.</p> <p>The test works with any convex polygons btw.. </p> <p><strong>Amendment:</strong> To identify a separating edge, it is not enough to test all points of one rectangle against each edge of the other. The candidate-edge E (below) would as such be identified as a separating edge, as all points in A are in the same half-plane of E. However, it isn't a separating edge because the vertices Vb1 and Vb2 of B are also in that half-plane. It would only have been a separating edge if that had not been the case <a href="http://www.iassess.com/collision.png">http://www.iassess.com/collision.png</a></p>
<p>If you're using Java, all implementations of the Shape interface have an <a href="http://java.sun.com/javase/6/docs/api/java/awt/Shape.html#intersects(double,%20double,%20double,%20double)" rel="nofollow noreferrer">intersects</a> method that take a rectangle. </p>
14,072
<p>For a beginner, which is the best book to start with for studying Bayesian Networks? </p>
<p>I would recommend "Probabilistic Graphical Models" by Daphne Koller and Nir Friedman. Its an excellent starter-to-intermediate handbook on both directed (Bayesian Networks) and undirected (Markov Networks) graphical models. The examples given are elaborate and easy to understand.</p>
<p>Mitchell's <em>Machine Learning</em> is an extremely important primer in the area of AI. It covers Bayesian Networks, devoting, as I recall, an entire chapter to it.</p> <p>I'd also check out Weka's Bayesian Network class to understand a practical implementation. If you don't know about Weka, check it out here: <a href="http://www.cs.waikato.ac.nz/ml/weka/" rel="nofollow noreferrer">http://www.cs.waikato.ac.nz/ml/weka/</a></p>
44,923
<p>I currently use nant, ccnet (cruise control), svn, mbunit. I use msbuild to do my sln build just because it was simpler to shell out. </p> <p>Are there any merits to switching my whole build script to MSBuild? I need to be able to run tests, watir style tests, xcopy deploy. Is this easier?</p> <p><strong>Update: Any compelling features that would cause me to shift from nant to msbuild?</strong></p>
<p>I like MSBuild. One reason is that .csproj files are msbuild files, and building in VS is just like building at the command line. Another reason is the good support from TeamCity which is the CI server I've been using. If you start using MSBuild, and you want to do more custom things in your build process, get the <a href="http://msbuildtasks.tigris.org/" rel="noreferrer">MSBuild Community Tasks</a>. They give you a bunch of nice extra tasks. I haven't used NAnt for several years now, and I haven't regretted it.</p> <p>Also, as Ruben mentions, there are the <a href="http://www.codeplex.com/sdctasks" rel="noreferrer">SDC Tasks</a> tasks on CodePlex.</p> <p>For even more fun, there is the <a href="http://www.codeplex.com/MSBuildExtensionPack" rel="noreferrer">MSBuild Extension Pack on CodePlex</a>, which includes a twitter task.</p>
<p>I use MSBuild <em>alongside</em> Nant, because the current version of Nant can't as yet compile .NET 3.5 applications (same was true when .NET 2.0 first came out).</p>
3,183
<p>I'm creating some text boxes on my form programmatically which I need to reference later using FindControl.</p> <p>I've put the FindControl instruction in the page load method after the code which creates them but get an error:</p> <blockquote> <p><strong>Object reference not set to an instance of an object.</strong></p> </blockquote> <p>I assume this is because the textbox controls are not created until later in the lifecycle and therefore cannot be referenced from within Page_Load. </p> <p>Can someone advise where in my code-behind I would need to place the FindControl instruction so that it can find these programmatically created text boxes?</p>
<p>Did you put your textbox control inside of another control such as a panel or grid? If so you need to recursively search all the controls on the page. </p> <p>Here is an example of a recursive FindControl implementation: <a href="http://www.codinghorror.com/blog/2005/06/recursive-pagefindcontrol.html" rel="nofollow noreferrer">Recursive Page.FindControl</a>. You can find many other examples by googling "recursive findcontrol".</p>
<p>If you make your TextBox controls during an OnInit override (before calling base.OnInit(e) I believe) they will be available during Page.OnLoad and any associated events. You also get them into the ViewState object graph in their correct position which is invaluable for dealing with post backs and especially server-side validation.</p>
23,129
<p>I have a question related to how relative paths are interpreted in various environments . If I have a C code to be compiled on linux using Makefile and gcc , and if some source file has :</p> <pre><code>fopen(“../../xyz.ctl”, ”r”); </code></pre> <p>where should this file be located. Or in other words, if I have </p> <pre><code>fopen(“xyz.ctl” , ”r”); </code></pre> <p>would the compiler look for xyz.ctl in same folder as the:-</p> <p>a.) Where source file having this statement fopen is present?</p> <p>b.) Where makefile is present ?</p> <p>c.) Where the linux executable would be generated ?</p> <p>I know that MSVC all relative paths are from the folder which has the *.dsw (workspace file). For RVDS environment it begins from the folder where the executable *.axf is generated.</p> <p>-AD</p>
<p>Your Makefile invokes gcc which compiles your code containing fopen(). fopen() is called when you execute the newly compiled code. The path is relative to your current working directory when you launched the program.</p>
<p>The path in code compiled by any Unix tool is relative to the path in which the final executable is executed.</p> <p>gcc does not try to understand what you do and it doesn't analyze paths which you compile into your application.</p> <p>As far as I know, the Windows copy command is the only command which tries to "fix" paths in applications it works on. (Story: I had a VB app on a floppy disk and when I copied it to C:, the checksum of the file had changed. A diff showed that copying the app to disk would replace "C:\" in the app to "A:\" and vice versa).</p>
44,176
<p>Erlang support to partition its nodes into groups using the <a href="http://erlang.org/doc/man/global_group.html" rel="nofollow noreferrer">global_group</a> module. Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?<br> As far as I understand, you have to name every node on startup to use the global groups.</p>
<blockquote> <p>A node is an executing Erlang runtime system which has been given a name, using the command line flag -name (long names) or -sname (short names).</p> <p>A hidden node is a node started with the command line flag -hidden. Connections between hidden nodes and other nodes are not transitive, they must be set up explicitly. Also, hidden nodes does not show up in the list of nodes returned by nodes(). Instead, nodes(hidden) or nodes(connected) must be used. This means, for example, that the hidden node will not be added to the set of nodes that global is keeping track of.</p> </blockquote> <p>So in short , yes, you need to give our node a name to be able other nodes to find it.</p> <p>It feels that you either are asking without trying out or have a very complex question and maybe an example of what you are trying to accomplish could make it possible to give a better answer.</p>
<blockquote> <p>A node is an executing Erlang runtime system which has been given a name, using the command line flag -name (long names) or -sname (short names).</p> <p>A hidden node is a node started with the command line flag -hidden. Connections between hidden nodes and other nodes are not transitive, they must be set up explicitly. Also, hidden nodes does not show up in the list of nodes returned by nodes(). Instead, nodes(hidden) or nodes(connected) must be used. This means, for example, that the hidden node will not be added to the set of nodes that global is keeping track of.</p> </blockquote> <p>So in short , yes, you need to give our node a name to be able other nodes to find it.</p> <p>It feels that you either are asking without trying out or have a very complex question and maybe an example of what you are trying to accomplish could make it possible to give a better answer.</p>
26,500
<p>I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last <i>word</i> before 200 chars.</p>
<p>By using the <a href="http://www.php.net/wordwrap" rel="noreferrer">wordwrap</a> function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:</p> <pre><code>substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n")); </code></pre> <p>One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:</p> <pre><code>if (strlen($string) &gt; $your_desired_width) { $string = wordwrap($string, $your_desired_width); $string = substr($string, 0, strpos($string, "\n")); } </code></pre> <hr> <p>The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:</p> <pre><code>function tokenTruncate($string, $your_desired_width) { $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE); $parts_count = count($parts); $length = 0; $last_part = 0; for (; $last_part &lt; $parts_count; ++$last_part) { $length += strlen($parts[$last_part]); if ($length &gt; $your_desired_width) { break; } } return implode(array_slice($parts, 0, $last_part)); } </code></pre> <p>Also, here is the PHPUnit testclass used to test the implementation:</p> <pre><code>class TokenTruncateTest extends PHPUnit_Framework_TestCase { public function testBasic() { $this-&gt;assertEquals("1 3 5 7 9 ", tokenTruncate("1 3 5 7 9 11 14", 10)); } public function testEmptyString() { $this-&gt;assertEquals("", tokenTruncate("", 10)); } public function testShortString() { $this-&gt;assertEquals("1 3", tokenTruncate("1 3", 10)); } public function testStringTooLong() { $this-&gt;assertEquals("", tokenTruncate("toooooooooooolooooong", 10)); } public function testContainingNewline() { $this-&gt;assertEquals("1 3\n5 7 9 ", tokenTruncate("1 3\n5 7 9 11 14", 10)); } } </code></pre> <h1><strong>EDIT :</strong></h1> <p>Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:</p> <p><code>$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);</code></p>
<p>I used this before</p> <pre><code>&lt;?php $your_desired_width = 200; $string = $var-&gt;content; if (strlen($string) &gt; $your_desired_width) { $string = wordwrap($string, $your_desired_width); $string = substr($string, 0, strpos($string, "\n")) . " More..."; } echo $string; ?&gt; </code></pre>
10,541
<p>I'm looking for a reasonably fast event handling mechanism in Java to generate and handle events across different JVMs running on different hosts.</p> <p>For event handling across multiple threads in a single JVM, I found some good candidates like Jetlang. But in my search for a distributed equivalent , I couldn't find anything that was lightweight enough to offer good performance.</p> <p>Does anyone know of any implementations that fit the bill?</p> <p><strong>Edit:</strong> Putting numbers to indicate performance is a bit difficult. But for example, if you implement a heartbeating mechanism using events and the heartbeat interval is 5 seconds, the heartbeat receiver should receive a sent heartbeat within say a second or two.</p> <p>Generally, a lightweight implementation gives good performance. A event handling mechanism involving a web server or any kind of centralized hub requiring powerful hardware (definitely not lightweight) to give good performance is not what I'm looking for. </p>
<p><a href="http://www.hazelcast.com" rel="noreferrer">Hazelcast</a> Topic is a distributed pub-sub messaging solution.</p> <pre><code>public class Sample implements MessageListener { public static void main(String[] args) { Sample sample = new Sample(); Topic topic = Hazelcast.getTopic (&quot;default&quot;); topic.addMessageListener(sample); topic.publish (&quot;my-message-object&quot;); } public void onMessage(Object msg) { System.out.println(&quot;Message received = &quot; + msg); } } </code></pre> <p>Hazelcast also supports events on distributed queue, map, set, list. All events are ordered too.</p> <p>Regards,</p> <p>-talip</p> <p><a href="http://www.hazelcast.com" rel="noreferrer">http://www.hazelcast.com</a></p>
<p>If a <a href="http://activemq.apache.org/" rel="nofollow noreferrer">JMS implementation</a> isn't for you, then you may be interested in an <a href="http://xmpp.org/about/" rel="nofollow noreferrer">XMPP</a> approach. There are multiple implementations, and also have a <a href="http://en.wikipedia.org/wiki/Publish/subscribe" rel="nofollow noreferrer">Publish-Subscribe</a> <a href="http://xmpp.org/tech/pubsub.shtml" rel="nofollow noreferrer">extension</a>. </p>
21,871
<p>So, I've been reading through and it appears that the Boost libraries get used a lot in practice (not at my shop, though). Why is this? and what makes it so wonderful? </p>
<p><a href="http://www.boost.org/" rel="noreferrer">Boost</a> is used so extensively because:</p> <ul> <li>It is open-source and peer-reviewed. </li> <li>It provides a <a href="http://www.boost.org/doc/libs" rel="noreferrer">wide range</a> of platform agnostic functionality that STL missed.</li> <li>It is a complement to STL rather than a replacement.</li> <li>Many of Boost developers are on the C++ standard committee. In fact, many parts of Boost is considered to be included in the next C++ standard library.</li> <li>It is documented nicely.</li> <li>Its <a href="http://en.wikipedia.org/wiki/Boost_Software_License" rel="noreferrer">license</a> allows inclusion in open-source and closed-source projects.</li> <li>Its features are not <em>usually</em> dependent on each other so you can link only the parts you require. [<a href="https://stackoverflow.com/users/15934/luc-hermitte">Luc Hermitte</a>'s comment]</li> </ul>
<p>I use the filesystem library quit a bit, and the boost::shared_ptr is pretty nifty. I hear it does other things too.</p>
15,266
<p>I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be </p> <pre><code>logname.2008-10-10.log </code></pre> <p>Anyone know the best way for me to do this?</p> <p>edit: I forgot to mention that we would want to do this in log4net as well. Plus any solution would need to be usable in JBoss.</p>
<p>DailyRollingFileAppender is what you exactly searching for.</p> <pre><code>&lt;appender name="roll" class="org.apache.log4j.DailyRollingFileAppender"&gt; &lt;param name="File" value="application.log" /&gt; &lt;param name="DatePattern" value=".yyyy-MM-dd" /&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n"/&gt; &lt;/layout&gt; &lt;/appender&gt; </code></pre>
<p>Even if you use <code>DailyRollingFileAppender</code> like @gedevan suggested, you will still get <code>logname.log.2008-10-10</code> (After a day, because the previous day log will get archived and the date will be concatenated to it's filename).</p> <p>So if you want <em>.log</em> at the end, you'll have to do it like this on the <code>DatePattern</code>:</p> <p><code>log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm'.log'</code></p>
23,387
<p>I was reading <em><a href="https://rads.stackoverflow.com/amzn/click/com/1430209879" rel="noreferrer" rel="nofollow noreferrer">More Joel on Software</a></em> when I came across <a href="http://en.wikipedia.org/wiki/Joel_Spolsky" rel="noreferrer">Joel Spolsky</a> saying something about a particular type of programmer knowing the difference between an <code>int</code> and an <code>Integer</code> in Java/C# (Object-Oriented Programming Languages).</p> <p>So, what is the difference?</p>
<p><strong>In Java,</strong> the 'int' type is a primitive, whereas the 'Integer' type is an object.</p> <p><strong>In C#,</strong> the 'int' type is the same as <code>System.Int32</code> and is <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types" rel="noreferrer">a value type</a> (ie more like the java 'int'). An integer (just like any other value types) can be <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" rel="noreferrer">boxed</a> ("wrapped") into an object. </p> <hr> <p>The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize: </p> <p><strong>Objects</strong> provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the <a href="http://en.wikipedia.org/wiki/Dynamic_memory_allocation" rel="noreferrer">heap</a>. Conversely, <strong>primitives</strong> are immutable types that are passed by value and are often allocated from the <a href="https://en.wikipedia.org/wiki/Stack-based_memory_allocation" rel="noreferrer">stack</a>.</p>
<p>In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like <code>Integer a = new Integer()</code>. So,as per generics <code>Integer</code> is not used but <code>int</code> is used. so there is so such difference there.</p>
2,298
<p>This would be useful when I have a user's address or zipcode, and used that to find their timezone so they don't have to enter it in a separate field.</p>
<p>I would recommend against trying to deduce the timezone from the users zip code.</p> <p>To the user the question:</p> <p>"What is your zip code" isn't likely to change very often.</p> <p>It will change, but probably less frequently then the question "what time zone are you in".</p> <p>For example, if the user travels somewhere, their zip code hasn't changed, but their timezone has.</p> <p>If you try to ask "what zip code are you in?", the user probably won't know, particularly if he or she is traveling.</p> <p>Instead, I would try and figure out what the timezone is directly.</p> <p>Most platforms will give you a way to do this.</p> <p>For example, if you are writing desktop software for .NET you can do this by</p> <ol> <li>Getting the current timezone using the TimeZoneInfo class, or</li> <li>Sending all times from the server to the client in UTC time, and then use DateTime.ToLocal Time to convert the UTC time into local time.</li> </ol> <p>Or, if you are writing web software, then you can get the timezone from the user's web browser using Java Script and submit it to the server.</p> <p>Take a look at the following date functions:</p> <p><a href="http://www.w3schools.com/jsref/jsref_obj_date.asp" rel="nofollow noreferrer">http://www.w3schools.com/jsref/jsref_obj_date.asp</a></p> <p>You can deduce the timezone using various date functions.</p> <p>There is a method "getTimezoneOffset", but it doesn't give a +/-. So for example it would give "1" for both +1 and -1 GMT, which could be a problem.</p> <p>What you can do, however, is send a known date from the server, convert that to local time using the conversion methods, and then send the result back up to the server.</p> <p>When you send the known date down, you should probably send it as a millisecond offset. That way you can avoid any culture issues (dates are formatted differently in different places).</p> <p>There are Win32 functions that will give you the timezone, and I am sure there are probably Unix, Mac, and Java APIS that will do the same thing.</p>
<p>Yes - you can use a geocoder such as geonames.org to get latitude,longitude from the zipcode (the geocoder may also include timezone or have a separate webservice for that).</p> <p>If your geocoder doesn't do it, then given the latitude and longitude you can get a timezone from this webservice:</p> <p><a href="http://www.earthtools.org/webservices.htm#timezone" rel="nofollow noreferrer">http://www.earthtools.org/webservices.htm#timezone</a></p>
47,898
<p>I'm looking for sources of inspiration and/or design patterns for navigation 'breadcrumbs'. So far I have found the <a href="http://patterntap.com/tap/collection/breadcrumbs" rel="noreferrer">breadcrumb collection on Pattern Tap</a>. Does anyone know of any other sources?</p>
<p>The article '<a href="http://www.alistapart.com/articles/taminglists/" rel="noreferrer">Taming lists</a>' from A List Apart has some good advice on CSS styling for breadcrumbs (look down for the heading 'Breadcrumb Trails').</p>
<p>If using Microsoft ASP.NET, there's a built in control: <a href="http://msdn.microsoft.com/en-us/library/x20z8c51.aspx" rel="nofollow noreferrer">SiteMapPath</a>.</p>
7,230
<p>I can't seem to find a true restful Blog API - are there any? I'm writing some blog software and wondered if there was a standard restful API, if not I'll go buy the RESTful Web Services book and design my own.</p>
<p>How about <a href="http://www.atomenabled.org/developers/protocol/#whatIsAtom" rel="noreferrer">AtomPub</a>?</p> <blockquote> <p>Atom is the name of an XML-based Web content and metadata syndication format, and an application-level protocol for publishing and editing Web resources.</p> </blockquote> <p>It isn't limited to blogs, but blogs certainly fall under the realm of applications are used for "publishing and editing Web resources".</p>
<p>I don't know about REST, but have you look at MetaWeblog API? It's XML-RPC though.</p>
37,075
<p>I'm trying to go deep into Dictionary ADT and Skip List for Java. My textbook doesn't cover a lot about this and whatever it has covered is very complicated. Which is the best online site to get more information on Dictionary ADT and Skip List for Java. I'm looking for the one which talks visually and gives a lot of examples.</p>
<p>Since it sounds like you're in an algorithms class, I would separate the implementation of a dictionary and a skip list from what is provided by the Java API. At this point, it's more important that you understand the concept of what these abstract data types are, because they can be implemented in any language (C#, PHP, Scheme, Brainfuck, etc.)</p> <p>Your instructor will probably want you to: first, define the interface or contract for a dictionary (or a skip list), and then figure out its implementation. If you're programming in Java, use JUnit to verify the correctness of your algorithms. If you're programming in some other language, look for any xUnit API.</p> <p>Look in <a href="http://www.nist.gov/dads/" rel="nofollow noreferrer">NIST's Dictionary of Algorithms and Data Structures</a> as a secondary resource to your textbook to understand what these things mean. Probably the best algorithm book in Java is Sedgewick's, and its main distinctive is its pedagogical use of applets. Since the sample code is not written in idiomatic Java, I wouldn't look there for industrial-strength implementations of the algorithms. After all, you're supposed to do the work yourself, not use someone else's collections API.</p> <p>Oh, btw, Java 6 has two implementations of skip lists: <code>ConcurrentSkipListSet</code> and <code>ConcurrentSkipListMap</code>. And the interface of a dictionary data structure in Java is <code>Map</code>.</p>
<p>You can download the PDF of William Pugh's original paper describing skip lists and the theory behind it <a href="ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf" rel="nofollow">here</a>.</p> <p>Also, <a href="http://iamwww.unibe.ch/~wenger/DA/SkipList/" rel="nofollow">this</a> is a good applet to visualize the operations of a skip list. It helped me alot when skip lists came up in my data structures class.</p> <p>Also, the <a href="http://en.wikipedia.org/wiki/Skip_list" rel="nofollow">Wikipedia</a> entry has a few good links at the bottom for other implementations and the Java source code.</p>
32,005
<p>I want to catch all unhandled exceptions thrown in a remote object on <em>the server</em> and log them there before I translate them into some custom exception so that specific exceptions do not cross the client/server boundary.</p> <p>I think I have to use a custom channel sync, but can anyone confirm this and/or have any other advice to give? </p>
<p>I would use the Microsoft Enterprise Library Exception Handling app block -- it lets you handle errors and convert specific types of exception to a different type of exception before rethrowing to the client.</p>
<p>I would use the Microsoft Enterprise Library Exception Handling app block -- it lets you handle errors and convert specific types of exception to a different type of exception before rethrowing to the client.</p>
6,429
<p>I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.</p> <p>How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.</p> <p>thank you</p>
<p>When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.</p>
<p>** Watch out because SQL DateTime columns are non-nullable and their minimum value is 1/1/1753 while .net DateTimes are non-nullable with min values of 1/1/0001. **</p> <p>If you're pulling data from a real DateTime column, by default it will always be in the same standard format. For saving the data to the column, you might want to specify the SqlDbType.DateTime in your parameter.</p> <p>i ripped this off of <a href="http://bytes.com/forum/thread767920.html" rel="nofollow noreferrer">http://bytes.com/forum/thread767920.html</a> :</p> <p>com.Parameters.Add("@adate", SqlDbType.DateTime).Value = DateTime.Now;</p>
15,089
<p>I would like to host a silverlight control in winforms via a winforms browser, but for it to work I need some way for the forms to talk to the silverlight, and also the other way around. Would it be possible to somehow have the two interact with each other using JavaScript as a middleman? I.e., have the form speak to the browser's javascript, and have that speak to the silverlight control? Is there a better way? Or even a way at all? (other than compiling the code as silverlight and wpf)</p>
<p>I think using the Windows Forms WebBrowser control is your best bet. To do this, you'll need your Silverlight app on a webpage, then you point your WebBrowser at the page's URI.</p> <p>To keep your WebBrowser control from acting like IE, I'd recommend setting the following:</p> <pre><code>webBrowser.AllowNavigation = false; webBrowser.AllowWebBrowserDrop = false; webBrowser.IsWebBrowserContextMenuEnabled = false; webBrowser.WebBrowserShortcutsEnabled = false; </code></pre> <p>Calling methods on your form from within Silverlight is easy enough to do. To start, you need a class that has all the methods you want to call from Silverlight. You can use your form itself or another object, but you need to mark the class with the [ComVisible(true)] attribute. Then you assign your object to the WebBrowser.ObjectForScripting property. This exposes your object as "window.external" on the webpage.</p> <pre><code>[ComVisible(true)] public partial class Form1 : Form { ...... webBrowser.ObjectForScripting = this; ...... public void CallMeInForm(string something) { MessageBox.Show("Silverlight said: " + something); } } </code></pre> <p>That's it for inside your Windows Forms project. Inside of your Silverlight app, you need to pick up this ObjectForScripting and invoke methods on it. To call the method in my example above, use the following lines:</p> <pre><code>using System.Windows.Browser; ...... ScriptObject myForm = (ScriptObject)HtmlPage.Window.GetProperty("external"); myForm.Invoke("CallMeInForm", "testing 1 2 3"); </code></pre> <p>The Invoke command lets you pass any number and type of parameters to your function, although I suspect it wouldn't like it very much if you try passing complex datatypes around. But if you needed to do so, you could always use serialization.</p> <p>Calling Silverlight functions from your form seems to be the tricker direction. I haven't figured this one out completely yet.</p> <p>In your Silverlight app, you also expose functions to the webpage. To do this, use the HtmlPage.RegisterScriptableObject() function. Again, you can pass in any class with methods you want to expose. For a method to be exposed, though, you have to mark it with the [ScriptableMember] attribute.</p> <pre><code>HtmlPage.RegisterScriptableObject("Page", this); ...... [ScriptableMember] public void CallMeInSilverlight(string message) { HtmlPage.Window.Alert("The form said: " + message); } </code></pre> <p>At this point, your method is exposed to JavaScript on the page and you could call it like so, assuming you added <code>id="silverlightControl"</code> to your <code>&lt;object&gt;</code> element:</p> <pre><code>document.getElementById('silverlightControl').Content.Page.CallMeInSilverlight("testing 1 2 3"); </code></pre> <p>Notice the <code>Page</code> property? That's what the call to <code>RegisterScriptableObject()</code> gave us. Now, let's wrap this into a tidy JavaScript method:</p> <pre><code>&lt;script type="text/javascript"&gt; function CallMe(message) { var control = document.getElementById('silverlightControl'); control.Content.Page.CallMeInSilverlight(message); } &lt;/script&gt; </code></pre> <p>And now we can call the <code>CallMe()</code> method from the Windows Forms app like so:</p> <pre><code>public void CallToSilverlight() { webBrowser.InvokeScript("CallMe", new object[] { "testing 1 2 3" }); } </code></pre>
<p>Silverlight in a winform app just sounds like bad news. It would mean you are running to different CLR's in a single app and would have to deal with alot of added complexity to make it work. If possible consider using the full WPF within your app instead here is a <a href="http://blog.paranoidferret.com/index.php/2008/06/24/wpf-tutorial-using-wpf-in-winforms/" rel="nofollow noreferrer">link</a> showing you how.</p>
24,164
<p>I own a Creality CR-10 (using Ultimaker Cura for slicing) and I am experiencing terrible printing problems.</p> <p>My problem: I am not able to print anything that takes several hours to print. For parts printed in 30 minutes or so, my printer usually works.</p> <p>The prints end up like this (unfinished and with a lot of stringing)</p> <p><a href="https://i.stack.imgur.com/OyQrG.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/OyQrG.jpg" alt="fail"></a></p> <p>This below is actually the best result I got so far.. (important note: there is no under extrusion during the print, it suddenly stops out of nowhere..) <a href="https://i.stack.imgur.com/CGeTY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CGeTY.jpg" alt="fail2"></a> (Although I have to use terrible retraction settings and need a lot of post processing because of all the stringing - you might have an answer for that too.. I just couldnt get the 3d printer to print parts properly with good retraction settings.)</p> <p><strong>The problem is that at some point of the print, no more (PLA) material is extruded and the printer moves without actually printing anything. The first couple of layers usually work (you can see that in the images) but after wasting almost 600 grams of PLA, I am not able to find a solution myself.</strong></p> <p>.</p> <p><strong>I have some suspicions:</strong></p> <p>Could the problem be the angle, the PLA is inserted into the feeder? (so that it is almost a 90 degree bend)? The filament comes from a spool in the right hand side. But I dont think that this would cause such a problem..</p> <p><a href="https://i.stack.imgur.com/7CHIe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7CHIe.jpg" alt="Angle of inserted filament"></a></p> <p>Is it a software problem? Here are all my cura settings (I even reduced the printing speed to 30mm/s at 205°C - still didnt work..) :-(</p> <p><a href="https://i.stack.imgur.com/qKcvg.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qKcvg.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/kXKwS.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/kXKwS.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/lpbKs.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/lpbKs.jpg" alt="enter image description here"></a></p> <p>Could the length of the bowden tube and it tangling up be a problem? (as you can see in the image below) <a href="https://i.stack.imgur.com/2SoCm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/2SoCm.jpg" alt="enter image description here"></a></p> <p><strong>And annother important thing: The feeder always grinds into the filament (even at those low retraction settings) and it is always very hard to pull the filament out of the bowden after a failed print. Sometimes its almost impossible and i have to use heavy tools for it.. that should be the probelem</strong> <a href="https://i.stack.imgur.com/oZnhq.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/oZnhq.jpg" alt="enter image description here"></a></p> <p>I already did some atomic pulls, replaced the nozzle and switched the bowden tube.</p> <p><strong>I have a dream: My printer printing a part without any stringing and actually finishing the print. Please help me to achieve this dream..</strong></p> <p>Thank you for your help in advance. :)</p> <p>(and the filament I used, sorry for the bad quality of the pic) <a href="https://i.stack.imgur.com/vzH9u.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/vzH9u.jpg" alt="enter image description here"></a></p>
<p><strong>Stringing?</strong></p> <p>The stringing is explained by your relatively low retraction settings, 1.5&nbsp;mm is not much for a Bowden setup. As do too high printing temperatures.</p> <p><strong>Stopping mid printing?</strong></p> <p>What you are experiencing is called clogging, the extruder cannot push the filament through the hotend and cause the grinding you report. Clogging mid printing is usually caused by insufficient cooling (for the temperature you print at) of the cold end (causing heat creep; slowly increasing temperature of the heat break), especially all-metal hotend assemblies are notoriously known for this problem. </p> <p>Your Bowden tube does make a lot of kinks, maybe you can improve the path of the Bowden tube. Also if you are concerned about the sharp filament intake angle, you could print a filament guide:</p> <p><a href="https://i.stack.imgur.com/4E5Gk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4E5Gk.jpg" alt="Creality CR-10 extruder assembly with filament guide"></a></p>
<p>I had the same thing! On my anycubic I3 mega.</p> <p>Tried a lot of stuff and got so sick of it so I installed a 10:1 gearbox on my extruder motor. So now it provides 10x more torque and since I havent got the issue anymore where the extruder is just grinding on the filament and the motor is just skipping steps. </p> <p>No because of this and because my anycubic won't connect to a pc I can't change settings on my printer so I resolve the ratio with 1000% flow in my cura settings. And other stuff is also affected.</p> <p>But at least it won't stop and just be sitting there and skipping steps.</p>
1,186
<p>I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value.</p> <p>I've given him a number of different reasons against this, the main ones being:</p> <ul> <li>random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build)</li> <li>if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was</li> </ul> <p>Another coworker added:</p> <ul> <li>If I am testing an exception, random values will not ensure that the test ends up in the expected state</li> <li>random data is used for flushing out a system and load testing, not for unit tests</li> </ul> <p>Can anyone else add additional reasons I can give him to get him to stop doing this?</p> <p>(Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?)</p>
<p>There's a compromise. Your coworker is actually onto something, but I think he's doing it wrong. I'm not sure that totally random testing is very useful, but it's certainly not invalid.</p> <p>A program (or unit) specification is a hypothesis that there exists some program that meets it. The program itself is then evidence of that hypothesis. What unit testing ought to be is an attempt to provide counter-evidence to refute that the program works according to the spec.</p> <p>Now, you can write the unit tests by hand, but it really is a mechanical task. It can be automated. All you have to do is write the spec, and a machine can generate lots and lots of unit tests that try to break your code.</p> <p>I don't know what language you're using, but see here:</p> <p>Java <a href="http://functionaljava.org/" rel="noreferrer">http://functionaljava.org/</a></p> <p>Scala (or Java) <a href="http://github.com/rickynils/scalacheck" rel="noreferrer">http://github.com/rickynils/scalacheck</a></p> <p>Haskell <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/" rel="noreferrer">http://www.cs.chalmers.se/~rjmh/QuickCheck/</a></p> <p>.NET: <a href="http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx" rel="noreferrer">http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx</a></p> <p>These tools will take your well-formed spec as input and automatically generate as many unit tests as you want, with automatically generated data. They use "shrinking" strategies (which you can tweak) to find the simplest possible test case to break your code and to make sure it covers the edge cases well.</p> <p>Happy testing!</p>
<p>How can your guy run the test again when it has failed to see if he has fixed it? I.e. he loses repeatability of tests.</p> <p>While I think there is probably some value in flinging a load of random data at tests, as mentioned in other replies it falls more under the heading of load testing than anything else. It is pretty much a "testing-by-hope" practice. I think that, in reality, your guy is simply not thinkng about what he is trying to test, and making up for that lack of thought by hoping randomness will eventually trap some mysterious error.</p> <p>So the argument I would use with him is that he is being lazy. Or, to put it another way, if he doesn't take the time to understand what he is trying to test it probably shows he doesn't really understand the code he is writing.</p>
5,239
<p>Is it possible to inherit from both ViewPage and ViewPage&lt;T&gt;?? Or do I have to implement both. Currently this is what I have for ViewPage. Do i need to repeat myself and do the same for ViewPage&lt;T&gt;??</p> <pre><code> public class BaseViewPage : ViewPage { public bool LoggedIn { get { if (ViewContext.Controller is BaseController) return ((BaseController)ViewContext.Controller).LoggedOn; else return false; } } } </code></pre>
<p>Create both versions:</p> <pre><code>public class BaseViewPage : ViewPage { // put your custom code here } public class BaseViewPage&lt;TModel&gt; : BaseViewPage where TModel : class { // code borrowed from MVC source private ViewDataDictionary&lt;TModel&gt; _viewData; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public new ViewDataDictionary&lt;TModel&gt; ViewData { get { if (_viewData == null) { SetViewData(new ViewDataDictionary&lt;TModel&gt;()); } return _viewData; } set { SetViewData(value); } } protected override void SetViewData(ViewDataDictionary viewData) { _viewData = new ViewDataDictionary&lt;TModel&gt;(viewData); base.SetViewData(_viewData); } } </code></pre> <p>then </p> <pre><code>public class MyCustomView : BaseViewPage { } or public class MyCustomView : BaseViewPage&lt;MyCustomViewData&gt; { } </code></pre>
<p>I wouldn't put this in the View, instead I'd have it as a property on the ViewModel (have a BaseViewModel). It will be easier to test as well as ensuring you're not going down the slope of putting business logic into the views.</p>
48,400
<p>I am going to be making an application that lets users input several parameters for a bowling ball layout, and then show what that layout would look like on the ball. I have found some good resources for sphere math, so if I have a sphere whose center is (0,0,0), I will be able to get the values of the points I need on the surface of the ball. What I will need to do is have the library create:</p> <ul> <li>A sphere</li> <li>Mark points on the surface of the sphere</li> <li>Draw lines connecting the points on the sphere (arcs along a great circle - in other words, the shortest distance across the surface of the sphere)</li> <li><strong><em>Super duper bonus</em></strong> Actually be 3D, so the user could pan, zoom, rotate.</li> </ul> <p>Basically, I want to calculate the points, tell the library which ones to draw and which ones to connect with which colors, and then sit back and watch the kudos roll in. <hr/> I'd like to use .NET 2.0 and WinForms if possible...</p>
<p>If you're gonna be using WPF I recommend you use <a href="http://www.codeplex.com/perspective" rel="nofollow noreferrer">Perspective</a> or <a href="http://www.codeplex.com/3DTools" rel="nofollow noreferrer">3DTools</a>. They're both easy to use and do the job fine. </p> <p>If I had to recommend only one I would go with Perspective, at the time I used it it was easier and had more features, but it's been a long time so you should probably see for yourself.</p>
<p>If you use GLUT, you could just have the library draw the sphere for you without you having to figure out the points.</p>
31,711
<p>Search the web for the phrase "I cosay". I run across this phrase being used from time to time by individuals in tech forums, but for the life of me, I cannot figure out what it means or how it makes sense in the context of the conversations where it is used.</p> <p>Am I just way behind the times? New slang?</p>
<p>As far as I can tell from the contexts Google pulls up, it is a very poorly machine-translated form of "codigo". "digo" or some variant is "I say", so it forms it as "I cosay" when it really shouldn't be translated at all. Roughly translated it should probably be "code" or "encoding".</p>
<p>Without context, I'll have to say a cosay is the counter-say in the same vein that cosine is a counter to sine.</p>
40,609
<p>I'm attempting to use File.Move to move a file from one UNC location to another. This blows up if the UNC path for the destination happens to be the local machine (error: Access to the path is denied). Example <code>File.Move(@"\\someServer\path\file.txt", @"\\blah2\somewhere\file.txt")</code>. This assumes there's a network share out there somewhere named \\someServer and my local machine name is blah2. Change \\blah2 to C:\ and all is good.</p>
<p>Maybe it's a typo, but shouldn't it be <code>@"\\blah2\somewhere\file.txt"</code>, i.e. with two backslashes?</p>
<p>I can't seem to reproduce the bug. Maybe it has something to do with permissions? Can you move to anywhere on the local machine using a UNC address or do they all throw the exception?</p>
23,713
<p>How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how?</p>
<p>In the HTML including the Flash SWF, add the following parameter to your &lt;object&gt; tag:</p> <pre><code>&lt;param name="allowFullScreen" value="true" /&gt; </code></pre> <p>and the following attribute to your &lt;embed&gt; tag:</p> <pre><code>allowFullScreen="true" </code></pre> <p>Or, if you are using <a href="http://code.google.com/p/swfobject/" rel="nofollow noreferrer">SWFObject</a> (as you should be), add the allowFullscreen parameter to your embed code. See the <a href="http://code.google.com/p/swfobject/wiki/documentation" rel="nofollow noreferrer">SWFObject documentation</a> for the various ways to this.</p> <p>In your Flash/Flex file, you need to provide the user a way to initiate fullscreen mode - <strong>you cannot force fullscreen without the user initiating it</strong>. Whatever you have the user do, include this code as a response to it:</p> <pre><code>stage.displayState = StageDisplayState.FULL_SCREEN; //Flash systemManager.stage.displayState = StageDisplayState.FULL_SCREEN; // Flex </code></pre>
<p>I believe it is a simple actionscript command. <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary372.html" rel="nofollow noreferrer" title="Source">Source</a></p> <pre><code> fscommand( "fullscreen" , "true" ) </code></pre>
21,537
<p>I need to know when the user finishes editing a cell in an NSTableView. The table contains all of the user's calendars (obtained from the CalCalendarStore), so in order for the user's changes to be saved I need to inform the CalCalendarStore of the changes. However, I can't find anything that gets called after the user finishes their editing - I would guess that there would be a method in the table's delegate, but I only saw one that gets called when editing starts, not when editing ends.</p>
<p>You can achieve the same result without subclassing <code>NSTableView</code> by using <code>NSNotificationCenter</code> or using the <code>NSControl</code> methods. See the Apple documentation here:</p> <p><a href="http://developer.apple.com/library/mac/#qa/qa1551/_index.html">http://developer.apple.com/library/mac/#qa/qa1551/_index.html</a></p> <p>It's only a couple of lines of code and worked perfectly for me.</p> <hr> <p>If you can be the <code>delegate</code> of the <code>NSTableView</code> you just need to implement the method</p> <pre><code>- (void)controlTextDidEndEditing:(NSNotification *)obj { ... } </code></pre> <p>In fact, <code>NSTableView</code> is the <code>delegate</code> of the <code>NSControl</code> elements it contains, and forwards those method calls to its <code>delegate</code> (There are other methods that are useful)</p> <p>Otherwise, use the <code>NSNotificationCenter</code>:</p> <pre><code>// where you instantiate the table view [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingDidEnd:) name:NSControlTextDidEndEditingNotification object:nil]; // somewhere else in the .m file - (void)editingDidEnd:(NSNotification *)notification { ... } // remove the observer in the dealloc - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:NSControlTextDidEndEditingNotification object:nil]; [super dealloc] } </code></pre>
<p>Subclass NSArrayController and override objectDidEndEditing: (be sure to call super's implementation). </p> <p>This will mostly only be invoked by text fields NSTextFieldCell or NSComboBoxCell (but only when changing the value by typing it, not by selecting the value from the combo's menu). There may be a few other cells that will invoke it, but I'm not sure which ones. If you have a custom cell then consider implementing the NSEditor and NSEditorRegistration informal protocols.</p>
23,594
<p>Recently, <a href="https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception">I made a post about the developers I'm working with not using try catch blocks properly</a>, and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter:</p> <pre><code>public void AddLocations(BOLocation objBllLocations) { try { dbManager.Open(); if (objBllLocations.StateID != 0) { // about 20 Paramters added to dbManager here } else { // about 19 Paramters added here } dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations"); } catch (Exception ex) { } finally { dbManager.Dispose(); } } </code></pre> <p>This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. </p> <pre><code>// ******************************************************************************************* /// &lt;summary&gt; /// Summary description for BaseBusinessObject /// &lt;/summary&gt; /// &lt;remarks&gt; /// Base Class allowing me to do basic function on a Busines Object /// &lt;/remarks&gt; public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable { public enum DBCode { DBUnknownError, DBNotSaved, DBOK } // private fields, public properties public int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } } private int m_errorCode = 0; public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } private string m_errorMsg = ""; public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } } private Exception m_LastException = null; public Exception LastException { get { return m_LastException; } set { m_LastException = value;} } //Constructors public BaseBusinessObject() { Initialize(); } public BaseBusinessObject(int iID) { Initialize(); FillByID(iID); } // methods protected void Initialize() { Clear(); Object_OnInit(); // Other Initializable code here } public void ClearErrors() { m_errorCode = 0; m_errorMsg = ""; m_LastException = null; } void System.Runtime.Serialization.ISerializable.GetObjectData( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { //Serialization code for Object must be implemented here } // overrideable methods protected virtual void Object_OnInit() { // User can override to add additional initialization stuff. } public virtual BaseBusinessObject FillByID(int iID) { throw new NotImplementedException("method FillByID Must be implemented"); } public virtual void Clear() { throw new NotImplementedException("method Clear Must be implemented"); } public virtual DBCode Save() { throw new NotImplementedException("method Save Must be implemented"); } } // ******************************************************************************************* /// &lt;summary&gt; /// Example Class that might be based off of a Base Business Object /// &lt;/summary&gt; /// &lt;remarks&gt; /// Class for holding all the information about a Customer /// &lt;/remarks&gt; public class BLLCustomer : BaseBusinessObject { // *************************************** // put field members here other than the ID private string m_name = ""; public string Name { get { return m_name; } set { m_name = value; } } public override void Clear() { m_id = -1; m_name = ""; } public override BaseBusinessObject FillByID(int iID) { Clear(); try { // usually accessing a DataLayerObject, //to select a database record } catch (Exception Ex) { Clear(); LastException = Ex; // I can have many different exception, this is usually an enum ErrorCode = 3; ErrorMessage = "Customer couldn't be loaded"; } return this; } public override DBCode Save() { DBCode ret = DBCode.DBUnknownError; try { // usually accessing a DataLayerObject, //to save a database record ret = DBCode.DBOK; } catch (Exception Ex) { LastException = Ex; // I can have many different exception, this is usually an enum // i do not usually use just a General Exeption ErrorCode = 3; ErrorMessage = "some really weird error happened, customer not saved"; ret = DBCode.DBNotSaved; } return ret; } } // ******************************************************************************************* // Example of how it's used on an asp page.. protected void Page_Load(object sender, EventArgs e) { // Simplifying this a bit, normally, I'd use something like, // using some sort of static "factory" method // BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34); BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); if (cust.ErrorCode != 0) { // There was an error.. Error message is in //cust.ErrorMessage // some sort of internal error code is in //cust.ErrorCode // Give the users some sort of message through and asp:Label.. // probably based off of cust.ErrorMessage //log can be handled in the data, business layer... or whatever lab.ErrorText = cust.ErrorMessage; } else { // continue using the object, to fill in text boxes, // literals or whatever. this.labID = cust.ID.toString(); this.labCompName = cust.Name; } } </code></pre> <p>Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a *.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?</p>
<p>Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel.</p> <p>To me this is a code smell:</p> <pre><code>BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); </code></pre> <p>Too many brackets!</p> <p>I've found that using the active record pattern in a language like C# always ends in tears because it's hard(er) to unit test.</p>
<p>Why not just catch the exception in the Page_Load event? Some exception you might expect and know how to deal with, other exceptions should be handled by a global exception handler. </p>
29,115
<p>I'm looking for an answer in MS VC++.</p> <p>When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.</p> <p>Example in pseudo code:</p> <pre><code>FunctionB() { ... throw e; ... } FunctionA() { ... FunctionB() ... } try { Function A() } catch(e) { (&lt;--- breakpoint) ... } </code></pre> <p>I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in <code>FunctionA()</code> or <code>FunctionB()</code>, or some other function. (Assuming extensive exception use and a huge version of the above example).</p> <p>One solution to my problem is to determine and save the call stack <strong>in the exception constructor</strong> (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.</p> <p>Is there an easier way that requires less work? Without having to change my large code base?</p> <p>Are there better solutions to this problem in other languages?</p>
<p>If you are just interested in where the exception came from, you could just write a simple macro like</p> <pre><code>#define throwException(message) \ { \ std::ostringstream oss; \ oss &lt;&lt; __FILE __ &lt;&lt; " " &lt;&lt; __LINE__ &lt;&lt; " " \ &lt;&lt; __FUNC__ &lt;&lt; " " &lt;&lt; message; \ throw std::exception(oss.str().c_str()); \ } </code></pre> <p>which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).</p> <p>Then throw exceptions using</p> <pre><code>throwException("An unknown enum value has been passed!"); </code></pre>
<p>Other languages? Well, in Java you call e.printStackTrace(); It doesn't get much simpler than that.</p>
5,671
<p>Please let me know how can I disable basic authentication on Tomcat 5.5.27</p>
<p>Authentication is there only if you configure it yourself. By default web applications do not use authentication.</p>
<p>But if, as I suspect, you didn't put it there yourself, it would have been helpful for you to be told where to look. In Java, at any rate, there is probably a web.xml file in a source directory (WEB_INF/).</p>
41,835
<p>Is it better to learn how to code AJAX without the use of an AJAX library? What are the advantages of coding from scratch over using a library such as jQuery?</p> <h3>See also:</h3> <p><a href="https://stackoverflow.com/questions/122902/what-are-some-of-the-pros-and-cons-of-using-jquery">What are some of the pros and cons of using jQuery?</a></p>
<p>For learning, yes, avoid libraries. Especially for something as conceptually simple as AJAX, forcing yourself to learn how the browser can be used "raw" will benefit you immensely later on, even if you are using a library to take care of the drudgery and abstract away browser differences.</p> <p>Once you have a solid understanding of how it works though, use a library, if for no other reason than spending time working around subtle browser differences is a waste. Better yet though, spending some time reading through the source of jQuery and others will give you insight into what well-written JavaScript looks like - and that in turn will benefit the code you <em>do</em> write!</p>
<p>I think it's all a matter of what your end goal is. If your looking to have a good fundamental understanding of AJAX so you can make educated decisions about which framework is best and why certain things work then learning AJAX without the help of a framework is best for you. If your goal to learn how to architect dynamic websites and AJAX is the missing link in your understanding, then I see no harm in learning based on a framework. Besides, how often do you really need to understand the fundamentals of a technology. In the same way that you don't really need to know how to use the WinHttp object to be able to make Http requests in .Net, for the most part you don't need to know how to use the XmlHttpRequest object because your likely going to be using some form of interface to access it anyway. </p>
26,498
<p>I found <a href="http://www.jenitennison.com/xslt/grouping/muenchian.html" rel="noreferrer">this page</a> describing the Muenchian method, but I think I'm applying it wrong.</p> <p>Consider that this would return a set of ages:</p> <pre><code>/doc/class/person/descriptive[(@name='age')]/value </code></pre> <blockquote> <p>1..2..2..2..3..3..4..7</p> </blockquote> <p>But I would like a nodeset only one node for each age.</p> <blockquote> <p>1..2..3..4..7</p> </blockquote> <p>Each of these seem to return all of the values, instead of unique values:</p> <pre><code>/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value /doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)] </code></pre> <p>What am I missing?</p>
<p>Here's an example:</p> <pre><code>&lt;root&gt; &lt;item type='test'&gt;A&lt;/item&gt; &lt;item type='test'&gt;B&lt;/item&gt; &lt;item type='test'&gt;C&lt;/item&gt; &lt;item type='test'&gt;A&lt;/item&gt; &lt;item type='other'&gt;A&lt;/item&gt; &lt;item type='test'&gt;B&lt;/item&gt; &lt;item type='other'&gt;D&lt;/item&gt; &lt;item type=''&gt;A&lt;/item&gt; &lt;/root&gt; </code></pre> <p>And the XPath:</p> <pre><code>//preceding::item/preceding::item[not(.=preceding-sibling::item)]/text() </code></pre> <p>Results: A B C D</p> <p><strong>EDIT</strong>: As mousio commented this doesn't capture the last item in a list if it's the only time it appears. Taking that and Fëanor's comment into account, here's a better solution:</p> <pre><code>/root/item[not(.=preceding-sibling::item)] </code></pre>
<p>Aren't you missing a reference to 'descriptive' right after the preceding-value? Some thing like the following:</p> <pre><code>/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::descriptive[@name='age']/value)]/value </code></pre> <p>(Haven't tested it)</p>
28,186
<p>How do I get the caller's IP address in a WebMethod?</p> <pre><code>[WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } </code></pre> <p>using C# and ASP.NET</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress.aspx" rel="noreferrer">HttpContext.Current.Request.UserHostAddress</a> is what you want.</p>
<p>I made the following function:</p> <pre><code>static public string sGetIP() { try { string functionReturnValue = null; String oRequestHttp = WebOperationContext.Current.IncomingRequest.Headers["User-Host-Address"]; if (string.IsNullOrEmpty(oRequestHttp)) { OperationContext context = OperationContext.Current; MessageProperties prop = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; oRequestHttp = endpoint.Address; } return functionReturnValue; } catch (Exception ex) { return "unknown IP"; } } </code></pre> <p>This work only in Intranet, if you have some Proxy or natting you should study if the original IP is moved somewhere else in the http packet.</p>
15,828
<p>Greetings!</p> <p>I'm creating a User Control that will display data in a GridView control. We are using n-tier architecture and the data in question is retrieved from our database and returned to us as a ReadOnlyCollection. OurNewObject is a class containing several properties and an empty constructor that takes no parameters - it's in the following namespace: Acme.ObjectModel.</p> <p>In the user control, I have the following:</p> <pre><code>&lt;asp:GridView ID="ourGrid" runat="server" DataSourceID="ourDataSource"&gt; &lt;columns&gt; &lt;asp:BoundField DataField="Name" HeaderText="Full Name" /&gt; &lt;asp:BoundField DataField="Gender" HeaderText="Gender" /&gt; &lt;asp:BoundField DataField="BirthYear" HeaderText="Year of Birth" /&gt; &lt;asp:BoundField DataField="JoinDate" HeaderText="Date Joined" /&gt; &lt;/columns&gt; &lt;/asp:GridView&gt; &lt;asp:ObjectDataSource ID="ourDataSource" runat="server" SelectMethod="GetTopUsers" TypeName="Acme.Model.OurNewObject"&gt; &lt;/asp:ObjectDataSource&gt; </code></pre> <p>In the User Control's code behind, I have the following public method:</p> <pre><code>public ReadOnlyCollection&lt;OurNewObject&gt; GetTopUsers() { return (OurDataProxy.GetJustTheTopUsers()); } </code></pre> <p>When I place the User Control on a Web form and run it, I get the following message:</p> <p><strong>ObjectDataSource 'ourDataSource' could not find a non-generic method 'GetTopUsers' that has no parameters.</strong></p> <p>So my questions are:</p> <ol> <li>Am I using the ObjectDataSource incorrectly?</li> <li>Is there a more proper way to use the ObjectDataSource in this situation?</li> </ol> <p>Thanks.</p>
<p>Normally, you would create a separate object that contains your data access method(s), rather than putting the methods in the code-behind. The separate object can be an instance or static, but the object itself must have a parameterless constructor (or no constructor at all).</p> <p>Also, the TypeName property on the ObjectDataSource should reference the typename of the above-mentioned separate object. Example:</p> <pre><code>public class SampleDataObject { public ICollection&lt;OurNewObject&gt; GetTopUsers() { //[...] } } </code></pre> <p>The attributes mentioned above: [System.ComponentModel.DataObject(true)] at the class level, and [System.ComponentModel.DataObjectMethod(DataObjectMethodType.Select)] at the getter method are not required, but will aid in design-time support by filtering out other types when looking for classes to hook yer ObjectDataSource up to.</p>
<p>Try adding the <code>DataKeyNames</code> (add the primary key) attribute to the <code>GridView</code> and see if that works?</p>
38,989
<p>We have an old system running on a WinServer2003 R2 - IIS6 and it was written using classic ASP.</p> <p>We need to trap all errors and for that, I configured IIS to redirect 404s and 500s to a custom page (custom errors config) that writes the info to a log file (this page creates and manages the logs).</p> <p>Here is the weird thing: The first time the error occurs, the page is redirected and I get my log file entry. But, if this page is loaded again (I hit F5, or other user goes there, etc), the browser receives a blank page: no error message and my custom page is ever called.</p> <p>If I restart IIS6 I get the same behavior, first time it works, next not.</p> <p>-> Send ASP errors to browser is turned on</p> <p>-> Show friendly http errors is turned off in my explorer</p> <p>Any thoughts?</p>
<p>You need to ensure Server Side Debugging is not enabled in the ASP module. </p> <p>Classic ASP server 500 errors are returned as 200's. An attempt is made at opening the Server Side Debug Application, that then can't be found and IIS subsequently returns a 200 response.</p>
<p>maybe its this issue</p> <p><a href="http://www.webdevbros.net/2006/11/26/ie7-bug-blank-page-white-screen-after-some-refreshs/" rel="nofollow noreferrer">http://www.webdevbros.net/2006/11/26/ie7-bug-blank-page-white-screen-after-some-refreshs/</a></p>
30,161
<p>This has happened to me 3 times now, and I am wondering if anyone is having the same problem. I am running Visual Studio 2008 SP1, and hitting SQL Server 2005 developer edition. </p> <p>For testing, I use the Server Explorer to browse a database I have already created. For testing I will insert data by hand (right click table -> show table data).</p> <p>I can do this for a week without problems, but sometimes my computer will crash when the stars are aligned. It doesn't hang, it doesn't blue screen, I see the bios boot screen .2 seconds after I enter some value in a new row that hasn't been saved yet. I have never seen a crash like this, where it reboots instantly. I think it may happen when I enter something that violates a database constraint, but I am not sure yet (need a few more crashes to pinpoint it).</p> <p>Anyone have the same problem? Know of a solution? Too bad VS wasn't written with managed code, eh? :)</p> <p>UPDATE: I can reproduce it by inserting a duplicate primary key, clicking off the row, clicking OK on the database error notification, then trying to update the primary key again. I agree - it definitely sounds like a hardware or driver issue, but am not really sure how to solve this since this has only happened when doing this 1 particular thing in VS. I am not overclocking either - I am running a normal (single core) 3 Ghz Dell.</p>
<p>Just so you know, when your computer just snaps right back to the BIOS boot screen with no blue screen or other crash data, this is called a "<a href="http://en.wikipedia.org/wiki/Triple_fault" rel="nofollow noreferrer">triple fault</a>" Basically, there was an exception (on a hardware level) whose exception handler triggered an exception whose exception handler triggered an exception. This is almost always a hardware issue since operating systems tend to be VERY careful in the double fault handler not to trigger an exception.</p> <p>Needless to say, it could be a software problem, but I would check your RAM, CPU and motherboard for potential issues. I had a dell which was doing this fairly randomly with Vista and a new mobo/CPU from dell solved it perfectly.</p> <p>EDIT: just to note, it can be very hard to convince dell that it is indeed a hardware issue, but stick with it and eventually they'll cave and fix it for you.</p>
<p>Are you overclocking the machine? Reboots like that are a sign that you have a bad overclock, ie. too high, bad voltage settings, bad memory timings.</p>
24,306
<pre><code>String s = ""; for(i=0;i&lt;....){ s = some Assignment; } </code></pre> <p>or</p> <pre><code>for(i=0;i&lt;..){ String s = some Assignment; } </code></pre> <p>I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself.</p> <p>EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through.</p> <p>Also, the question isn't because I'm worried about memory management. Just want to know which is better.</p>
<h3>Limited Scope is Best</h3> <p>Use your second option:</p> <pre><code>for ( ... ) { String s = ...; } </code></pre> <h3>Scope Doesn't Affect Performance</h3> <p>If you disassemble code the compiled from each (with the JDK's <code>javap</code> tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that <a href="https://stackoverflow.com/questions/110083/which-of-these-loops-is-better-code-in-terms-of-performance-garbage-collection#110095">Brian R. Bondy's</a> "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases.</p> <h3>Avoid Premature Initialization</h3> <p>The only difference between the two cases is that, in the first example, the variable <code>s</code> is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to <code>s</code>, and a good JIT compiler will probably elide it at runtime. </p> <p>You could fix this simply by using an empty declaration (i.e., <code>String s;</code>), but this is considered bad practice and has another side-effect discussed below. </p> <p>Often a bogus value like <code>null</code> is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value.</p> <h3>Conserve Stack Slots</h3> <p>As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope:</p> <pre><code>void x(String[] strings, Integer[] integers) { String s; for (int i = 0; i &lt; strings.length; ++i) { s = strings[0]; ... } Integer n; for (int i = 0; i &lt; integers.length; ++i) { n = integers[i]; ... } } </code></pre> <p>The variables <code>s</code> and <code>n</code> could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller.</p> <h3>What Really Matters</h3> <p>However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application.</p> <p>The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have.</p>
<p>It seems to me that we need more specification of the problem.</p> <p>The </p> <pre><code>s = some Assignment; </code></pre> <p>is not specified as to what kind of assignment this is. If the assignment is </p> <pre><code>s = "" + i + ""; </code></pre> <p>then a new sting needs to be allocated.</p> <p>but if it is </p> <pre><code>s = some Constant; </code></pre> <p>s will merely point to the constants memory location, and thus the first version would be more memory efficient.</p> <p>Seems i little silly to worry about to much optimization of a for loop for an interpreted lang IMHO.</p>
13,533
<p>I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.</p> <pre><code>class object { int get_value(int n) const { ... } ... object x; int a = x.get_value(1); ... int b = x.get_value(1); </code></pre> <p>then the compiler could optimize the second call away and either use the value in a register or simply do <code>b = a;</code></p> <p>Is this true?</p>
<p><code>const</code> is about program semantics and not about implementation details. You should mark a member function <code>const</code> when it does not change the visible state of the object, and should be callable on an object that is itself <code>const</code>. Within a <code>const</code> member function on a class <code>X</code>, the type of <code>this</code> is <code>X const *</code>: pointer to constant <code>X</code> object. Thus all member variables are effectively <code>const</code> within that member function (except <code>mutable</code> ones). If you have a <code>const</code> object, you can only call <code>const</code> member functions on it.</p> <p>You can use <code>mutable</code> to indicate that a member variable may change even within a <code>const</code> member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the <code>const</code> member functions) or use counters.</p> <pre><code>class X { int data; mutable boost::mutex m; public: void set_data(int i) { boost::lock_guard&lt;boost::mutex&gt; lk(m); data=i; } int get_data() const // we want to be able to get the data on a const object { boost::lock_guard&lt;boost::mutex&gt; lk(m); // this requires m to be non-const return data; } }; </code></pre> <p>If you hold the data by pointer rather than directly (including smart pointers such as <code>std::auto_ptr</code> or <code>boost::shared_ptr</code>) then the pointer becomes <code>const</code> in a <code>const</code> member function, but not the pointed-to data, so you can modify the pointed-to data.</p> <p>As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function <em>effectively</em> only being called once.</p> <p>The next version of the <a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="noreferrer">C++ Standard (C++0x)</a> will have a new keyword <code>constexpr</code>. Functions tagged <code>constexpr</code> return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact).</p>
<p>I doubt it, the function could still call a global function that altered the state of the world and not violate const.</p>
12,405
<p>Assume you are doing something like the following</p> <pre><code>List&lt;string&gt; myitems = new List&lt;string&gt; { "Item 1", "Item 2", "Item 3" }; ComboBox box = new ComboBox(); box.DataSource = myitems; ComboBox box2 = new ComboBox(); box2.DataSource = myitems </code></pre> <p>So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.</p> <p>Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all. </p> <p>As a workaround, don't this would achieve the functionality that is expected/desired</p> <pre><code>ComboBox box = new ComboBox(); box.DataSource = myitems.ToArray(); </code></pre>
<p>This has to do with how data bindings are set up in the dotnet framework, especially the <code>BindingContext</code>. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same <code>BindingContext</code>. When you are setting the <code>DataSource</code> property the <code>ComboBox</code> will use the <code>BindingContext</code> to get a <code>ConcurrenyMangager</code> that wraps the list. The <code>ConcurrenyManager</code> keeps track of such things as the current selected position in the list. </p> <p>When you set the <code>DataSource</code> of the second <code>ComboBox</code> it will use the same <code>BindingContext</code> (the forms) which will yield a reference to the same <code>ConcurrencyManager</code> as above used to set up the data bindings.</p> <p>To get a more detailed explanation see <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.bindingcontext" rel="nofollow noreferrer">BindingContext</a>.</p>
<p>A better workaround (depending on the size of the datasource) is to declare two <code>BindingSource</code> objects (new as of 2.00) bind the collection to those and then bind those to the comboboxes.</p> <p>I enclose a complete example.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { private BindingSource source1 = new BindingSource(); private BindingSource source2 = new BindingSource(); public Form1() { InitializeComponent(); Load += new EventHandler(Form1Load); } void Form1Load(object sender, EventArgs e) { List&lt;string&gt; myitems = new List&lt;string&gt; { "Item 1", "Item 2", "Item 3" }; ComboBox box = new ComboBox(); box.Bounds = new Rectangle(10, 10, 100, 50); source1.DataSource = myitems; box.DataSource = source1; ComboBox box2 = new ComboBox(); box2.Bounds = new Rectangle(10, 80, 100, 50); source2.DataSource = myitems; box2.DataSource = source2; Controls.Add(box); Controls.Add(box2); } } } </code></pre> <p>If you want to confuse yourself even more then try always declaring bindings in the constructor. That can result in some <em>really</em> curious bugs, hence I always bind in the Load event.</p>
2,292
<p>I need to create a custom control to display bmp images with alpha channel. The background can be painted in different colors and the images have shadows so I need to truly "paint" the alpha channel.</p> <p>Does anybody know how to do it?</p> <p>I also want if possible to create a mask using the alpha channel information to know whether the mouse has been click on the image or on the transparent area.</p> <p>Any kind of help will be appreciated!</p> <p>Thanks.</p> <p>Edited(JDePedro): As some of you have suggested I've been trying to use alpha blend to paint the bitmap with alpha channel. This just a test I've implemented where I load a 32-bit bitmap from resources and I try to paint it using AlphaBlend function:</p> <pre><code>void CAlphaDlg::OnPaint() { CClientDC dc(this); CDC dcMem; dcMem.CreateCompatibleDC(&amp;dc); CBitmap bitmap; bitmap.LoadBitmap(IDB_BITMAP); BITMAP BitMap; bitmap.GetBitmap(&amp;BitMap); int nWidth = BitMap.bmWidth; int nHeight = BitMap.bmHeight; CBitmap *pOldBitmap = dcMem.SelectObject(&amp;bitmap); BLENDFUNCTION m_bf; m_bf.BlendOp = AC_SRC_OVER; m_bf.BlendFlags = 0; m_bf.SourceConstantAlpha = 255; m_bf.AlphaFormat = AC_SRC_ALPHA; AlphaBlend(dc.GetSafeHdc(), 100, 100, nWidth, nHeight, dcMem.GetSafeHdc(), 0, 0,nWidth, nHeight,m_bf); dcMem.SelectObject(pOldBitmap); CDialog::OnPaint(); } </code></pre> <p>This is just a test so I put the code in the OnPaint of the dialog (I also tried the AlphaBlend function of the CDC object).</p> <p>The non-transparent areas are being painted correctly but I get white where the bitmap should be transparent.</p> <p>Any help???</p> <p>This is a screenshot..it's not easy to see but there is a white rectangle around the blue circle: <a href="http://img385.imageshack.us/img385/7965/alphamh8.png">alt text http://img385.imageshack.us/img385/7965/alphamh8.png</a></p> <p>Ok. I got it! I have to pre-multiply every pixel for the alpha value. Someone can suggest the optimized way to do that?</p>
<p>The way I usually do this is via a DIBSection - a device independent bitmap that you can modify the pixels of directly. Unfortunately there isn't any MFC support for DIBSections: you have to use the Win32 function CreateDIBSection() to use it.</p> <p>Start by loading the bitmap as 32-bit RGBA (that is, four bytes per pixel: one red, one green, one blue and one for the alpha channel). In the control, create a suitably sized DIBSection. Then, in the paint routine</p> <ul> <li>Copy the bitmap data into the DIBSection's bitmap data, using the alpha channel byte to blend the bitmap image with the background colour.</li> <li>Create a device context and select the DIBSection into it.</li> <li>Use BitBlt() to copy from the new device context to the paint device context.</li> </ul> <p>You can create a mask given the raw bitmap data simply by looking at the alpha channel values - I'm not sure what you're asking here.</p>
<p>You need to do an <a href="http://en.wikipedia.org/wiki/Alpha_Blend" rel="nofollow noreferrer">alpha blend</a> with your background color, then take out the alpha channel to paint it to the control.</p> <p>The alpha channel should just be every 4th byte of your image. You can use that directly for your mask, or you can just copy every 4th byte to a new mask image.</p>
39,552
<p>I find it odd that in Visual C# 2008 Express edition, when you use the database explorer, your options are:</p> <ol> <li>Microsoft Access</li> <li>SQL Server Compact 3.5, and </li> <li>SQL Server Database File. </li> </ol> <p>BUT if you use Visual Web Developer 2008 Express, you can connect to a regular SQL Server, Oracle, ODBC, etc.</p> <p>For people developing command-line or other C# apps that need to talk to a SQL Server database, do you really need to build your LINQ/Data Access code with one IDE (Visual Web Developer) and your program in another (Visual C#)? </p> <p>It's not a hard workaround, but it seems weird. If Microsoft wanted to force you to upgrade to Visual Studio to connect to SQL Server, why would they include that feature in one of their free IDEs but not the other? I feel like I might be missing something (like how to do it all in Visual C#).</p>
<p>You should be able to choose the SQL Server Database file option to get the right kind of database (the <code>system.data.SqlClient</code> provider), and then manually correct the connection string to point to your db.</p> <p>I think the reasoning behind those db choices probably goes something like this: </p> <ul> <li>If you're using the Express Edition, and you're <em>not</em> using Visual Web Developer, you're probably building a desktop program.</li> <li>If you're building a desktop program, and you're using the express edition, you're probably a hobbyist or uISV-er working at home rather than doing development for a corporation. </li> <li>If you're not developing for a corporation, your app is probably destined for the end-user and your data store is probably going on their local machine.</li> <li>You really shouldn't be deploying <em>server-class</em> databases to end-user desktops. An <em>in-process</em> db like Sql Server Compact or MS Access is much more appropriate.</li> </ul> <p>However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:</p> <ul> <li>A real db server (and the hardware to run it) costs real money. If you have access to that, you ought to be able to afford at least the standard edition of visual studio.</li> </ul>
<p>My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.</p> <p>This difference in IDE behavior is one of the key reasons for upgrading to a full version.</p>
22,919
<p>I have a remote JS that must appear in the head of the document. If the server is slow to respond or inaccessible, obviously this slows or prevents the page from loading. I have been searching for a simple way to set a limit of say 3 seconds (probably less) for it to give up and simply not load the functionality.</p> <p>Does anyone have a simple way to do this with Javascript only?</p>
<p>Include the .JS file after the page is done loading:</p> <pre><code>&lt;script type='text/javascript'&gt; window.onload = function(){ document.write("&lt;script type='text/javascript' src='http://domain.com/file.js'&gt;&lt;/script&gt;"); } &lt;/script&gt; </code></pre> <p>Place that in the HEAD of your document, then the file will start loading when the page has finished loading.</p>
<p>If that is an issue, split the .js apart and have the low end css functions in the and the slow ones in the onload="";</p>
45,090
<p>I cannot get the internet explorer web developer tool bar to work with a pop-up, it won't render at the bottom of the pop-up. Any suggestions? </p>
<p>I am pretty sure it won't work with modal popup windows. If you are opening popups as modal you may have to change the code to mode-less just for debugging purposes.</p>
<p>Add a Javascript error in the code of the page, such as blabla();. It will make IE display the Javascript error dialog from which you can start the Developer Tools. You need to have Javascript error messages on I think:</p> <p>Tools - Internet Options, the Advanced tab Make sure "Display a notification about every script error" is checked.</p> <p>Not an ideal solution, but can help if you really need to debug in Modal Dialog mode when Modeless dialog does not produce the same result as in Modal Dialog.</p>
28,063
<p>How to encode video on the fly and send it trough the network from C#?</p> <p>Can't find a suitable library. I need to encode in WMV and don't mind if the actual encoding is made in C++ as long as the library has a .NET assembly available.</p> <p>Thanks</p>
<p>I'm aware of <a href="http://ffmpeg.mplayerhq.hu/" rel="nofollow noreferrer">ffmpeg</a>, but it is native C code only. If you're ok with interoperability this may be your ticket.</p> <p>Edit: It turns out someone already wrapped this in a .NET assembly. It's called <a href="http://www.intuitive.sk/fflib/" rel="nofollow noreferrer">FFlib.NET</a>.</p>
<p>Depending on what you are encoding (size, framerate, hardware, etc) real-time encoding may not even be possible. Video encoding is VERY CPU intensive.</p>
6,585
<p>We are designing an application which would also have a need to manage a large number of files (docs, spreadsheets, scanned files, pdfs, etc.). We will need to associate files with other data in the system.</p> <p>This will be a web-based application.(asp.net)</p> <p>While there are many ways to solve this problem, I am thinking whether there is document management backend which we can plug into the software, and use its API to store, retrieve and reference files.</p> <p>There must be some, but do you know of any open source ones that you have used in the past.</p> <p>Thanks.</p>
<p>It would be helpful to know what platform you are using. Since most of my experience is with the Java platform here's some links:</p> <p>JSR-170: Content Repository API <a href="http://www.cmswatch.com/Feature/123" rel="nofollow noreferrer">http://www.cmswatch.com/Feature/123</a></p> <p>And here is the reference implementation, Apache Jackrabbit: <a href="http://jackrabbit.apache.org/" rel="nofollow noreferrer">http://jackrabbit.apache.org/</a></p>
<p>There are quite a number of commercial Document Management Systems out there, and they are configurable to the various categories you need to store. They generally also support revision control and archiving. Examples include:</p> <ul> <li><a href="http://www.openedms.com/" rel="nofollow noreferrer">OpenEDMS</a></li> <li><a href="http://www.documentum.com/" rel="nofollow noreferrer">Documentum</a></li> <li><a href="http://www.software-innovation.com/en/pages/default.aspx" rel="nofollow noreferrer">ProArc</a></li> <li><a href="http://www.filehold.com/" rel="nofollow noreferrer">Filehold</a></li> </ul> <p>Also read more here: <a href="http://en.wikipedia.org/wiki/Document_management_system" rel="nofollow noreferrer">Wikipedia article</a></p> <p>A Google search can identify hundreds of offerings, including those from Oracle and IBM.</p>
42,532
<p>If I have a base class such that</p> <pre><code>public abstract class XMLSubscription &lt;T extends XMLMessage&gt; </code></pre> <p>Is it possible to write a method in XMLSubscription that returns a class object of T?</p> <p>The only possible solution that I came up with is to have each descendant of XMLSubscription have a method like:</p> <pre><code>public class XMLStatusSubscription extends XMLSubscription&lt;XMLStatusMessage&gt; { public Class &lt;XMLStatusMessage&gt; getExpectedMessageType() { return XMLStatusMessage.class; } } </code></pre>
<p>Unfortunately - and yes, this is due to type erasure - there is no way to return the <code>Class</code> object without providing it at runtime somehow.</p> <p>Fortunately this is not usually too difficult. Here's how I've typically done this / seen it done:</p> <pre><code>public abstract class XMLSubscription &lt;T extends XMLMessage&gt; { private Class&lt;T&gt; messageType; protected XMLSubscription(Class&lt;T&gt; messageType) { this.messageType = messageType; } public Class&lt;T&gt; getExpectedMessageType() { return this.messageType; } } public class XMLStatusSubscription extends XMLSubscription&lt;XMLStatusMessage&gt; { public XMLStatusSubscription() { super(XMLStatusMessage.class); } } </code></pre>
<p>As you guessed, T is erased by the compiler. When you instantiate the object it has no idea that's it's supposed to deal with <em>XMLStatusMessage</em> objects. Your base class would define the following template method, and 1.5's covariant return types would keep the compiler happy with the concrete subclasses:</p> <pre><code>public Class&lt;T&gt; getExpectedMessageType() </code></pre> <p>There is one meta-comment: this looks a lot like procedural code, where something calls <em>getExpectedMessageType()</em> and then takes action based on the return type. This might be better implemented using a Visitor pattern, with the visitor implementing "doSomething" methods for each of the subclasses of <em>XMLMessage</em>.</p>
47,144
<p>I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't?</p>
<p>I browse with NoScript in Firefox, and it always annoys me when I get pages that don't work. That said - know your audience. If you're trying to cater to paranoid computer security professionals - assume they might not have JavaScript enabled. If you're going for a general audience, JavaScript is probably on.</p>
<p>I think it's fair to assume that the majority of visitors to your site will have JavaScript enabled. Some of the more trafficked sites out there have a dependency on JavaScript. For example, I was surprised to learn that you can't authenticate through a Passport-enabled site without a JS-enabled browser. </p>
18,827
<p>I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang?</p> <p>I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine.</p> <p>It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store. </p>
<p>As things have moved on since the original post on 3by9.com, here are the steps that I had to follow to get the environment working on my PowerBook G4.</p> <p><strong>BTW, I would like to say that I realise that this is not a supported environment and I share this for purely pedagogic rea</strong>sons.</p> <ol> <li>Download and install the iPhoneSDK (final version)</li> <li>After the install finishes, navigate to the packages directory in the mounted DMG</li> <li>Install all of the pkg's that start with iPhone</li> <li>Copy the contents of <code>/Platforms</code> to <code>/Developer/Platforms</code> (should be two folders starting with iPhone)</li> <li>Locate '<code>iPhone Simulator Architectures.xcspec</code>' in <code>/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications</code> and open in a text editor.</li> <li>Change line 12 to: <code>Name = "Standard (iPhone Simulator: i386 ppc)";</code></li> <li>Change line 16 to: <code>RealArchitectures = ( i386, ppc );</code></li> <li>Add the following to line 40 onwards:</li> </ol> <pre> // PowerPC { Type = Architecture; Identifier = ppc; Name = "PowerPC"; Description = "32-bit PowerPC"; PerArchBuildSettingName = "PowerPC"; ByteOrder = big; ListInEnum = NO; SortNumber = 106; }, </pre> <ol start="9"> <li>Save the file and start Xcode</li> <li>You should see under the New Project Folder the ability to create iPhone applications.</li> <li>To get an app to work in the simulator (and using the WhichWayIsUp example) open Edit Project Settings under the Project menu</li> <li>On the Build tab change the Architectures to: Standard (iPhone Simulator:i386 ppc)</li> <li>Change Base SDK to Simulator - iPhone OS 2.0</li> <li>Build and go should now see the app build and run in the simulator</li> </ol>
<blockquote> <p>I have a Powerbook G4 running Leopard and would very much like to do dev on it </p> </blockquote> <p>Not sure what sort of application you are developing, but if you jailbreak your iPhone, you can:</p> <ul> <li>develop applications using Ruby/Python/Java which won't require compiling at all</li> <li>compile on the phone(!), as there is an GCC/Toolchain install in Cydia - although I've no idea how long that'll take, or if you can simply take a regular iPhone SDK project and SSH it to the phone, and run <code>xcodebuild</code>)</li> </ul> <p>You <em>should</em> be able to compile iPhone applications from a PPC machine, as you can compile PPC applications from an Intel Mac, and vice-versa, there shouldn't be any reason you can't compile an ARM binary from PPC.. Wether or not Apple include the necessary stuff with Xcode to allow this is a different matter.. The steps that <a href="http://3by9.com/85/" rel="nofollow noreferrer">Ingmar posted</a> seem to imply you can..?</p>
5,866
<p>I haven't been able to find any documentation on hardware access via the iPhone SDK so far. I'd like to be able to send signals via the dock connector to an external hardware device but haven't seen any evidence that this is accessible via the SDK (not interested in possibilities on jailbroken iPhones).</p> <p>Anyone have any pointers to docs for this or some idea of what deep dark corner i should look?</p>
<p>It will with the new SDK (3.0):</p> <p><a href="http://developer.apple.com/iphone/program/accessories/" rel="nofollow noreferrer">iPhone OS Accessories</a></p> <blockquote> <p>Using iPhone SDK 3.0 your application can communicate with accessories attached to iPhone or iPod touch through either the 30-pin dock connector or wirelessly using Bluetooth.</p> </blockquote>
<p>This falls into the range of capabilities that requires working with Apple to get a special license. At, I presume, a special price.</p> <p>This has changed to some extent with the 3.0 version of the iPhone firmware. If PyjamaSam is correct there is still some special activity required to get the connector specifications.</p>
13,018