instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is it possible to check what version of BPL (ie Rtl70.BPL, Indy70.bpl etc) are installed on a clients computer when the program starts?</p> <p>I have had some programs crash because the BPL on there computer is different to the ones on the build machine.<br> If i have to add each BPL used into the installer on each update, i think it will defeat one of the points on using them.</p> <p>Delphi 7, if it makes a difference</p> <p><hr> Just a follow up on the issue i had.<br> The rtl70.bpl file was only slightly different between the build computer and the clients.</p> <blockquote> <p>Clients Computer: 7.0.4.453 760 KB (778,240 bytes) Tuesday, 20 August 2002, 4:40:26 PM<br> Build computer: 7.0.4.453 760 KB (778,240 bytes) ‎Friday, ‎9 ‎August ‎2002, ‏‎11:30:00 PM</p> </blockquote> <p>The updater i was using ignored them as being the same (no change in build number), but when i manually deleted and copied the files every thing seemed to work.</p>
<p>Unfortunately, no. If the crash is due to missing imports from the .bpl files required by your application, there is no way (short of rewriting the Delphi RTL and linker themselves) to check for those packages from within the crashing executable itself. PatrickvL's solution is probably the best for your situation.</p> <p>Neftalí's solution might be an option - of course, at the cost of packaging the RTL, duplicating a lot of files, and losing one of the points of having packages in the first place. However, if you're using private DLLs (i.e., if you copy the DLLs in your private binaries directory) then you should also create an empty file with the same name as your executable but appending the extension <strong>.local</strong> to it, i.e. for <strong>notepad.exe</strong> you'd create a <strong>notepad.exe.local</strong>. See <a href="http://technet.microsoft.com/en-us/magazine/cc162526.aspx" rel="nofollow noreferrer">Raymond Chen's article on DLL redirection</a> for more details.</p>
<p>Sometimes Delphi adds of automatic form the line:<br> {$R ' *.res'}<br> to the files of project or packages. </p> <p>Comment (//) that line and to compile again. </p>
12,434
<p>I'm looking for a good template on server-side installation of software for a project I'm working on.</p> <p>The client-side is pretty straight-forward. The server-side installation is a little trickier. It is made up of several pieces (services, database connections, dependencies, ports that need to be unblocked, etc.). During a recent test, several undocumented pieces were discovered. Now I need to create installation documentation for our disaster-recovery plans and ways to test the installation without necessarily having a "full-up" system to test on.</p> <p>I'd really like a suggestion of where I can get a template or a really good example of such a document. I'd like it to be something that an operator could read and comprehend in the heat of a recovery.</p> <hr> <p>[EDIT] Our current documentation comes mainly from the questions our administrators have had during off-site tests. As new code is written, I'd like to make sure the documentation is written ahead of time. I've been collecting VMWare images to start testing, but was looking for some good examples. It's a Windows Server shop (2000 &amp; 2003). Word templates would be great, but if I could see good documentation, I could create the templates. Any suggestions about what should be tested would be great as well.</p> <hr> <p>[2nd EDIT] I've gotten several good ideas from the answers posted. After changing my Google search, I came up with some good starting points. They're not perfect, but they are a good start.</p> <p>Microsoft Exchange - <a href="http://technet.microsoft.com/en-us/library/bb125074(EXCHG.65).aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/bb125074(EXCHG.65).aspx</a> iPhone - <a href="http://manuals.info.apple.com/en_US/Enterprise_Deployment_Guide.pdf" rel="nofollow noreferrer">http://manuals.info.apple.com/en_US/Enterprise_Deployment_Guide.pdf</a></p> <p><a href="http://www.novell.com/documentation/gwgateways/gw7_exch/index.html?page=/documentation/gwgateways/gw7_exch/data/ab32nt1.html" rel="nofollow noreferrer">http://www.novell.com/documentation/gwgateways/gw7_exch/index.html?page=/documentation/gwgateways/gw7_exch/data/ab32nt1.html</a> <a href="http://cregan.wordpress.com/2006/06/22/exchange-2003-step-by-step-installation-instructions/" rel="nofollow noreferrer">http://cregan.wordpress.com/2006/06/22/exchange-2003-step-by-step-installation-instructions/</a></p> <p><a href="http://technet.microsoft.com/en-us/magazine/cc160942.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/magazine/cc160942.aspx</a></p> <p>Covers planning in the design stage well - <a href="http://www.onlamp.com/pub/a/onlamp/2004/04/08/disaster_recovery.html?page=2" rel="nofollow noreferrer">http://www.onlamp.com/pub/a/onlamp/2004/04/08/disaster_recovery.html?page=2</a></p> <hr> <p>[Edit 10/29/2008]<br> THIS is the type sample I was looking for. It doesn't have a lot of garbage, but seems to explain enough of the why along with the how <a href="http://wiki.alfresco.com/wiki/Installing_Labs_3_Nile" rel="nofollow noreferrer">http://wiki.alfresco.com/wiki/Installing_Labs_3_Nile</a></p>
<p>The most complete method that we've come up with for creating our DR documentation, involves going through a full cycle (or two) of installation, and documenting each step along the way.</p> <p>I realize this can be a bit difficult if you don't have a test (or replacement) system to use to create your documentation - but it's worth lobbying for running through this cycle at least once.</p> <p>(I recommend twice, the second being done by someone not involved with the project - this is how you test the documentation for future admins, who may not be as experienced with the process.)</p> <p>A side effect of the above is that your documentation grows fairly large - last I had to do it, I believe the completed installation manual for our database servers was 30+ pages.</p>
<p>Depending on the admins, automation is helpful. I've had windows admins that want a Word doc with step by step instructions and other admins that wanted a script.</p> <p>However, some helpful things to include, probably as sections</p> <ul> <li>Database changes <ul> <li>Scripts to run</li> <li>Verification that they worked</li> </ul></li> <li>Configuration changes <ul> <li>what are the change</li> <li>where is a version of the new file (In my case they diffed the two, which helped reduced errors concerning production-specific values)</li> </ul></li> <li>General verification <ul> <li>what should be different from the user perspective (feature changes)</li> </ul></li> <li>For web farm deployments, it might be helpful to have a coordination document concerning how the servers need to be pulled in and out of pool.</li> </ul>
15,208
<p>FYI: I am running on dotnet 3.5 SP1</p> <p>I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder). After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of <code>myDataset.tables(0).Rows(0)("ID")</code>, but it is System.DBNull (despite the fact that the row was inserted).</p> <p>(Note: I do not want to explicitly write a new stored procedure to do this!)</p> <p>One method often posted <a href="http://forums.asp.net/t/951025.aspx" rel="noreferrer">http://forums.asp.net/t/951025.aspx</a> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:</p> <pre><code>SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()" InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord </code></pre> <p>Apparently, this seemed to work for many people in the past, but does not work for me.</p> <p>Another technique: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1</a> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).</p> <p>Does anyone know the answer to this???</p>
<p>This is a problem that I've run into before, the bug seems to be that when you call da.Update(ds); the parameters array of the insert command gets reset to the inital list that was created form your command builder, it removes your added output parameters for the identity.</p> <p>The solution is to create a new dataAdapter and copy in the commands, then use this new one to do your da.update(ds);</p> <p>like</p> <pre><code>SqlDataAdapter da = new SqlDataAdapter("select Top 0 " + GetTableSelectList(dt) + "FROM " + tableName,_sqlConnectString); SqlCommandBuilder custCB = new SqlCommandBuilder(da); custCB.QuotePrefix = "["; custCB.QuoteSuffix = "]"; da.TableMappings.Add("Table", dt.TableName); da.UpdateCommand = custCB.GetUpdateCommand(); da.InsertCommand = custCB.GetInsertCommand(); da.DeleteCommand = custCB.GetDeleteCommand(); da.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText, "; SELECT ",GetTableSelectList(dt)," From ", tableName, " where ",pKeyName,"=SCOPE_IDENTITY()"); SqlParameter identParam = new SqlParameter("@Identity", SqlDbType.BigInt, 0, pKeyName); identParam.Direction = ParameterDirection.Output; da.InsertCommand.Parameters.Add(identParam); da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; //new adaptor for performing the update SqlDataAdapter daAutoNum = new SqlDataAdapter(); daAutoNum.DeleteCommand = da.DeleteCommand; daAutoNum.InsertCommand = da.InsertCommand; daAutoNum.UpdateCommand = da.UpdateCommand; daAutoNum.Update(dt); </code></pre>
<p>Have you looked into using LINQ instead? I understand this doesn't address your actual question, but if you are using .NET 3.5 you really ought to try using LINQ. In fact, with the advent of Code First EntityFramework, I think you could easily choose either LINQ to SQL or EF as relatively lightweight alternatives to rolling your own DAL.</p>
16,523
<p>I get an XML file From a web service. Now I want to get one of those elements out of the file.</p> <p>I think I should go use XPath - any good starter reference?</p>
<p>Not VB specific, but try this: <a href="http://www.w3schools.com/xsl/xpath_intro.asp" rel="nofollow noreferrer">http://www.w3schools.com/xsl/xpath_intro.asp</a></p>
<p>One way would be to only extract the needed informations with an xslt file into a new xml and use this new xml as data basis for further processing</p>
10,737
<p>In OpenSCAD, I am trying to make a linear_extrude on a shape imported from an svg. The svg file contains multiple path. I would like to scale each path separately. I have tried the following code, but the whole import is considered a single shape resulting in the image below.</p> <pre><code>linear_extrude(height = 5, center = true, scale=1.2) import(file = &quot;xxx.svg&quot;, center = true, dpi = 96); </code></pre> <p><a href="https://i.stack.imgur.com/cg1Rq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cg1Rq.png" alt="result" /></a></p> <p>How can I have each of the letters to have 'its own pyramid' ?</p> <p>I know I could create one SVG per letter. But for simplicity sake I would like to have only one SVG file, as I want to create much more complex motives in the future. My final goal is to create stamps from SVG drawings.</p> <p>Edit: Alternative tried after Mick's comment (same result):</p> <pre><code>module pyramidChildren(height){ for ( i= [0:1:$children-1]) linear_extrude(height = height, scale=1.5) children(i); } pyramidChildren(5) import(file = &quot;xxx.svg&quot;, center = true, dpi = 96); </code></pre> <p>I have tried to use the basic svg (multiple paths) and also to group each path (with only itself) without changes in the result.</p>
<p>Lame solution: creating stepped pyramid with offset. I realized that scale will not worked for motives with holes inside. Offset seems then more appropriate than scale for my application (creation of stamps)</p> <p>It takes ages to render, but it could be enough for simple patterns. Any better solution are still welcome...</p> <pre><code>module buildPyramidalExtrude(height,maxOffset,nSlices){ heightIncrement = height/nSlices; offsetIncrement = maxOffset/(nSlices-1); for(i=[1:nSlices]) linear_extrude(height=i*heightIncrement) offset(r = maxOffset-(i-1)*offsetIncrement) children(); } buildPyramidalExtrude(4,2.5,20) import(file = &quot;Farm/cow.svg&quot;, center = true); </code></pre> <p><a href="https://i.stack.imgur.com/pGUnC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pGUnC.png" alt="result" /></a></p>
<p>One option is to use <code>minkowski()</code> to combine the svg with a cone. On the positive side, it gives a rather nice result, but the downsides are:</p> <ul> <li>it's pretty slow</li> <li>it fattens the bottom rather than shrinking the top, so depending on your needs you may have to invert the image, run <code>minkowski</code>, then invert again.</li> </ul> <p>Another option is to convert to grayscale <strong>png and apply a blur</strong> with an external tool, then to import using <code>surface()</code> (the gray blur will become a nice slope). That will both fatten the bottom and shrink the top, but keeping only the top half should give the desired result.</p>
1,810
<p>I want to display the results of a searchquery in a website with a title and a short description. The short description should be a small part of the page which holds the searchterm. What i want to do is: 1 strip tags in page 2 find first position of seachterm 3 from that position, going back find the beginning (if there is one) of that sentence. 4 Start at the found position in step 3 and display ie 200 characters from there</p> <p>I need some help with step 3. I think i need an regex that finds the first capital or dot...</p>
<p>Even that will ultimately fail. Given the sentence "We went to Dr. Smith's office", if your search term is "office", virtually any criterion you use will give you "Smith's office" as your sentence.</p>
<p>To save others from thinking they can beat this problem - it can't be done without accepting either false positives or false negatives. To add to what James Curran said, you either declare <code>Smith</code> the start of the sentence in <code>We went to Dr. Smith's office.</code>, or you read <code>This sentence is English. So is this one.</code> as a single sentence. Next to those problems, different forms of abbreviations and Overeager Capitalization Of Every Word Can Kill Your Algorithm Or Regex.</p> <p>That said, I might as well share the regexes I came up with.</p> <p>The first regex is simple enough:</p> <pre><code>(?m)(?:^|[.!?][\t ]+)([A-Z]\S*) </code></pre> <p>It matches the start of a line or a .!? This is followed by at least one tabs/whitespace, after which a capital letter is matched and the rest of the word (including dots to match abbreviations). The first word of the sentence will be caught in group 1.</p> <p>The second regex</p> <pre><code>(?m)[A-Z]\S*\.[^\S\r\n]+[A-Z]|(?:^|[.!?][\t ]+)([A-Z]\S*) </code></pre> <p>This is the previous regex, prepended with <code>[A-Z]\S*\.[^\S\r\n]+[A-Z]|</code>. This part matches a word starting with a capital, followed by a dot, some whitespace and another capitalized character. Because the first part gets matched, the second part no longer tries to match it (explained in-depth <a href="https://stackoverflow.com/questions/23589174/regex-pattern-to-match-excluding-when-except-between">here</a>). The first word of the sentence will again be caught in group 1.</p> <p>The first regex has false positives: it will wrongly match <code>Smith</code> in the second half of the sentence <code>We went to Dr. Smith's office.</code><br /> The second regex has false negatives: it will fail to match <code>So</code> in <code>This is sentence is English. So is this one.</code></p> <p>Test the regexes <a href="https://regex101.com/r/vxjkmi/1" rel="nofollow noreferrer">here</a>.</p>
23,257
<p>As I've read somewhere it is advised to use !== and === instead.</p>
<p>"Use the strict equality operator (===) when you want to check that the two operands are of the same type and value. Use the regular equality operator (==) if you care only about the value and the type does not matter. If, for example, one operand is the number 5 and the other operand is the string "5", standard equality operator will return true, but, since they are not of the same type, a strict equality operator will return false." <a href="http://www.webreference.com/js/column26/stricteq.html" rel="noreferrer">http://www.webreference.com/js/column26/stricteq.html</a></p>
<p>Personally, in addition to the excellently valid reasons others have stated, I just like knowing that what I'm comparing is exactly what I intend. To me, the difference between the following is important, even though they both evaluate to <code>!myVar</code>:</p> <pre><code>false === myVar 'undefined' === typeof myVar </code></pre>
28,584
<p>Our svn repository has lots of branches that are branches off of sub-trees. This works OK with svn because I can check out that sub-tree in the correct spot in my working copy. However, if I check out the same branch using git, I get a working copy with only the branch sub-tree. Is it possible to make git relocate the branch so that my working copy structure is identical whether I am on trunk or a branch?</p> <p>I realize that our svn practices clash with git's philosophy of always working on the whole tree. How do people deal with this?</p>
<p>If possible, fix it on the server side: Subversion doesn't copy data when branching (<code>svn copy</code>), it just hardlinks, so there's really no obvious reason to branch out only a subtree.</p> <p>If that's not feasible, you should have a look at <a href="http://help.github.com/subtree-merge/" rel="nofollow noreferrer">http://help.github.com/subtree-merge/</a> -- it may do the trick, but I haven't tried it myself. He's basically describing an alternative to git submodules, where you just automatically merge the remote (in this case your Subversion branch) into a subdirectory instead of the root directory of the repository.</p>
<p>I've never used svn like this, and if the silence you've gotten is any indication then it's kind of a rare practice. Could you give some rationale for doing things this way, maybe by describing what problem it solves? That way we can better judge what would be an acceptable solution.</p>
20,918
<p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p> <pre><code>def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: break #i want the loop to stop and return 0 if the #period is bigger than 12 if period&gt;12: #i wrote this line to stop it..but seems it #doesnt work....help.. return 0 else: return period </code></pre>
<p>just indent your code correctly:</p> <pre><code>def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: return period if period&gt;12: #i wrote this line to stop it..but seems its doesnt work....help.. return 0 else: return period </code></pre> <p>You need to understand that the <code>break</code> statement in your example will exit the infinite loop you've created with <code>while True</code>. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the <code>break</code> statement by a <code>return</code> statement.</p> <p>Following your idea to use an infinite loop, this is the best way to write it:</p> <pre><code>def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: break if period&gt;12: #i wrote this line to stop it..but seems its doesnt work....help.. period = 0 break return period </code></pre>
<p>I would do it using a for loop as shown below :</p> <pre><code>def determine_period(universe_array): tmp = universe_array for period in xrange(1, 13): tmp = apply_rules(tmp) if numpy.array_equal(tmp, universe_array): return period return 0 </code></pre>
48,117
<p>I have a master page that contains an ASP.NET server side Menu control (System.Web.UI.WebControls.Menu)</p> <p>I <em>am</em> using the CSSFriendly adapters from here</p> <p><a href="http://www.asp.net/CSSAdapters/Menu.aspx" rel="noreferrer">http://www.asp.net/CSSAdapters/Menu.aspx</a></p> <p>and they do make the rendered HTML much cleaner however I am still getting inline styles output into the HEAD element in the HTML like this</p> <pre><code>&lt;style type="text/css"&gt; .ctl00_SiteHeader1_TabBar1_Menu1_0 { background-color:white;visibility:hidden;display:none;position:absolute;left:0px;top:0px; } .ctl00_SiteHeader1_TabBar1_Menu1_1 { text-decoration:none; } .ctl00_SiteHeader1_TabBar1_Menu1_2 { } .ctl00_LeftColumnContent_LeftHandNavigator1_Menu1_0 { text-decoration:none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; </code></pre> <p>I thik these styles are being generated by ASP.NET, I don't think I need them as I am using the CSSAdapters so is there any way of stopping them from being generated?</p> <p>Derek</p>
<p>The short story is that it isn't <a href="http://forums.asp.net/p/1006669/1336527.aspx" rel="nofollow noreferrer">easily</a> accomplished. That code is added to the header by the menu during the prerender phase. </p> <p>A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer">tagMappings</a>.</p> <p>I'd suggest you stay clear of the menu control if you can.</p>
<p>The short story is that it isn't <a href="http://forums.asp.net/p/1006669/1336527.aspx" rel="nofollow noreferrer">easily</a> accomplished. That code is added to the header by the menu during the prerender phase. </p> <p>A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer">tagMappings</a>.</p> <p>I'd suggest you stay clear of the menu control if you can.</p>
27,365
<p>How can I determine current version of my repository to see if I need to upgrade it (svnadmin upgrade)?</p> <p>In reality I'm hosting SVN with 3rd party and I want to find out if I need to ask them to upgrade my repos or not.</p> <p>I'm asking since 1.5 server will keep repo version at 1.4, unless I miss something?</p>
<p>Have a look at <code>&lt;REPO&gt;/db/format</code>. After upgrading to 1.5 format, my <code>format</code> file shows:</p> <pre><code>3 layout sharded 1000 </code></pre> <p>Before it used to be:</p> <pre><code>2 </code></pre>
<p>I think what you want is "svnlook youngest"</p>
35,771
<p>I know almost nothing about linq.</p> <p>I'm doing this:</p> <pre><code>var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select app; </code></pre> <p>Which gets me all the running processes which match that criteria.</p> <p>But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this</p> <pre><code>var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select app).First(); </code></pre> <p>which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?</p> <p><strong>UPDATE</strong></p> <p>I'm actually trying to find the first matching item, and call <code>SetForegroundWindow</code> on it</p> <p>I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?</p> <pre><code>var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess </code></pre>
<p>@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:</p> <pre><code>var app = Process.GetProcesses().FirstOrDefault(p =&gt; p.ProcessName.Contains("MyAppName") &amp;&amp; p.MainWindowHandle != IntPtr.Zero); if (app == null) return; SetForegroundWindow(app.MainWindowHandle); </code></pre>
<p>Assuming that in your first example apps is an IEnumerable you could make use of the .Count and .FirstOrDefault properties to get the single item that you want to pass to SetForegroundWindow.</p> <pre><code>var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select app; if (apps.Count &gt; 0) { SetForegroundWindow(apps.FirstOrDefault().MainWindowHandle ); } </code></pre>
2,904
<p>We have a huge data of about 300 million records, which will get updated every 3-6 months.We need to query this data(continously, real time) to get some information.What are the options - a RDBMS(mysql) , or some other option like Hadoop.Which will be better?</p>
<p>300M records is well within the bounds of regular relational databases and live querying should be no problem if you use indexes properly.</p> <p>Hadoop sounds like overkill unless you really need highly distributed and redundant data, and it will also make it harder to find support if you run into trouble or for optimizations.</p>
<p>300 million records should pose no problems to a top-end RDBMS like Oracle, SQL Server, DB2. I'm not sure about mySQL, but I'm pretty sure it gets used for some pretty big databases these days.</p>
45,963
<p>When using wireframe fill mode in Direct3D, all rectangular faces display a diagonal running across due to the face being split in to two triangles. How do I eliminate this line? I also want to remove hidden surfaces. Wireframe mode doesn't do this.</p> <p>I need to display a Direct3D model in isometric wireframe view. The rendered scene must display the boundaries of the model's faces but must exclude the diagonals. </p>
<p>Getting rid of the diagonals is tricky as the hardware is likely to only draw triangles and it would be difficult to determine which edge is the diagonal. Alternatively, you could apply a wireframe texture (or a shader that generates a suitable texture). That would solve the hidden line issues, but would look odd as the thickness of the lines would be dependant on z distance.</p> <p>Using line primitives is not trivial, although surfaces facing away from the camera can be easily removed, partially obscured surfaces would require manual clipping. As a final thought, do a two pass approach - the first pass draws the filled polygons but only drawing to the z buffer, then draw the lines over the top with suitable z bias. That would handle the partially obscured surface problem.</p>
<p>I think you'll need to draw those line manually, as wireframe mode is a built in mode, so I don't think you can modify that. You can get the list of vertex in your mesh, and process them into a list of lines that you need to draw. </p>
33,686
<p>I've been struggling with a problem for the past couple days and haven't found a solution.</p> <p>I have an Visual Studio solution with 2 projects, the first one is a DLL with my business objects and logic, the other project is my WinForm application, and a reference dependency on the first project.</p> <p>I initially wrote the business objects with Attribute LINQ mapping and everything was working fine. Then I thought I would try external mapping. I followed a few different guides on how it should work; however, everytime I ran the code in my solution I would get a <em>InvalidOperationException: Mapping Problem: Cannot find type 'Org.Example.System.Material' from mapping</em>, when the WinForm attempts to create the DataContext object.</p> <p>After trying different configurations in the XML file I placed a copy of the class into my GUI solution under a different namespace and it worked. My question is, is it not possible to map an object in a class library or if it is how is it accomplished.</p> <p>Samples</p> <p><strong>dbmap.xml</strong></p> <pre><code>&lt;Database xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007" Name="Gravel_Dev"&gt;&lt;Table Name="dbo.Materials" Member="Material"&gt; &lt;Type Name="Org.Example.System.Material"&gt; &lt;Column Name="MaterialID" Member="MaterialID" Storage="mMaterialID" DbType="UniqueIdentifier NOT NULL" IsDbGenerated="true" IsPrimaryKey="true"/&gt; &lt;Column Name="Code" Member="Code" Storage="mMaterialCode" DbType="Char(4)"/&gt; &lt;Column Name="Description" Member="Description" Storage="mDescription" DbType="VarChar(50)"/&gt; &lt;Column Name="UnitPrice" Member="UnitPrice" Storage="mUnitPrice" DbType="Decimal(5,2)"/&gt; &lt;/Type&gt; </code></pre> <p> </p> <p><strong>WinForm Loading</strong></p> <pre><code>XmlMappingSource mapping = XmlMappingSource.FromUrl("dbmap.xml"); mContext = new DataContext(Properties.Settings.Default.dbConn, mapping); reloadTable(); </code></pre>
<p>I think the problem you might be getting is that the assembly/class library containing your classes hasn't been loaded into memory at this stage?</p> <p>Try accessing a class in the library before instantiating the data context to see if that works.</p>
<p>I have the same problem. We have a mapping file which maps different assemblies and we get the mapping error since all assemplies are not loaded in memory. What are the different solutions to this problem?</p> <p>I have read that is is possible to reference a type in a different assembly using the AssemblyQualifiedName of the type. But we did not get it to work. If this is possible can you give an example of what this would look like?</p> <p>Another solution, I suppose, is to have one mapping file for each assembly and give the datacontext the correct mapping file at runtime.</p>
25,203
<p>With Php when does an included file get included? Is it during a preprocessing stage or is it during script evaluation?</p> <p>Right now I have several scripts that share the same header and footer code, which do input validation and exception handling. Like this:</p> <pre><code>/* validate input */ ... /* process/do task */ ... /* handle exceptions */ ... </code></pre> <p>So I'd like to do something like this</p> <pre><code>#include "verification.php" /* process/do task */ ... #include "exception_handling.php" </code></pre> <p>So if include happens as a preprocessing step, I can do the #include "exception_handling.php" but if not, then any exception will kill the script before it has a chance to evaluate the include.</p> <p>Thanks</p>
<p><a href="http://fi.php.net/include/" rel="nofollow noreferrer">PHP.net: include</a> gives a basic example:</p> <pre><code>vars.php &lt;?php $color = 'green'; $fruit = 'apple'; ?&gt; test.php &lt;?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?&gt; </code></pre> <p>so include happens when its executed in code.</p> <p>Edit: fixed url.</p>
<p>In the order it appears in the code.</p>
44,105
<p>I have the following code in WCF service to throw a custom fault based on certain situations. I am getting a "The creator of this fault did not specify a Reason" exception. What am I doing wrong?</p> <pre><code>//source code if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException&lt;InvalidRoutingCodeFault&gt;(fault); } //operation contract [OperationContract] [FaultContract(typeof(InvalidRoutingCodeFault))] bool MyMethod(); //data contract [DataContract(Namespace="http://myuri.org/Simple")] public class InvalidRoutingCodeFault { private string m_ErrorMessage = string.Empty; public InvalidRoutingCodeFault(string message) { this.m_ErrorMessage = message; } [DataMember] public string ErrorMessage { get { return this.m_ErrorMessage; } set { this.m_ErrorMessage = value; } } } </code></pre>
<p>After some addtional research, the following modified code worked:</p> <pre><code>if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException&lt;InvalidRoutingCodeFault&gt;(fault, new FaultReason("Invalid Routing Code - No Approval Started")); } </code></pre>
<p>You might try this in the server config (behaviors -> serviceBehaviors -> behavior):</p> <pre><code>&lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; </code></pre>
44,391
<p>The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in <b>Python</b>:</p> <pre><code>R=lambda s:all(a==b for a,b in zip(s,reversed(s))) </code></pre> <p>50 characters.</p> <p>The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.</p>
<p>7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)</p> <pre><code>p=:-:|. </code></pre> <p>explanation: |. reverses the input. -: compares. the operands are implicit.</p> <pre><code>p 'radar' 1 p 'moose' 0 </code></pre>
<p>Josh's Java snippet above will return true every time.</p>
28,275
<p>Newbie WiX question: How do I<br> 1. Copy a single-use shell script to temp along with the installer<br> e.g. </p> <pre><code> &lt;Binary Id='permissions.cmd' src='permissions.cmd'/&gt; </code></pre> <p>2. Find and run that script at the end of the install.<br> e.g. </p> <pre><code>&lt;CustomAction Id='SetFolderPermissions' BinaryKey='permissions.cmd' ExeCommand='permissions.cmd' Return='ignore'/&gt; &lt;InstallExecuteSequence&gt; &lt;Custom Action="SetFolderPermissions" Sequence='1'/&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>I think I have at least three problems: </p> <ul> <li>I can't find <strong>permissions.cmd</strong> to run it - do I need <strong>[TEMPDIR]permissions.cmd</strong> or something? </li> <li>My <strong>Sequence</strong> comes too soon, before the program is installed.</li> <li>I need <strong>cmd /c permissions.cmd</strong> somewhere in here, probably near <strong>ExeCommand</strong>?</li> </ul> <p>In this example <strong>permissions.cmd</strong> uses <strong>cacls.exe</strong> to add the interactive user with write permissions to the <strong>%ProgramFiles%\Vendor</strong> ACL. I could also use <strong>secureObject</strong> - that question is <strong><a href="https://stackoverflow.com/questions/170140/how-do-i-add-the-interactive-user-to-a-directory-in-a-localized-windows">"How do I add the interactive user to a directory in a localized Windows"?</a></strong> </p>
<p>I found the blog post <em><a href="http://blogs.technet.com/alexshev/archive/2008/02/21/from-msi-to-wix-part-5-custom-actions.aspx" rel="nofollow noreferrer">From MSI to WiX, Part 5 - Custom actions: Introduction</a></em> helpful when I wanted to understand CustomActions in WiX.</p> <p>You can also find the definition of CustomAction and its attributes in <em><a href="http://wix.sourceforge.net/manual-wix2/wix_xsd_customaction.htm" rel="nofollow noreferrer">CustomAction Element</a></em>.</p> <p>You need to do something like this</p> <pre><code>&lt;CustomAction Id="CallCmd" Value="[SystemFolder]cmd.exe" /&gt; &lt;CustomAction Id="RunCmd" ExeCommand="/c permission.cmd" /&gt; &lt;InstallExecuteSequence&gt; &lt;Custom Action="CallCmd" After="InstallInitialize" /&gt; &lt;Custom Action="RunCmd" After="CallCmd" /&gt; &lt;/InstallExecuteSequence&gt; </code></pre>
<p>Most people tend to steer clear of the lockPermissions table as it is not additive, meaning it will overwrite your current permissions (from a managed environment perspective, this is bad). I would suggest you use a tool which supports <a href="https://en.wikipedia.org/wiki/Access_control_list" rel="nofollow noreferrer">ACL</a> inheritance such as SUBINACL or SETACL or one of the many ACL tools.</p> <p>In relation to why your earlier posts failed there is a few reasons. There are four locations where you can put your custom actions (CAs): UI, Immediate, Deferred, and Commit/Rollback.</p> <p>You need your CA to set permissions in the deferred sequence, because the files are not present until midway through the deferred sequence. As such, anything prior will fail.</p> <ol> <li>Your setup is in immediate (so will fail)</li> <li>Your setup is at sequence of 1 (which is not possible to be deferred so will fail)</li> </ol> <p>You need to add an attribute of <code>Execute="Deferred"</code> and change sequence from "1" to:</p> <pre><code>&lt;Custom Action="CallCmd" Execute="Deferred" Before="InstallFinalize" /&gt; </code></pre> <p>This will ensure it's done after the files are installed, but prior to the end of the deferred phase (the desired location).</p> <p>I would also suggest you call the EXE file directly and not from a batch file. The installer service will launch and the EXE file directly in the context you need. Using a batch file will launch the batch file in the correct context and potentially lose context to an undesired account while executing.</p>
20,534
<p>I have a HTML page that scrolls up and down (not a lot, but it does scroll). How can I set the scroll position in the page after executing some JavaScript?</p> <p>I'm using jQuery to inject some additional HTML at the bottom of the page and I'd like to programmatically scroll to the position of that new content after it's added.</p>
<p>Try using <a href="http://developer.mozilla.org/en/DOM/window.scroll" rel="nofollow noreferrer"><code>window.scroll</code></a>.</p> <blockquote> <p>Example:</p> <pre><code>// put the 100th vertical pixel at the top of the window &lt;button onClick="scroll(0, 100);"&gt;click to scroll down 100 pixels&lt;/button&gt; </code></pre> </blockquote>
<p>Another way to do this, so that you have the option:</p> <p>In the HTML you are adding to the bottom of the page, you can insert a named anchor tag and then change the URL so that the page moves there (FYI: it will not refresh the page).</p> <pre><code>// add HTML like this, dynamically: // &lt;a name="moveHere" /&gt; // the javascript to make the page go to that location: window.location.hash = "moveHere"; </code></pre> <p>Depending on what you are doing, this may or may not be a useful solution. </p>
25,760
<p>I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus:</p> <pre> create user $blah identified by $password; grant resource, connect, create view to $blah; </pre> <p>I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice.</p> <p>Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.</p>
<p>AFAIK you need to do the grants object one at a time.</p> <p>Typically you'd use a script to do this, something along the lines of:</p> <pre><code>SELECT 'GRANT ALL ON '||table_name||' TO BOB;' FROM ALL_TABLES WHERE OWNER = 'ALICE'; </code></pre> <p>And similar for other db objects.</p> <p>You could put a package in each schema that you need to issue the grant from which will go through all call each GRANT statement via an EXECUTE IMMEDIATE.</p> <p>e.g.</p> <pre><code> PROCEDURE GRANT_TABLES IS BEGIN FOR tab IN (SELECT table_name FROM all_tables WHERE owner = this_user) LOOP EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user'; END LOOP; END; </code></pre>
<p>There are many things to consider. When you say access, do you want to prefix the tables with the other users name? You can use public synonyms so that you can hide the original owner, if that is an issue. And then grant privs on the synonym.</p> <p>You also want to plan ahead as best you can. Later, will you want Frank to be able to access Alice's schema as well? You don't want to have to regrant privileges on N number of tables. Using a database role would be a better solution. Grant the select to role "ALICE_TABLES" for example and when another user needs access, just grant them privilege to the role. This helps to organize the grants you make inside the DB.</p>
24,245
<p>What's the object type returned by Datepicker? Supposing I have the following:</p> <pre><code>$("#txtbox").datepicker({ onClose: function(date){ //something } }); </code></pre> <p>What is <code>date</code>? I'm interested in reading the date object from another Datepicker for comparison, something like:</p> <pre><code> function(date){ oDate = $("#oDP").datepicker("getDate"); if(oDate == date) //do one else if(oDate &gt; date) //do two } </code></pre> <p>However, this kind of comparison is not working. I'm guessing there is some sort of comparison method for Date object, but I don't know. I also tried comparing the String representation of the dates like <code>oDate.toString() > date.toString()</code> to no avail.</p>
<p>I just downloaded the source from <a href="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/jquery.datePicker.js" rel="nofollow noreferrer">here</a> and noticed (ex line 600) the author is using .getTime() to compare dates, have you tried that?</p> <pre><code>if (oDate.getTime() &gt; date.getTime()) { ... } </code></pre> <p>Also this is tangential but you mention you tried oDate.toString() while I noticed in the <a href="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html" rel="nofollow noreferrer">examples</a> the author is using .asString()</p>
<blockquote> <p>What is date?</p> </blockquote> <p>it's the $("#txtbox") object</p>
18,662
<p>I've seen it mentioned in many blogs around the net, but I believe it shoud be discussed here. What can we do when we have an MVC framework (I am interested in ZEND) in PHP but our host does not provide mod_rewrite? Are there any "short-cuts"? Can we transfer control in any way (so that a mapping may occur between pages)? Any ideas? Thank you :-)</p>
<p>Zend framework should work without <code>mod_rewrite</code>. If you can live with your URL:s looking more like "/path/to/app/index.php/controller/action". If you had mod_rewrite you could do away with the "index.php" bit, but it should work with too.</p> <p>It's all a matter of setting up the routes to accept the index.php part.</p>
<p>Drupal's rewrite rules translate</p> <p><a href="http://example.com/path/goes/here" rel="nofollow noreferrer">http://example.com/path/goes/here</a></p> <p>into</p> <p><a href="http://example.com/index.php?q=path/goes/here" rel="nofollow noreferrer">http://example.com/index.php?q=path/goes/here</a></p> <p>...and has logic to decide which flavor of URLs to generate. If you can live with ugly URLs, this would let you keep all the logic of a single front controller in place w/o relying on URL rewriting.</p>
3,462
<p>We've got some in-house applications built in MFC, with OpenGL drawing routines. They all use the same code to draw on the screen and either print the screen or save it to a JPEG file. Everything's been working fine in Windows XP, and I need to find a way to make them work on Vista.</p> <p>In three of our applications, everything works. In the remaining one, I can get the window border, title bar, menus, and task bar, but the interior never shows up. As I said, these applications use the exact same code to write to the screen and capture the window image, and the only difference I see that looks like it might be relevant is that the problem application uses the MFC multiple document interface, while the ones that work use the single document interface.</p> <p>Either the answer isn't on the net, or I'm worse at Googling than I thought. I asked on the MSDN forums, and the only practical suggestion I got was to use GDI+ rather than GDI, and that did nothing different. I have tried different things with every part of the code that captures and prints or save, given a pointer to the window, so apparently it's a matter of the window itself. I haven't rebuilt the offending application using SDI yet, and I really don't have any other ideas.</p> <p>Has anybody seen anything like this?</p> <hr> <p>What I've got is four applications. They use a lot of common code, and share the actual .h and .cpp files, so I know the drawing and screen capture code is identical.</p> <p>There is a WindowtoDIB() routine that takes a *pWnd, and a source rectangle and destination size. It looks like very slightly adapted Microsoft code, and I've found other functions in this file on the Microsoft website. Of my four applications, three handle this just fine, but one doesn't. The most obvious difference is that the problem one is MDI.</p> <p>It looks to me like the *pWnd is the problem. I'm not a MFC guru by a long shot, and it seems to me that the problem may be that we've got one window setup in the SDIs, and more than one in the MDI. I may be passing the wrong *pWnd to the function.</p> <p>In the meantime, it has started working properly on the 64-bit Vista test machine, although it still doesn't work on the 32-bit Vista machine. I have no idea why. I haven't changed anything since the last tests, and I didn't think anybody else had. (On the 32-bit version, the Print Screen key works as expected, but it does not save the screen as a JPEG.)</p>
<p>Your question title mentions screen capture but your actual question doesn't. Please elaborate more clearly. Is the problem that you can do screen capture of three of your applications, but not the fourth one? You can use different screen capture software that can capture OpenGL/DirectX windows. Those surfaces are handled directly by the Window Manager and won't show up with a simple 'PrtScn'.</p> <p>Switching to GDI+ won't solve it, nor will switching to SDI.</p>
<p>The contents of each window are directX surfaces and are only assembled by the window manager in the graphics card. You'd not be able to capture this unless you switch off the new interface (DWM) or code specifically for screen capture from the DWM. </p> <p>Wikipedia has a good description of the <a href="http://en.wikipedia.org/wiki/Desktop_Window_Manager" rel="nofollow noreferrer">Desktop Window Manager (DWM)</a></p>
11,252
<p>I use to run</p> <pre><code>$s =~ s/[^[:print:]]//g; </code></pre> <p>on Perl to get rid of non printable characters. </p> <p>In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. </p> <p>What would you do? </p> <p>EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output. curses.ascii.isprint will return false for any unicode character.</p>
<p>Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The <em>unicodedata</em> module is quite helpful for this, especially the <em>unicodedata.category()</em> function. See <a href="http://www.unicode.org/reports/tr44/#General_Category_Values" rel="noreferrer">Unicode Character Database</a> for descriptions of the categories.</p> <pre><code>import unicodedata, re, itertools, sys all_chars = (chr(i) for i in range(sys.maxunicode)) categories = {'Cc'} control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories) # or equivalently and much more efficiently control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0)))) control_char_re = re.compile('[%s]' % re.escape(control_chars)) def remove_control_chars(s): return control_char_re.sub('', s) </code></pre> <p>For Python2</p> <pre><code>import unicodedata, re, sys all_chars = (unichr(i) for i in xrange(sys.maxunicode)) categories = {'Cc'} control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories) # or equivalently and much more efficiently control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0))) control_char_re = re.compile('[%s]' % re.escape(control_chars)) def remove_control_chars(s): return control_char_re.sub('', s) </code></pre> <p>For some use-cases, additional categories (e.g. all from the <em>control</em> group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:</p> <ul> <li><code>Cc</code> (control): 65</li> <li><code>Cf</code> (format): 161</li> <li><code>Cs</code> (surrogate): 2048</li> <li><code>Co</code> (private-use): 137468</li> <li><code>Cn</code> (unassigned): 836601</li> </ul> <p><em><strong>Edit</strong> Adding suggestions from the comments.</em></p>
<p>I used this:</p> <pre><code>import sys import unicodedata # the test string has embedded characters, \u2069 \u2068 test_string = &quot;&quot;&quot;&quot;ABC⁩.⁨ 6&quot;, &quot;}&quot;&quot;&quot; nonprintable = list((ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c) in ['Cc','Cf'])) translate_dict = {character: None for character in nonprintable} print(&quot;Before translate, using repr()&quot;, repr(test_string)) print(&quot;After translate, using repr()&quot;, repr(test_string.translate(translate_dict))) </code></pre>
11,785
<p>Given this data:</p> <pre><code>CREATE TABLE tmpTable( fldField varchar(10) null); INSERT INTO tmpTable SELECT 'XXX' UNION ALL SELECT 'XXX' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'YYY' SELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable </code></pre> <p>The expected resultset is:<br> XXX<br> XXX<br> XXX<br> XXX<br> OTH </p> <p>What situation would casue SQL server 2000 to NOT find 'YYY'? And return the following as the resultset:<br> XXX<br> XXX<br> XXX<br> XXX<br> XXX </p> <p>The problem is with the like 'YYY', I have found other ways to write this to get it to work, but I want to know why this exact method doesn't work. Another difficulty is that it works in most of my SQL Server 2000 environments. I need to find out what is different between them to cause this. Thanks for your help.</p>
<p>Check your service pack. After upgrading my SQL 2000 box to SP4 I now get the correct values for your situation.</p> <p>I'm still getting the swapped data that I reported in my earlier post though :(</p> <p>If you do <code>SELECT @@version</code> you should get 8.00.2039. Any version number less than that and you should install SP4.</p>
<p>You aren't specifying what you are selecting and checking the CASE against...</p> <pre><code>SELECT CASE fldField WHEN 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable </code></pre>
14,239
<p>How do you get a list of files within a directory so each can be processed?</p>
<p>But <code>boost::filesystem</code> can do that: <a href="http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp</a></p>
<pre><code>void getFilesList(String filePath,String extension, vector&lt;string&gt; &amp; returnFileName) { WIN32_FIND_DATA fileInfo; HANDLE hFind; String fullPath = filePath + extension; hFind = FindFirstFile(fullPath.c_str(), &amp;fileInfo); if (hFind == INVALID_HANDLE_VALUE){return;} else { return FileName.push_back(filePath+fileInfo.cFileName); while (FindNextFile(hFind, &amp;fileInfo) != 0){ return FileName.push_back(filePath+fileInfo.cFileName);} } } String optfileName =""; String inputFolderPath =""; String extension = "*.jpg*"; getFilesList(inputFolderPath,extension,filesPaths); vector&lt;string&gt;::const_iterator it = filesPaths.begin(); while( it != filesPaths.end()) { frame = imread(*it);//read file names //doyourwork here ( frame ); sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it-&gt;c_str()); imwrite(buf,frame); it++; } </code></pre>
39,430
<p>When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.</p>
<p>A famous quote come to mind:</p> <p>"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)</p> <p>But maybe you should not pass large data structures by value anyway... :-)</p> <p>Edit: And maybe also avoid <em>O</em>(N^2) or more complex algorithms...</p>
<p>"premature optimization is the root of all evil" (Knuth, Donald)</p> <p>It really depends on the type of code you write and it's typical usage.</p>
40,712
<p>I'd like to create a webpage layout with the sidebar to the right and the main content flowing around the sidebar.</p> <p>Requirements:</p> <ol> <li>Content below the sidebar should occupy all of the available width</li> <li>Content below the sidebar should not wrap when it hits the left of the sidebar</li> <li>Main content should <em>precede</em> the sidebar in the markup</li> <li>Sidebar has fixed width but unknown/variable height</li> <li>CSS-only - no JavaScript solutions</li> </ol> <p>This could be achieved without the third requirement: if the sidebar is before the main content in the markup and is within the same containing element, a simple right float does the job. A sidebar before the main content in the markup is not an option here. The sidebar will contain supplemental information and adverts. If this is before the main content in the markup it will be annoying to CSSless browsers and screenreader users (even with 'skip to ...' links).</p> <p>This could be achieved without the fourth requirement. If the sidebar had a fixed height I could put a containing element before the main content, float it right and give it a suitable width and height and then use absolute positioning to put the sidebar on top of the pre-made space.</p> <p>Example markup (without CSS, relevant bits only):</p> <pre><code>&lt;body&gt; &lt;div id="content"&gt; &lt;p&gt; Lorem ipsum .... &lt;/p&gt; &lt;p&gt; Pellentesque .... &lt;/p&gt; &lt;div id="sidebar"&gt; /* has some form of fixed width */ &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>Example layout:</p> <p><a href="http://webignition.net/images/layoutexample.png">alt text http://webignition.net/images/layoutexample.png</a></p> <p>I'm not sure if this is possible. I'm happy to accept an authoritative answer stating that this cannot be achieved. If this can't be achieved I'd appreciate an explanation - knowing why it can't be achieved is much more valuable than just being told it can't.</p> <p><strong>Update</strong>: I'm happy to see answers that don't meet all of the five requirements, so long as an answer states which requirement is being ignored plus the consequences (pros and cons) of ignoring the requirement. I can then make an informed compromise.</p> <p><strong>Update 2</strong>: I can't ignore requirement 3 - the sidebar cannot precede the content.</p>
<p>Simple floating w/ opposite source order just can't be done (w/o CSS3 draft specs). The pragmatic approach is to first build a nice layout that supports your desired source order. HTML:</p> <pre><code>&lt;div id="content" class="noJs"&gt; &lt;div id="floatSpace"&gt;&lt;/div&gt; &lt;p&gt;Lorem ipsum ....&lt;/p&gt; &lt;p&gt;Pellentesque ....&lt;/p&gt; &lt;div id="sidebar"&gt;content&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#content {position:relative;} #sidebar {width:150px; position:absolute; top:0; right:0;} .noJs {padding-right:150px;} .noJs #floatSpace {display:none;} .js #floatSpace {float:right; width:150px;} </code></pre> <p>This satisfies all but 1 and 2. Now, we add the JS:</p> <pre><code>$(function () { // make floatSpace the same height as sidebar $('#floatSpace').height($('#sidebar').height()); // trigger alternate layout $('#content')[0].className = 'js'; }); </code></pre> <p>This will make the contents float around #floatSpace, and #sidebar will remain positioned on top of it. This is better than moving #sidebar because source order remains the same (for screenreaders that support Javascript, etc.).</p> <p>Here's a <a href="http://jsfiddle.net/wh6oLjy0/" rel="nofollow noreferrer">JSFiddle of this in action</a>. This layout does come with the unfortunate requirement of keeping the floatSpace height in sync with the sidebar height. If the sidebar is dynamic or has lazy-loading content, you must re-sync. </p>
<p>To my knowledge, the only way of getting the sidebar where you want (without the obvious markup reordering) is to set <code>#content { position: relative; }</code> and <code>#sidebar { position: absolute; right: 0; top: 0; }</code></p> <p>Unfortunately, absolute positioning will take the sidebar out of the flowing layout and the content of <code>#content</code> will not avoid <code>#sidebar</code> as you desire.</p>
33,639
<p>Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page:</p> <pre><code>&lt;%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%&gt; &lt;%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%&gt; &lt;%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%&gt; &lt;%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%&gt; </code></pre> <p>I dont like this, I have to build my links with careful consideration to what was posted previously etc.. </p> <p>What I'd like to do is</p> <pre><code>&lt;%=Html.BuildActionLinkUsingCurrentActionPostData ("Next", "Search", new { Page = 1}); </code></pre> <p>where the anonymous dictionary overrides anything currently set by previous action. </p> <p>Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy.</p> <p>Im probably missing something obvious</p>
<p>I had a similar problem inside an HtmlHelper; I wanted to generate links that linked backed to the current page, with a small adjustment in parameters (think incrementing the page number). So if I had URL /Item/?sort=Name&amp;page=0, I wanted to be able to create links to the same page, but just change the page parameter, and have the sort parameter automatically included (ie /Item/?sort=Name&amp;page=1).</p> <p>My solution was this (for use in an HtmlHelper extension method, but since you can access the same data almost anywhere in MVC, you can adapt it easily to your uses):</p> <pre><code>private static RouteValueDictionary CreateRouteToCurrentPage(HtmlHelper html) { RouteValueDictionary routeValues = new RouteValueDictionary(html.ViewContext.RouteData.Values); NameValueCollection queryString = html.ViewContext.HttpContext.Request.QueryString; foreach (string key in queryString.Cast&lt;string&gt;()) { routeValues[key] = queryString[key]; } return routeValues; } </code></pre> <p>What the method does is take the RouteValueDictionary for the current request and create a copy of it. Then it adds each of the query parameters found in the query string to this route. It does this because, for some reason, the current request's RouteValueDictionary does not contain them (you'd think it would, but it doesn't).</p> <p>You can then take the resultant dictionary, modify only a part of it, for example:</p> <pre><code>routeValues["page"] = 2; </code></pre> <p>and then give that dictionary to the out-of-the-box HtmlHelper methods for them to generate you a URL/etc.</p>
<p>take a look on this, it's a good example: <a href="http://nerddinnerbook.s3.amazonaws.com/Part8.htm" rel="nofollow">http://nerddinnerbook.s3.amazonaws.com/Part8.htm</a></p>
14,841
<p>Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:</p> <ol> <li><p>Create a new instance every time we need to generate a key pair</p></li> <li><p>Initialize a static instance and use it for all key pairs</p></li> </ol> <p>Which approach is generally better and <em>why</em>?</p> <p>ADDED: My gut feeling is that the second option is more secure. But my only argument is a theoretical attack based on the assumption that the pseudorandomness is derived from the current timestamp: someone may see the creation time of the key pair, guess timestamps in the surrounding time interval, compute the possible pseudorandom sequences, and obtain the key material.</p> <p>ADDED: My assumption about determinism based on a timestamp was wrong. That's the difference between Random and SecureRandom. So, it looks like the answer is: in terms of security it doesn't really matter.</p>
<p>Unlike the <code>java.util.Random</code> class, the <code>java.security.SecureRandom</code> class must produce non-deterministic output on each call.</p> <p>What that means is, in case of <code>java.util.Random</code>, if you were to recreate an instance with the same seed each time you needed a new random number, you would essentially get the <em>same</em> result every time. However, <code>SecureRandom</code> is guaranteed to NOT do that - so, creating a single instance or creating a new one each time does <em>not</em> affect the randomness of the random bytes it generates.</p> <p>So, from just normal good coding practices view point, why create too many instances when one will do?</p>
<p>Why would you want to create a new instance every time? It's not like that would be <em>more</em> random. I think it would be best to initialize once and use it for all pairs.</p>
37,789
<p>We log values and we only log them once in a table. When we add values to the table we have to do a look up everytime to see if it needs to insert the value or just grab the id. We have an index on the table (not on the primary key) but there are about 350,000 rows (so it is taking 10 seconds to do 10 of these values). </p> <p>So either </p> <ul> <li>We figure out a way to optimize it </li> <li>Strip it this feature out or </li> <li>Do something completely different when logging these values.</li> </ul>
<p>Just to be clear, the index is on the (presumably varchar or nvarchar) field in the table, correct? Not the PK?</p> <p>ok, after your edit: You're doing an indexed lookup on a large (n)varchar text field. Even with the index that can be pretty slow -- you're still doing 2 big string comparisons. I can't really thing of a great way to do this, but some initial SWAGS:</p> <ul><li>compute a hash of the to-be-logged text, and store that in the database for subsequent lookups</li><li>as another poster suggested, store all of the rows, and filter out dupes in the query (or with a nightly batch, whatever</li><li>don't check for duplicates. Catching an exception may still be cheaper than the lookup*</li><li>hire someone with a really good memory who's fast with a mouse. When a message is going to be logged, flash it to their screen with an accept/deny prompt. If the entry is a dupe, ahve them click "deny"</li></ul> <p><br/> * yeah, I know I'll be down-modded for that, but sometimes pragmatism just works.</p>
<p>I'm not sure I have enough informaiton to answer this, but here are some thoughts none the less:</p> <ol> <li>If you are not already doing so you may be able to do the insert and the verfication all in one SQL (insert into table (values) (select lefter outer join to table where id is null)</li> <li>Are you using a DAL layer, or stored procedures to do this? Do you control the SQL used to select/insert? If you don't you may want to user SQL Profiler to examine what is being sent to the DB incase it's format invalidates the index.</li> </ol>
14,265
<p>I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen <a href="http://web.archive.org/web/20100208164146/http://www.spoono.com/html/tutorials/tutorial.php?id=19" rel="noreferrer">the W3C solution</a>, which doesn't even work on Firefox, and <a href="http://web.archive.org/web/20130127125919/http://wiki.novemberborn.net/sifr/How+to+use" rel="noreferrer">this pretty cool solution</a>. The second solution is for titles only. Is there a solution available for full text? I'm tired of the standard fonts for web pages.</p> <p>Thanks!</p>
<p><strong>Things have changed</strong> since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.</p> <p>Paul Irish put together <a href="http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/" rel="noreferrer">Bulletproof @font-face syntax</a> combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.</p> <p>Snipped from his article:</p> <pre><code>@font-face { font-family: 'Graublau Web'; src: url('GraublauWeb.eot'); src: local('Graublau Web Regular'), local('Graublau Web'), url(&quot;GraublauWeb.woff&quot;) format(&quot;woff&quot;), url(&quot;GraublauWeb.otf&quot;) format(&quot;opentype&quot;), url(&quot;GraublauWeb.svg#grablau&quot;) format(&quot;svg&quot;); } </code></pre> <p>Working from that base, <a href="http://www.fontsquirrel.com/" rel="noreferrer">Font Squirrel</a> put together a variety of useful tools including the <a href="http://www.fontsquirrel.com/fontface/generator" rel="noreferrer"><strong>@font-face Generator</strong></a> which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has <a href="http://www.fontsquirrel.com/fontface" rel="noreferrer">Hundreds of @font-face kits</a>.</p> <p>Soma Design also put together the <a href="http://somadesign.ca/projects/fontfriend/" rel="noreferrer">FontFriend Bookmarklet</a>, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.</p> <p>More recently, Google has started to provide the <a href="http://www.google.com/webfonts" rel="noreferrer">Google Web Fonts</a>, an assortment of fonts available under an Open Source license and served from Google's servers.</p> <p><strong>License Restrictions</strong></p> <p>Finally, WebFonts.info has put together a nice wiki'd list of <a href="https://web.archive.org/web/20140713192153/http://www.webfonts.info/fonts-available-font-face-embedding" rel="noreferrer">Fonts available for @font-face embedding</a> based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. <strong>It's important to read the licenses</strong>, because there are some limitations that aren't pushed forward obviously on the font downloads.</p>
<p>And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE. Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism. A list apart had a good discussion about this a while <a href="http://www.alistapart.com/articles/cssatten" rel="nofollow noreferrer">back</a>.</p>
27,118
<p>Our software is built on linux and windows platforms. Depending on the preference of the developer a contribution is developed and tested on either platform and then committed to our subversion repository. It then turns out that the contribution doesn't build on the other platform, and a fix has to be made. The fix on the other platform may again break the build on the original platform, and so on.</p> <p>I'd rather see that a contribution is built (and regression tested) on the other platform as well before being committed. We have a continuous build server (CruiseControl), but that server builds from the repository. I am looking for a solution where the continuous build server builds on the other platform as a pre-commit check and then commits the stuff if the build and test succeed. </p> <p>Any suggestions? </p>
<p>Teamcity handles pre-tested commit, you may be able to do something with the new build chaining features in 4.0( <a href="http://www.jetbrains.com/teamcity/features/newfeatures.html" rel="nofollow noreferrer">http://www.jetbrains.com/teamcity/features/newfeatures.html</a> ). Agents are cross platform and can be configured to only run particular bits of the build, so could possibly be configured to only run a subset of tests.</p> <p>Note that I haven't actually done this :)</p>
<p>We used a custom build and test rig that could remotely deploy to multiple OSes (and multiple Database products on multiple OSes). This was done as a nightly build with a rule that you fix your bugs the next morning. </p> <p>No entirely continuous then, but that's potentially a lot of work to do on a pre-commit hook. Especially if your source control repository locks the affected files for the duration of the pre-commit hook execution.</p> <p>I think there's a difference between a continuous integration test that runs during the day, per-commit, and a system integration test that runs nightly.</p>
42,196
<p>I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..</p> <pre><code>const char *GetString() { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); return ss.str().c_str(); } </code></pre> <p>could the c string be destroyed when ss falls off the stack? I'm assuming so...</p> <p>Another option may be to create a new string on the heap, but what is going to deallocate that?</p> <pre><code>const char *GetString() { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); char *out = new char[ss.str().size()]; strcpy(ss.str().c_str(), out); return out;//is out ever deleted? } </code></pre> <p>The same goes for pointers to other things as well as strings.</p>
<p>The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.</p> <p>Next, you can not return a const char* unless you return a pointer to a static string like this:</p> <pre><code>const char *GetString() { return "a static string in DATA segment - no need to delete"; } </code></pre> <p>You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible.</p> <p>If you return a string to C, there are 2 way to do that:</p> <pre><code>char *GetString() { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); return strdup( ss.str().c_str() ); // allocated in C style with malloc() } void foo() { char *p = GetString(); printf("string: %s", p)); free( p ); // must not forget to free(), must not use delete() } </code></pre> <p>or:</p> <pre><code>char *GetString(char *buffer, size_t len) { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory } void foo() { char buffer[ 100 ]; printf("string: %s", GetString(buffer, sizeof( buffer ))); // no memory leaks } </code></pre> <p>depending on you memory handling policy.</p> <p>As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.</p>
<p>If you declare ss as static you can avoid the problem. This could be a good solution if your program runs on a single-thread enviroment.</p>
35,907
<h2>Context:</h2> <p>A while ago, I stumbled upon this 2001 DDJ article by Alexandrescu: <a href="http://www.ddj.com/cpp/184403799" rel="noreferrer">http://www.ddj.com/cpp/184403799</a></p> <p>It's about comparing various ways to initialized a buffer to some value. Like what "memset" does for single-byte values. He compared various implementations (memcpy, explicit "for" loop, duff's device) and did not really find the best candidate across all dataset sizes and all compilers.</p> <p>Quote:</p> <blockquote> <p>There is a very deep, and sad, realization underlying all this. We are in 2001, the year of the Spatial Odyssey. (...) Just step out of the box and look at us — after 50 years, we're still not terribly good at filling and copying memory.</p> </blockquote> <h2>Question:</h2> <ol> <li>does anyone have more recent information about this problem ? Do recent GCC and Visual C++ implementations perform significantly better than 7 years ago ? <li>I'm writing code that has a lifetime of 5+ (probably 10+) years and that will process arrays' sizes from a few bytes to hundred of megabytes. I can't assume that my choices now will still be optimal in 5 years. What should I do: <ul> <li>a) use the system's memset (or equivalent) and forget about optimal performance or assume the runtime and compiler will handle this for me. <li>b) benchmark once and for all on various array sizes and compilers and switch at runtime between several routines. <li>c) run the benchmark at program initialization and switch at runtime based on accurate (?) data. </ul> </ol> <p>Edit: I'm working on image processing software. My array items are PODs and every millisecond counts !</p> <p>Edit 2: Thanks for the first answers, here are some additional informations:<ul><li>Buffer initialization may represent 20%-40% of total runtime of some algorithms. <li>The platform may vary in the next 5+ years, although it will stay in the "fastest CPU money can buy from DELL" category. Compilers will be some form of GCC and Visual C++. No embedded stuff or exotic architectures on the radar<li>I'd like to hear from people who had to update their software when MMX and SSE appeared, since I'll have to do the same when "SSE2015" becomes available... :) </ul></p>
<p>The DDJ article acknowledges that memset is the best answer, and much faster than what he was trying to achieve:</p> <blockquote> <p>There is something sacrosanct about C's memory manipulation functions memset, memcpy, and memcmp. They are likely to be highly optimized by the compiler vendor, to the extent that the compiler might detect calls to these functions and replace them with inline assembler instructions — this is the case with MSVC.</p> </blockquote> <p>So, if memset works for you (ie. you are initializing with a single byte) then use it. </p> <p>Whilst every millisecond may count, you should establish what percentage of your execution time is lost to setting memory. It is likely very low (1 or 2%??) given that you have useful work to do as well. Given that the optimization effort would likely have a much better rate of return elsewhere.</p>
<p>The year isn't 2001 anymore. Since then, new versions of Visual Studio have appeared. I've taken the time to study the memset in those. They will use SSE for memset (if available, of course). If your old code was correct, <em>statistically</em> if will now be faster. But you might hit an unfortunate cornercase. I expect the same from GCC, although I haven't studied the code. It's a fairly obvious improvement, and an Open-Source compiler. <em>Someone</em> will have created the patch.</p>
20,727
<p>How can I compile/run C or C++ code in a Unix console or a Mac terminal?</p>
<p>If it is a simple single-source program,</p> <pre class="lang-none prettyprint-override"><code>make foo </code></pre> <p>where the source file is <em>foo.c</em>, <em>foo.cpp</em>, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.</p> <p>Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in <code>$PATH</code> to find executables, and most often that does not include the current directory (<code>.</code>).</p> <p>So to run the built executable <code>foo</code>:</p> <pre class="lang-none prettyprint-override"><code>./foo </code></pre>
<p>Running a .C file using the terminal is a two-step process. The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press <kbd>Enter</kbd>:</p> <pre class="lang-none prettyprint-override"><code>gcc /Desktop/test.c </code></pre> <p>In the second step, run the following command:</p> <pre class="lang-none prettyprint-override"><code>~/a.out </code></pre>
27,252
<p>If you have a sequence of block elements and you wanted to place margin in between them. </p> <p>Which do you prefer, margin-top or margin-bottom or both? Why?</p>
<p>I always use <code>margin-bottom</code>, which means there is no unnecessary space before the first element.</p>
<p>Yeah I usually use margin-bottom as well and then assign a last class to the last one in the bunch. Assuming you want a different styling on this.</p> <pre><code>.discussion .detailed.topics { margin: 20px 0 } .discussion .detailed.topics .topic { margin-bottom: 30px } .discussion .detailed.topics .topic.last { margin-bottom: 0 } </code></pre> <p>This is a strong approach when your using dynamically driven content</p> <p>HTML (Razor View Engine)</p> <pre><code>&lt;div class="detailed topics"&gt; @if (Model.ActiveTopics != null &amp;&amp; Model.ActiveTopics.Count &gt; 0) { for (int i = 0; i &lt; Model.ActiveTopics.Count(); i++) { var topic = Model.ActiveTopics[i]; &lt;div class="topic@(i == Model.ActiveTopics.Count - 1 ? " last" : "")"&gt; ... &lt;/div&gt; } } &lt;/div&gt; </code></pre>
36,148
<p>What are my validation options with .net mvc?</p> <p>Do any of them have a nice validation summary like webforms did?</p>
<p>You can use a MVC html validation summary,see this blog</p> <p><a href="http://blog.maartenballiauw.be/post/2008/08/29/Form-validation-with-ASPNET-MVC-preview-5.aspx" rel="noreferrer">http://blog.maartenballiauw.be/post/2008/08/29/Form-validation-with-ASPNET-MVC-preview-5.aspx</a></p>
<p>xVal is the best one. We implemented in three web applications and we will use it in many more in the future(until we find a better one than this). Check the details of xVal here</p> <p><a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/" rel="nofollow noreferrer">http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/</a></p>
28,963
<p>How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?</p>
<pre><code>#include &lt;algorithm&gt; std::reverse(str.begin(), str.end()); </code></pre> <p>This is the simplest way in C++.</p>
<p>If you don't need to store it, you can reduce the time spent like this:</p> <pre><code>void showReverse(char s[], int length) { printf("Reversed String without storing is "); //could use another variable to test for length, keeping length whole. //assumes contiguous memory for (; length &gt; 0; length--) { printf("%c", *(s+ length-1) ); } printf("\n"); } </code></pre>
24,139
<p>I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0.</p> <p>I have a label component, and I'm dynamically assigning it text from an xml document. For example:</p> <pre><code>label.text = "&lt;b&gt;" + xml_node.firstChild + "&lt;/b&gt;"; </code></pre> <p>This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using <code>&lt;font&gt;</code> tags won't work.</p> <p>Am I missing something? How do I make the font larger? ActionScript is just so picky!</p>
<p>When you say "label component", do you mean a Flex 2 label, or a TextField?</p> <p>In the latter case, the font tag should work just fine. will set the font to 24px text for example. If it doesn't, you can use the stylesheet class to specify a font size and then assign it to the TextField.</p> <p>In the case of of Flex 2 label, use label.setStyle("fontSize", 24) to set it to 24px text for example.</p>
<p>I can't say for sure but I think you probably need to set the fontSize style of the Label. </p>
24,812
<p>I've got an NSArrayController, and I'm using KVO to observe the Old/New values of it's selection method.</p> <p>This works perfectly (triggers when the selection changes, the usual) except that the items in the change dictionary are all null instead of being the old/new selected object. [arrayController selection] still returns the proper object, but I'd like to be able to access the previously selected object as well if possible (my workaround will probably be to observe the selected index instead and see if that works).</p> <p>The only possible reason for this I've come up with is perhaps it's because the NSArrayController is a proxy object.</p> <p>So is this the expected behavior, or is something weird going on?</p> <p>EDIT: I tried observing just the Indexes, but that didn't work either. Both old and new keys still show up as null.</p>
<p><a href="http://homepage.mac.com/mmalc/CocoaExamples/controllers.html" rel="nofollow">mmalc's Cocoa bindings page</a> says:</p> <blockquote> <p>The change dictionary doesn't contain old and new values. This is not your fault, it's due to a bug in the controller. This bug will not be fixed in the forseeable future.</p> </blockquote>
<p>For plain KVO (as opposed to bindings), try observing the selectedObjects property instead of the selection property. That will give you a straightforward array of objects instead of the proxy objects which are used by the Cocoa bindings system. I believe the old/new keys should accurately reflect the change in the selection that way.</p>
35,346
<p>What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").</p> <p>I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).</p> <p>For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.</p> <hr> <p>John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.</p> <hr> <p>Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.</p> <p>Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.</p>
<p><a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html" rel="noreferrer">http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html</a></p> <pre><code>asm {trap} ; Halts a program running on PPC32 or PPC64. __asm {int 3} ; Halts a program running on IA-32. </code></pre>
<p>There is also the following function that is available as cross platform straight Halt() alternative:</p> <pre><code>#include &lt;stdlib.h&gt; void abort(void); </code></pre> <p>We use it in our cross platform engine for the iPhone implementation in case of fatal asserts. Cross platform across Nintendo DS/Wii/XBOX 360/iOS etc...</p>
5,794
<p>When we execute <code>select count(*) from table_name</code> it returns the number of rows.</p> <p>What does <code>count(1)</code> do? What does <code>1</code> signify here? Is this the same as <code>count(*)</code> (as it gives the same result on execution)?</p>
<p>The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.)</p> <p>There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained.</p> <p>Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).</p>
<p>Depending on who you ask, some people report that executing <code>select count(1) from random_table;</code> runs faster than <code>select count(*) from random_table</code>. Others claim they are exactly the same.</p> <p>This <a href="http://laurentschneider.com/wordpress/2008/08/what-is-faster-select-count-or-select-countpk.html" rel="nofollow noreferrer">link</a> claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.</p>
21,877
<p>Which search engine would you recommend for a Commerce website?</p> <p>We have millions of products in a catalog and we want it to be as quick as possible.</p> <p>We would also want to make sure that the marketing driven through the search engine will be fast and effective.</p> <p>What are your opinions?</p>
<p>This is only half the answer to your question. I've used it with Java and not .NET. Fast is said to be the better search engine. I don't know. However for Commerce Endeca is considered to be the best. I've used it with a catalog of 5Mil. products and queries are very very fast. If you use .NET or Java does not matter in the end solution the Search Engine stays the same. And what search engine to be used is not answered easily. it all depends on what you want/can spend. My experiences with Endeca are very positive.</p>
<p>Endeca is the best commercial product in my own honest opinion. We've been using it for our millions of catalogs data.</p> <p>Or you can try Lucene.NET</p>
20,563
<p>Is there a way to control the number of displayed rows in a DropDownList control? I'd like it to only display 10 rows, but it defaults to 30. This causes the list to appear higher than the control instead of below it because of its position on the page.</p>
<p>If ASP.NET renders a DropDownList control as a <code>&lt;select&gt;</code> then there is no way to control the number of rows shown when the <code>&lt;select&gt;</code> is opened, it is browser-implementation dependant.</p> <p>A quick test shows that IE 6 reveals 27 items from a 27 item list, Safari for Windows 3.2.1 reveals 22, Firefox 2 reveals 20 and Opera 9.6.2 reveals 16. The number revealed may even depend on the total number of items, but I didn't bother to test that because it is pretty obvious this isn't something you're going to be able to control.</p> <p>Adding <code>size="..."</code> to the control will make the drop-down list a fixed size and it will no longer be a "drop-down list" (assuming you can even do that).</p> <p>The only solution to this seems to be to implement a JavaScript-based pull-down control of your own, or buy or download one.</p>
<p>Note: I have not tried this using code</p> <p>Add "size" attribute with "10" as value to show 10 rows in the dropdown.</p> <pre> &lt;asp:dropdownlist size="10" ...&gt; </pre> <p>Does this work? (I am guessing it,as dropdownlist is SELECT tag in html)</p>
48,304
<p>Trying to understand an fft (Fast Fourier Transform) routine I'm using (stealing)(recycling)</p> <p>Input is an array of 512 data points which are a sample waveform. Test data is generated into this array. fft transforms this array into frequency domain. Trying to understand relationship between freq, period, sample rate and position in fft array. I'll illustrate with examples:</p> <p>========================================</p> <p>Sample rate is 1000 samples/s. Generate a set of samples at 10Hz.</p> <p>Input array has peak values at arr(28), arr(128), arr(228) ... period = 100 sample points</p> <p>peak value in fft array is at index 6 (excluding a huge value at 0) </p> <p>========================================</p> <p>Sample rate is 8000 samples/s Generate set of samples at 440Hz</p> <p>Input array peak values include arr(7), arr(25), arr(43), arr(61) ... period = 18 sample points</p> <p>peak value in fft array is at index 29 (excluding a huge value at 0)</p> <p>========================================</p> <p>How do I relate the index of the peak in the fft array to frequency ?</p>
<p>If you ignore the imaginary part, the frequency distribution is linear across bins:</p> <p>Frequency@i = (Sampling rate/2)*(i/Nbins).</p> <p>So for your first example, assumming you had 256 bins, the largest bin corresponds to a frequency of 1000/2 * 6/256 = 11.7 Hz. Since your input was 10Hz, I'd guess that bin 5 (9.7Hz) also had a big component. To get better accuracy, you need to take more samples, to get smaller bins.</p> <p>Your second example gives 8000/2*29/256 = 453Hz. Again, close, but you need more bins. Your resolution here is only 4000/256 = 15.6Hz.</p>
<p>WaveyDavey says that he's capturing sound from a mic, thru the audio hardware of his computer, BUT that his results are not zero-centered. This sounds like a problem with the hardware. It SHOULD BE zero-centered.</p> <p>When the room is quiet, the stream of values coming from the sound API should be very close to 0 amplitude, with slight +- variations for ambient noise. If a vibratory sound is present in the room (e.g. a piano, a flute, a voice) the data stream should show a fundamentally sinusoidal-based wave that goes both positive and negative, and averages near zero. If this is not the case, the system has some funk going on!</p> <p>-Rick</p>
16,781
<p>I'm using SVN right now, and I've used CVS and VSS in the past. SVN is the current favourite in my books, but I've been hearing a lot about git. Of the people that have used git, what are the pros and cons from your experience?</p>
<p>I don't have a <em>lot</em> of experience with git, but:</p> <p>Pros:</p> <ul> <li>It's really quick</li> <li>Local commits rock</li> <li>Quick to start a new repository (no configuration etc)</li> <li>github is easy to use</li> </ul> <p>(I haven't really "needed" the distributed side of things yet, beyond being able to have a local repository and push to a public one.)</p> <p>Cons:</p> <ul> <li>Windows support is still lagging behind, I believe - and you can't just use it from a normal command prompt</li> <li>Lack of IDE and Explorer integration</li> <li>It took me a while to find a <a href="http://book.git-scm.com/" rel="noreferrer">good introductory text</a> along the lines of the redbean book.</li> <li>The fact that "adding" a changed file only adds the contents at that point of time (so it can show up as staged for commit <em>and</em> still have modifications which require another <code>git add</code>) took a while to grasp</li> </ul>
<p>Pros:</p> <ul> <li>everything mentioned above</li> </ul> <p>Cons:</p> <ul> <li><p>strange behaviour of autocrlf in Windows</p></li> <li><p>impossibility to move/rename file or dir insode repo and kepp its commit history (<strong>git mv</strong> just removes file from repo, renames and adds it to repo again, thus loosing all history)</p></li> </ul>
44,698
<p>We have a Windows Service written in C#. The service spawns a thread that does this: </p> <pre><code>private void ThreadWorkerFunction() { while(false == _stop) // stop flag set by other thread { try { openConnection(); doStuff(); closeConnection(); } catch (Exception ex) { log.Error("Something went wrong.", ex); Thread.Sleep(TimeSpan.FromMinutes(10)); } } } </code></pre> <p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors. </p> <p>This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged.</p> <p>Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back?</p>
<p>Dig in and find out? Stick a debugger on that bastard!</p> <p>I can see at least the following possibilities:</p> <ol> <li>the logging system hangs;</li> <li>the thread exited just fine but the service is still running because some other part has a logic error.</li> </ol> <p>And maybe, but almost certainly not, the following:</p> <ul> <li>Sleep() hangs.</li> </ul> <p>But in any case, attaching a debugger will show you whether the thread is still there and whether it really has hung.</p>
<p>Have you tried using <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx" rel="nofollow noreferrer">Monitor.Pulse</a> (ensure your thread is using thread management before running this) to get the thread to do something? If that works, then you're going to have to look a bit more into your threading logic.</p>
4,965
<p>I'm designing an application which includes the need to log all incoming messages I receive from a Telnet connection. The text is largely plain though can include ANSI tags that provide text colour and formatting (16 colours, bold, underline, etc).</p> <p>I'm would like to format my logs to store the text with formatting, date/time and potentially other meta data later. My first thoughts was all XML but this could impact my ability to write a fast search tool later. My current idea is Date/Time + text in one file with meta-data stored in another XML file, referenced by line number.</p> <p>Is this a good solution? Also, where and how should I store the formatting commands? The original ANSI tags would disrupt the plain but having them in two different files might be awkward.</p> <p>Additional: Thanks to some answers so far, though I should mention that most of the time the messages will be person to person communications rather than system messages. A more primitive IRC of sorts. Its up to my user to decide later (by adding meta data) which messages were important. This is the raw on the record log that filtered or edited logs might derive from.</p>
<p>My first suggestion would be to use a drop-in logging tool like log4net, which will make formatting much more automatic.</p> <p>If you are going to go the route of two files (and I agree with Craig that a database is probably a better choice,) you can probably save yourself a lot of heartache by having one file that is as sparse as you can make it for later fast searches and one that holds all the information in one place (metadata and data) rather than creating a metadata-only format.</p>
<p>If you are catpuring logging information for future searching and anaylsis perhaps a database would be a better answer. </p> <p>As for your solution. Flat files do not scale well at all where as a database scale much better. I wouldn't split the files either, that just compounds the scalability issue. If you have to use a flat file I would probably try keeping the meta data in a csv (less over head) and the data in a series of files indexed by the csv file. That way all the data doesn't impact your index file. Just my thoughts.</p>
7,347
<p>Maybe this is an overarching question as I've seen similar bugs in Firefox and I'd like to know how to avoid coding them.</p> <p>For no apparent reason, the function keys, arrow keys (de-numlocked numpad as well), the 6 keys over the arrows, and backspace stop working. Every other key seems to work leading me to think it's some sort of interrupt issue. It works again when I restart Delphi. </p> <p>This is on an IBM Model M keyboard so certainly it couldn't be a hardware issue, although if someone knows better I won't be that naive, I've noticed this with different keyboards.</p> <p>I'm not actually interested in a fix for Delphi, I just would like to know how to avoid keyboard input bugs. I'm most certainly debugging bug laden code. I just wonder why it causes parts of the keyboard to malfunction.</p>
<p>I doubt that it's Delphi's fault. I'm using Delphi 7 and never had this problem. I suggest you look for another culprit.</p>
<p>If this happens when in the debugger, it is possible that the message processing for a keystroke is failing to be completed. Try pressing all the Alt, shift, control, and all other such keys to see if the issue clears. </p>
21,518
<p>Are they the same thing? If not, what are the differences?</p>
<p>Adobe Shockwave was a media player (formerly by Macromedia), and can be used to run Adobe Director applications (usually in a web browser as a plugin). It has largely been superseded by Adobe Flash (also originally by Macromedia). IIRC, Flash was originally just a new fancy version of Shockwave, usually referred to as Shockwave Flash (which is where it gets confusing). This is why most Flash objects have the SWF extension.</p> <p>Flex is built on top of Flash, and is designed to simplify a few aspects of flash. Think of Flex like a toolkit (à la Qt and GTK) for Flash.</p>
<p>Adding a bit: originally, the Shockwave player was a heavy-duty player intended for CD-ROM interfaces and such things, and Flash was a more light-weight player intended for web-based interfaces. Though SW is not so popular these days, this is still roughly true - feature-wise, Shockwave "supersedes" Flash in that it can play Flash content, as well as do things Flash can't do (like render hardware-accelerated 3D).</p> <p>With that said, while the feature lists differ Flash and Shockwave are equivalent technologies. They're both content players that can stand alone or run as browser plugins.</p> <p>For more on Flex see <a href="https://stackoverflow.com/questions/59083/what-is-adobe-flex-is-it-just-flash-ii#69694">this similar question</a>.</p>
46,035
<p>I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.</p> <p>So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?</p> <pre><code>$database = 'live'; if (some staging environment variable is true) { $database = 'testing'; // and not live } </code></pre> <p>If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile</p> <p>Hope this makes sense</p> <p>many thanks</p> <p>Ian</p>
<p>Yep...you can do this:</p> <pre><code>SetEnv DATABASE_NAME testing </code></pre> <p>and then in PHP:</p> <pre><code>$database = $_SERVER["DATABASE_NAME"]; </code></pre> <p>or</p> <pre><code>$database = getenv("DATABASE_NAME"); </code></pre>
<p>I was also looking at this type of solution. What I found is this, under Apache you can use the <code>SetEnv KeyName DataValue</code> in the http.conf and in IIS you can use Fast CGI Settings >> Edit... >> Environment Variables >> ... and add <code>KeyName, DataValue</code>. </p> <p>This in turn allows the PHP <code>$var = $_SERVER["KeyName"];</code> to be set to the <code>DataValue</code> and used as needed under both IIS and Apache consistently.</p> <p>I know this is a strange use case. I use WAMP at work and MAMP at home so it is nice to be able to work the same way.</p>
17,623
<p>Using ext/ldap I'm trying to add entries to an Active Directory. As long as I only use one single structural objectClass everything works as expected, but as soon as I try to add an entry with a second auxiliary objectClass, the server reports an error:</p> <blockquote> <p>Server is unwilling to perform; 00002040: SvcErr: DSID-030F0AA0, problem 5003 (WILL_NOT_PERFORM), data 0</p> </blockquote> <p>The following code works:</p> <pre><code>ldap_add($ldap, 'OU=Test,OU=Test,DC=domain,DC=example,DC=local', array( 'ou' =&gt; 'Test', 'objectClass' =&gt; 'organizationalUnit', 'l' =&gt; 'location' )); </code></pre> <p>This doesn't:</p> <pre><code>ldap_add($ldap, 'OU=Test,OU=Test,DC=domain,DC=example,DC=local', array( 'ou' =&gt; 'Test', 'associatedDomain' =&gt; 'domain', 'objectClass' =&gt; array('organizationalUnit', 'domainRelatedObject'), 'l' =&gt; 'location' )); </code></pre> <p>The same happens if I try to add an auxiliary objectClass to an existing entry:</p> <pre><code>ldap_mod_add($ldap, 'OU=Test,OU=Test,DC=domain,DC=example,DC=local', array( 'associatedDomain' =&gt; 'domain', 'objectClass' =&gt; 'domainRelatedObject' )); </code></pre> <p>The corresponding error message is essentially the same</p> <blockquote> <p>Server is unwilling to perform; 00002040: SvcErr: DSID-030508F8, problem 5003 (WILL_NOT_PERFORM), data 0</p> </blockquote> <p>As all other updating and adding operations work, I think the problem must be related to the objectClass attribute. </p> <p>As I've not enough experience with Active Directories (I'm used to OpenLDAP): Are there any known issues with objectClasses in Active Directory? Am I missing something here? Are there any restrictions that disallow adding e.g. <code>domainRelatedObject</code> to an <code>organizationalUnit</code>? What the heck 's going on here ;-)?</p> <p><em>Just in case you're wondering: the <code>domainRelatedObject</code> is present in the Active Directory schema.</em></p>
<p>I just found that, in order to add dynamic (per-instance) aux classes, the <a href="http://msdn.microsoft.com/en-us/library/ms676290.aspx" rel="nofollow noreferrer">forest functional level of the domain must be 2003</a>.</p>
<p>You may not have permission to set the objectClass attribute. See whether you can attach the auxiliary class after creation, through <a href="http://technet.microsoft.com/en-us/library/cc773354.aspx" rel="nofollow noreferrer">ADSI Edit</a>. If you can't, fix the permissions first (check the Properties tab in the Advanced view of Security settings)</p> <p>I could attach this specific class right now, onto a organizationalUnit object, as a domain admin; so in principle, this is possible.</p>
48,160
<p>I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons.</p> <p>How do you people overcome this (I'm sure common) problem? I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon.</p> <p>Do you rely on third party designers, in or out of house? Or do you know of some hidden website that offers lots of icons for us to use? I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons.</p> <p>Any help/advice appreciated.</p>
<p>Good icons are hard to design. I have tried to design my own, and have used in-house graphics designers as well. However, building a good icon set takes a lot of work, even for the graphic designer.</p> <p>I believe your best solution is to buy/find a set of icons for use in your projects.</p> <p>The silk icon set is a good, free set and can be found at <a href="http://famfamfam.com/lab/icons/silk/" rel="noreferrer">FamFamFam</a>. There are over 1000 icons in this set, and it is very popular.</p> <p>If you are looking for something "different", you can purchase icon sets for a couple hundred bucks. Considering the cost of having a designer create them for you, or doing them yourself, the cost of these sets is cheap!</p> <p>Here's a few icon designers I've come across of the web:</p> <ul> <li><a href="http://iconfactory.com/stockicons" rel="noreferrer">Icon Factory</a></li> <li><a href="http://www.iconexperience.com/index.php" rel="noreferrer">Icon Experience</a></li> <li><a href="http://www.iconbuffet.com/" rel="noreferrer">Icon Buffet</a></li> </ul>
<p>You can always go on <a href="http://www.elance.com/p/landing/buyer.html" rel="nofollow noreferrer">Elance</a> and hire someone to make any icons/logos for you. I've done it several times and it's pretty cheap for what you're getting. There is so much competition on that site that someone will eventually come in at your price point. I've always believed theres no point in spinning your wheels with something you don't really specialize in.</p> <p>Oh yeah and like this site, keeping it simple is always best!</p>
2,845
<p>I've created a <em>very</em> simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input.</p> <p>I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Windows window, top left of a Mac window) This button currently does nothing.</p> <p>Taking a look at the easygui module I found this line: </p> <pre><code>root.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) </code></pre> <p>This would seem to be the culprit. I'm no TKinter expert but I could probably work out how to alter this handler to act the way I want.</p> <p>However, as I'd rather not mess about with the easygui module, Is there a way to override this behavior from my main script, and have the close button either close the program outright or return None?</p>
<p>It would require altering the easygui module, yes. I will get it modified!</p> <p>** I have sent in a e-mail to the EasyGUI creator explaning this [12:12 PM, January 23/09]</p> <p>** I just want to say that the possibility of this change happening - if at all, which I doubt - is very tiny. You see, EasyGUI is intended to be a simple, discrete way to create GUIs. I think that this addition wouldn't help any, especially since the interface is very sequential, so it would be confusing to new users. [12:19 PM, January 23/09]</p> <p>** The EasyGUI creator said this in reply to my e-mail:</p> <blockquote> <p>An easygui dialog should never exit the application -- it should pass back a value to the caller and let the caller decide what to do.</p> <p>But this is an interesting idea. Rather than simply ignoring a click on the "close" icon, easygui boxes could return the same value that a click on the "cancel" button would return. I'll meditate on this.</p> <p>-- Steve Ferg</p> </blockquote> <p>I think that this is progress at least. [2:40 PM, January 23/09]</p>
<p>I don't know right now, but have you tried something like this?:</p> <pre><code>root.protocol('WM_DELETE_WINDOW', self.quit) </code></pre> <p>or </p> <pre><code>root.protocol('WM_DELETE_WINDOW', self.destroy) </code></pre> <p>I haven't tried, but google something like <code>"Tkinter protocol WM_DELETE_WINDOW"</code></p>
48,801
<p>I got my ender 3 about a month ago, it was working fine. Tried a new brand, overture, this is when I started experiencing problems. First, I was clogging nozzles left and right, then I went back to hatchbox, and my layers are messed up... <a href="https://i.stack.imgur.com/TXuzX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TXuzX.jpg" alt="enter image description here"></a></p>
<p>I wonder if this problem is unrelated to your material or printer, and purely a matter of slicer breakage. Have you tried printing gcode files you created before the problem appeared? If you use Cura and upgraded it, you might have hit one of the bugs where it assumes by default you have 2.85 mm filament, even though your printer actually uses 1.75 mm. That will create underextrusion that has the whole printed object coming apart like an unravelling mummy. When I've seen it happen, it looks very similar to your picture.</p>
<p>Seems like in Movement without displaycement in x and y it seems to fit (neck-area). I also would check your belts. There may be a bit too much friction. Otherwise have you made some Testprints (calibration cube, boat)?</p> <p>Especially the base looks bad. But it is not a cylinder or?</p> <p>If you want, you may show us your 3dModell (rendered)</p>
1,458
<p>How do I download all files in a directory and all subdirectories on an HTTP server?</p>
<p>By using a command-line tool like wget rather than reinventing the wheel.</p>
<p>By using a command-line tool like wget rather than reinventing the wheel.</p>
15,070
<p>How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components? </p>
<p>Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set, though. Other important operations are swapping, assignment and resetting to NULL. Basically, any operation that requires smartness.</p> <p>Note that some of these operations are excluded by some smart pointers. E.g. <code>boost::scoped_ptr</code> cannot even be copied, let alone be assigned. As this leaves less operations, the implementation can be optimized for these fewer methods. </p> <p>In fact, with TR1 coming up, it's quite likely that compilers can do better with smart pointers than raw pointers. E.g. it's possible that a compiler can prove that a smart non-copyable pointer is not aliased in some situations, merely because it's non-copyable. Think about it: aliasing occurs when two pointers are created pointing to the same object. If the first pointer cannot be copied, how would a second pointer end up pointing to the same object? (There are ways around that, too - operator* has to return an lvalue)</p>
<p>Reference-counted smart pointers (the most common type) only cost more when you copy, create and delete them. This extra cost can be substantial if you are copying a lot, because most of them are thread-safe.</p> <p>If you just want an "auto-deleting" pointer, there is the much maligned auto_ptr, or the new and shiny (but not much supported yet) unique_ptr from C++0x.</p>
39,738
<p>I'm trying to change user input in wildcard form <code>("*word*")</code> to a regular expression format. To that end, I'm using the code below to strip off the <code>'*'</code> at the beginning and end of the input so that I can add the regular expression characters on either end:</p> <pre><code>string::iterator iter_begin = expressionBuilder.begin(); string::iterator iter_end = expressionBuilder.end(); iter_end--; if ((char)*iter_begin == '*' &amp;&amp; (char)*iter_end == '*') { expressionBuilder.erase(iter_begin); expressionBuilder.erase(iter_end); expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b"; } </code></pre> <p>However, the call to <code>"expressionBuilder.erase(iter_end)"</code> does <em>not</em> erase the trailing <code>'*'</code> from the input string so I wind up with an incorrect regular expression. What am I doing wrong here? <code>"(char)*iter_end == '*'"</code> must be true for the code inside the if statment to run (which it does), so why doesn't the same iterator work when passed to erase()?</p>
<p>Try erasing them in the opposite order:</p> <pre><code>expressionBuilder.erase(iter_end); expressionBuilder.erase(iter_begin); </code></pre> <p>After erasing the first *, iter_end refers to one character past the end of the string in your example. The <a href="http://www.sgi.com/tech/stl/basic_string.html" rel="nofollow noreferrer">STL documentation</a> indicates that iterators are invalidated by <code>erase()</code>, so technically my example is wrong too but I believe it will work in practice.</p>
<p>Minus the error handling, you could probably just do it like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; string stripStar(const string&amp; s) { return string(s.begin() + 1, s.end() - 1); } int main() { cout &lt;&lt; stripStar("*word*") &lt;&lt; "\n"; } </code></pre>
28,611
<p>The codebase I work on is huge, and grepping it takes about 20 minutes. I'm looking for a good web-based source code search engine.. something like an intranet version of koders.com.</p> <p>The only thing I've found is Krugle Enterprise Edition, which doesn't post its prices... and if you have to ask, you can't afford it.</p> <p>I'd really prefer a plain old search engine, without a lot of other bells and whistles.</p> <p>The source is mostly ASP.NET/C# and Javascript.</p>
<p>20 minutes is outrageous! I'm working with a million+ line source code base these days and grepping takes a few seconds at most (I use <a href="http://petdance.com/ack/" rel="noreferrer">ack</a>). Our home directories are stored on a file server and mounted over NFS, and to speed up grepping we do that while logged in to the file server. I'm not sure how long it takes over NFS, but it's certainly longer.</p> <p>We also do source control operations while logged in to the file server, for the same performance reasons.</p>
<p>Perhaps you should invest some time and/or money in an editor or IDE that supports symbol tagging. You only need to make one pass through the entire source tree to tag it, and thereafter the editor uses an index search or map lookup to find the symbol definition or references.</p> <p>Some examples of editors or IDEs that support tagging are Eclipse, Visual Studio, SlickEdit. Some IDEs might call the feature Symbol Browser or something similar.</p>
13,192
<p>Anyone know how to detect if a television is currently connected to a PC in c#?</p> <p>Cheers</p>
<p>How is the device attached?</p> <p>Whenever a device arrival/removal happens, Windows sends a message called WM_DEVICECHANGE to all the applications running currently in the system. But to receive this message our application should handle the "Windows Process function". C# applications will not have default support for this function, but it's possible to add it. You could extend the form class.</p> <p>The code to do this for a usb mass storage device would be something like:</p> <pre><code>using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; namespace WindowsApplication { /// &lt;summary&gt; /// Summary description for Form1. /// &lt;/summary&gt; public class Form1 : System.Windows.Forms.Form { /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } [StructLayout(LayoutKind.Sequential)] public struct DEV_BROADCAST_VOLUME { public int dbcv_size; public int dbcv_devicetype; public int dbcv_reserved; public int dbcv_unitmask; } protected override void WndProc(ref Message m) { //you may find these definitions in dbt.h and winuser.h const int WM_DEVICECHANGE = 0x0219; const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device const int DBT_DEVICEREMOVECOMPLETE = 0x8001; // system detected a new device const int DBT_DEVTYP_VOLUME = 0x00000002; // logical volume switch(m.Msg) { case WM_DEVICECHANGE: switch(m.WParam.ToInt32()) { case DBT_DEVICEARRIVAL: { int devType = Marshal.ReadInt32(m.LParam,4); if(devType == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME vol; vol = (DEV_BROADCAST_VOLUME) Marshal.PtrToStructure(m.LParam,typeof(DEV_BROADCAST_VOLUME)); MessageBox.Show(vol.dbcv_unitmask.ToString("x")); } } break; case DBT_DEVICEREMOVECOMPLETE: MessageBox.Show("Removal"); break; } break; } //we detect the media arrival event base.WndProc (ref m); } /// &lt;summary&gt; /// Clean up any resources being used. /// &lt;/summary&gt; protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// &lt;summary&gt; /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// &lt;/summary&gt; private void InitializeComponent() { // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { } } } </code></pre> <p>It might give you an idea how to implement it.</p>
<p>I suppose you are talking about monitors/TV's ?</p> <p>You can make a winform application with a big button saying 'TV CONNECTED' when the user switches to the TV :-)</p> <p>If the only connection to the PC is just the VGA connector, you are out of luck. You could always implement an infrared sensor connected to a serial port to read infrared signals from the remote control (whenever the user clicks it).</p>
32,286
<p>C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp?</p> <p>What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?</p>
<p>To boil down your problem, you want to be able to have a class that has a <strong>ushort[,] pixels</strong> field (16-bits per pixel) sometimes and a <strong>uint32[,] pixels</strong> field (32-bits per pixel) some other times. There are a couple different ways to achieve this.</p> <p>You could create replacements for ushort / uint32 by making a Pixel class with 32-bit and 16-bit sub-classes, overriding various operators up the wazoo, but this incurs a lot of overhead, is tricky to get right and even trickier to determine if its right. Alternately you could create proxy classes for your pixel data (which would contain the ushort[,] or uint32[,] arrays and would have all the necessary accessors to be useful). The downside there is that you would likely end up with a lot of special case code in the ImageData class which executed one way or the other depending on some 16-bit/32-bit mode flag.</p> <p>The better solution, I think, would be to sub-class ImageData into 16-bit and 32-bit classes, and use a factory method to create instances. E.g. ImageData is the base class, ImageData16bpp and ImageData32bpp are sub-classes, static method ImageData.Create(string imageFilename) is the factory method which creates either ImageData16bpp or ImageData32bpp depending on the header data. For example:</p> <pre><code>public static ImageData Create(string imageFilename) { // ... ImageDataHeader imageHeader = ParseHeader(imageFilename); ImageData newImageData; if (imageHeader.bpp == 32) { newImageData = new ImageData32(imageFilename, imageHeader); } else { newImageData = new ImageData16(imageFilename, imageHeader); } // ... return newImageData; } </code></pre>
<p>Have your decode function return an object of type Array, which is the base class of all arrays. Then people who care about the type can do "if (a is ushort[,])" and so on if they want to go through the pixels. If you do it this way, you need to allocate the array in ImageData, not the other way around.</p> <p>Alternatively, the caller probably knows what kind of pixel array <em>they</em> want you to use. Even if it's an 8bpp or 16bpp image, if you're decoding it to a 32bpp screen, you need to use uint instead of ushort. So you could write an ImageData function that will decode into integers of whatever type T is.</p> <p>The root of your problem is that you don't know how to decide what kind of output format you want. You need to figure that out first, and the program syntax comes second.</p>
12,306
<ol> <li>Video podcast</li> <li>???</li> <li>Audio only mp3 player</li> </ol> <p>I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.</p> <p>I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.</p> <p>If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. </p> <p>What would you use?</p> <p><b>Edit:</b> I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.</p> <p>Here's my use case: I want to listen to <a href="http://video.google.com/videosearch?q=google+techtalks&amp;so=1&amp;output=rss" rel="nofollow noreferrer">lectures</a> at Google Video, or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>. These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. </p> <p>Here's one approach I'd thought of:</p> <ul> <li>download the RSS</li> <li>parse the RSS for enclosures, </li> <li>download the enclosures, keeping a track what has already been downloaded previously</li> <li>transcode the files, but not the ones done already</li> <li>reconstruct an RSS with the audio files, remembering to change the metadata.</li> <li>schedule to be run periodically</li> <li>point podcatcher at new RSS feed.</li> </ul> <p>I also liked the approach of gPodder of using a <a href="http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook" rel="nofollow noreferrer">post-download script</a>.</p> <p>I wish the <a href="http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html" rel="nofollow noreferrer">Lazy Web</a> still worked.</p>
<p>You could automate this using the open source command line tool ffmpeg. Parse the RSS to get the video files, fetch them over the net if needed, then spit each one out to a command line like this:</p> <pre><code>ffmpeg -i episode1.mov -ab 128000 episode1.mp3 </code></pre> <p>The -ab switch sets the output bit rate to 128 kbits/s on the audio file, adjust as needed. </p> <p>Once you have the audio files you can reconstruct the RSS feed to link to the audio files if so desired.</p>
<p>How to extract audio from video to MP3:</p> <p><a href="http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm" rel="nofollow noreferrer">http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm</a></p> <p>How to Convert a Video Podcast to Audio Only:</p> <p><a href="http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/" rel="nofollow noreferrer">http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/</a></p>
6,781
<p>How can i check (and additionally create) PDF-A 1b compliant PDF documents using open source tools? Does anybody know an open source tool? Thanks in advance...</p>
<p>Try with <a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">http://www.lowagie.com/iText/</a>. It can recognize the version of the loaded PDF and can create PDF as well. It is open source, but I'm not sure do they support exactly the version of the PDF you mention.</p>
<p>Or try <a href="http://www.validatepdfa.com" rel="nofollow noreferrer">www.validatepdfa.com</a> - not open source but 100% free online validator.</p>
11,614
<p>I have recently started working with Unified Communication Managed API 2.0 (UCMA) and Office Communication Server(OCS) 2007. I have a need in my app that I have to create custom presence for my users? Has anyone of you guys done this before and can point me in right direction?</p> <p>There is not much documentation out there regarding this, so I am struggling here.</p> <p>Thanks</p>
<p>A couple options might be:</p> <ol> <li>Use the <a href="http://www.jetbrains.net/confluence/display/TCD4/Simple+Command+Runner" rel="nofollow noreferrer">Simple Command Runner</a> to exec out to something like <a href="http://technet.microsoft.com/en-us/library/bb490994.aspx" rel="nofollow noreferrer">runas</a>, specifying nant.exe running under a different user account. </li> <li>Change the account in which the TeamCity server runs as; like a limited privileged user that has access to DMZ. </li> <li>Attempt to use the <a href="http://nantcontrib.sourceforge.net/release/0.85/help/tasks/scp.html" rel="nofollow noreferrer"><code>&lt;scp</code>></a> (secure copy) task provided by <a href="http://nantcontrib.sourceforge.net/" rel="nofollow noreferrer">NAntContrib</a>.</li> <li>Use the nant <a href="http://nant.sourceforge.net/release/0.85/help/tasks/exec.html" rel="nofollow noreferrer"><code>&lt;exec</code>></a> task to call an ftp program, that places the files up on the DMZ.</li> </ol> <p>Hopefully this provides a little help. Good luck!</p>
<p>you could use powershell remoting to pull releases from the build server. The server would be less vulnerable than if you were to use a push release like a file copy.</p> <p>I'm doing this with a custom app that logs into teamcity and downloads artifacts and then deploys using powershell locally.</p>
44,824
<p>I am trying to write a bash script for testing that takes a parameter and sends it through curl to web site. I need to url encode the value to make sure that special characters are processed properly. What is the best way to do this? </p> <p>Here is my basic script so far:</p> <pre><code>#!/bin/bash host=${1:?'bad host'} value=$2 shift shift curl -v -d "param=${value}" http://${host}/somepath $@ </code></pre>
<p>Use <code>curl --data-urlencode</code>; from <code>man curl</code>:</p> <blockquote> <p>This posts data, similar to the other <code>--data</code> options with the exception that this performs URL-encoding. To be CGI-compliant, the <code>&lt;data&gt;</code> part should begin with a name followed by a separator and a content specification.</p> </blockquote> <p>Example usage:</p> <pre><code>curl \ --data-urlencode &quot;paramName=value&quot; \ --data-urlencode &quot;secondParam=value&quot; \ http://example.com </code></pre> <p>See <a href="https://curl.haxx.se/docs/manpage.html#--data-urlencode" rel="noreferrer">the man page</a> for more info.</p> <p>This requires <a href="https://curl.haxx.se/changes.html#7_18_0" rel="noreferrer">curl 7.18.0 or newer (released January 2008)</a>. Use <code>curl -V</code> to check which version you have.</p> <p>You can as well encode the <a href="https://curl.haxx.se/docs/manpage.html#-G" rel="noreferrer">query string</a>:</p> <pre><code>curl --get \ --data-urlencode &quot;p1=value 1&quot; \ --data-urlencode &quot;p2=value 2&quot; \ http://example.com # http://example.com?p1=value%201&amp;p2=value%202 </code></pre>
<p>The following is based on Orwellophile's answer, but solves the multibyte bug mentioned in the comments by setting LC_ALL=C (a trick from vte.sh). I've written it in the form of function suitable PROMPT_COMMAND, because that's how I use it.</p> <pre><code>print_path_url() { local LC_ALL=C local string="$PWD" local strlen=${#string} local encoded="" local pos c o for (( pos=0 ; pos&lt;strlen ; pos++ )); do c=${string:$pos:1} case "$c" in [-_.~a-zA-Z0-9/] ) o="${c}" ;; * ) printf -v o '%%%02x' "'$c" esac encoded+="${o}" done printf "\033]7;file://%s%s\007" "${HOSTNAME:-}" "${encoded}" } </code></pre>
37,918
<p>I am trying to make a basic API for my website so certain other websites that I approve of can show content from my site. I have a PHP script on my server that the other websites can access to pull content in XML format. How can I make sure that only certain websites can access this php page on my server?</p>
<p>Most APIs that need a similar sort of "authentication" opt for API keys. Just a big long string that gets passed through in the request.</p> <p>You can reinforce that by resolving the domain's IP and checking that against the incoming request. This is slow and expensive so cache IP lookups (but make sure you clean them out as domain IPs do legitimately change!)</p>
<p>Allowing only specific users by IP address is pretty simple with .htaccess.</p> <p>Normally you use it to block specific IP addresses like this</p> <pre><code>Order allow, deny Deny from 192.168.0.10 Deny from 212.155. Deny from 1.2.3.4 5.6.7.8 127.0.0.1 Allow from all </code></pre> <p>But you can also use it to only allow access from specific users, like this</p> <pre><code>Deny from all Allow from 1.2.3.4 </code></pre> <p><strong>EDIT:</strong> If you absolutely need to do this from a script (upon second careful reading of your question, I think you do), then you can do it like this.</p> <pre><code>&lt;? $allowed[0]="xxx.xxx.xxx.xxx"; $allowed[1]="yyy.yyy.yyy.yyy"; // add as many as you need if (!in_array($_SERVER['REMOTE_ADDR'],$allowed)) header("HTTP/1.1 403 Forbidden"); ?&gt; </code></pre>
34,702
<p>I have an application that detects if there is another instance of the app running and exits if one is found. This part seems to work reliably. My app takes a command-line argument that I would like to pass to the already running instance. I have the following code so far:</p> <h2>Project1.dpr</h2> <pre><code>program Project1; uses ... AppInstanceControl in 'AppInstanceControl.pas'; if not AppInstanceControl.RestoreIfRunning(Application.Handle) then begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TFormMain, FormMain); Application.Run; end; end. </code></pre> <h2>AppInstanceControl.pas</h2> <p>{ Based on code by Zarko Gajic found at <a href="http://delphi.about.com/library/code/ncaa100703a.htm" rel="noreferrer">http://delphi.about.com/library/code/ncaa100703a.htm</a>}</p> <pre><code>unit AppInstanceControl; interface uses Windows, SysUtils; function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean; implementation uses Messages; type PInstanceInfo = ^TInstanceInfo; TInstanceInfo = packed record PreviousHandle: THandle; RunCounter: integer; end; var UMappingHandle: THandle; UInstanceInfo: PInstanceInfo; UMappingName: string; URemoveMe: boolean = True; function RestoreIfRunning(const AAppHandle: THandle; const AMaxInstances: integer = 1): boolean; var LCopyDataStruct : TCopyDataStruct; begin Result := True; UMappingName := StringReplace( ParamStr(0), '\', '', [rfReplaceAll, rfIgnoreCase]); UMappingHandle := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, SizeOf(TInstanceInfo), PChar(UMappingName)); if UMappingHandle = 0 then RaiseLastOSError else begin if GetLastError &lt;&gt; ERROR_ALREADY_EXISTS then begin UInstanceInfo := MapViewOfFile(UMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, SizeOf(TInstanceInfo)); UInstanceInfo^.PreviousHandle := AAppHandle; UInstanceInfo^.RunCounter := 1; Result := False; end else //already runing begin UMappingHandle := OpenFileMapping( FILE_MAP_ALL_ACCESS, False, PChar(UMappingName)); if UMappingHandle &lt;&gt; 0 then begin UInstanceInfo := MapViewOfFile(UMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, SizeOf(TInstanceInfo)); if UInstanceInfo^.RunCounter &gt;= AMaxInstances then begin URemoveMe := False; if IsIconic(UInstanceInfo^.PreviousHandle) then ShowWindow(UInstanceInfo^.PreviousHandle, SW_RESTORE); SetForegroundWindow(UInstanceInfo^.PreviousHandle); end else begin UInstanceInfo^.PreviousHandle := AAppHandle; UInstanceInfo^.RunCounter := 1 + UInstanceInfo^.RunCounter; Result := False; end end; end; end; if (Result) and (CommandLineParam &lt;&gt; '') then begin LCopyDataStruct.dwData := 0; //string LCopyDataStruct.cbData := 1 + Length(CommandLineParam); LCopyDataStruct.lpData := PChar(CommandLineParam); SendMessage(UInstanceInfo^.PreviousHandle, WM_COPYDATA, Integer(AAppHandle), Integer(@LCopyDataStruct)); end; end; (*RestoreIfRunning*) initialization finalization //remove this instance if URemoveMe then begin UMappingHandle := OpenFileMapping( FILE_MAP_ALL_ACCESS, False, PChar(UMappingName)); if UMappingHandle &lt;&gt; 0 then begin UInstanceInfo := MapViewOfFile(UMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, SizeOf(TInstanceInfo)); UInstanceInfo^.RunCounter := -1 + UInstanceInfo^.RunCounter; end else RaiseLastOSError; end; if Assigned(UInstanceInfo) then UnmapViewOfFile(UInstanceInfo); if UMappingHandle &lt;&gt; 0 then CloseHandle(UMappingHandle); end. </code></pre> <h2>and in the main form unit:</h2> <pre><code>procedure TFormMain.WMCopyData(var Msg: TWMCopyData); var LMsgString: string; begin Assert(Msg.CopyDataStruct.dwData = 0); LMsgString := PChar(Msg.CopyDataStruct.lpData); //do stuff with the received string end; </code></pre> <p>I'm pretty sure the problem is that I'm trying to send the message to the handle of the running app instance but trying to process the message on the main form. I'm thinking I have two options here:</p> <p>A) From the application's handle somehow get the handle of its main form and send the message there.</p> <p>B) Handle receiving the message at the application rather than the main form level.</p> <p>I'm not really sure how to go about either. Is there a better approach?</p> <p>Thanks.</p>
<p>You don't need to create a file mapping if you use WM_COPYDATA. That's the whole point of WM_COPYDATA - it does all that for you.</p> <p>To send a string</p> <pre><code>procedure IPCSendMessage(target: HWND; const message: string); var cds: TCopyDataStruct; begin cds.dwData := 0; cds.cbData := Length(message) * SizeOf(Char); cds.lpData := Pointer(@message[1]); SendMessage(target, WM_COPYDATA, 0, LPARAM(@cds)); end; </code></pre> <p>To receive a string</p> <pre><code>procedure TForm1.WMCopyData(var msg: TWMCopyData); var message: string; begin SetLength(message, msg.CopyDataStruct.cbData div SizeOf(Char)); Move(msg.CopyDataStruct.lpData^, message[1], msg.CopyDataStruct.cbData); // do something with the message e.g. Edit1.Text := message; end; </code></pre> <p>Modify as needed to send other data. </p>
<p>Why don't you use DDE? Take a look at the links returned by this search: <a href="http://www.google.com/search?q=delphi+dde" rel="nofollow noreferrer">http://www.google.com/search?q=delphi+dde</a></p>
27,179
<p>Wwhen I click the button on the popup to insert data to database, it does nothing, WHYYYYY?</p> <pre><code>&lt;cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" BehaviorID="popup" TargetControlID="cmdTrigger" PopupControlID="pnlPopup" BackgroundCssClass="modalBackground" OkControlID="btnOk" &gt; &lt;/cc1:ModalPopupExtender&gt; &lt;asp:Panel ID="pnlPopup" runat="server" CssClass="modalpopup" Style="display: none"&gt; &lt;div class="container"&gt; &lt;div class="header"&gt; &lt;asp:Label ID="Label1" runat="server" CssClass="msg" Text="Add a new Entry" /&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" CssClass="close" OnClientClick="$find('popup').hide(); return false;" /&gt; &lt;/div&gt; &lt;div class="body"&gt; &lt;asp:Label ID="Label2" runat="server" CssClass="msg" Text="Name" /&gt; &lt;asp:TextBox ID="txtName" runat="server" Width="346px"&gt;&lt;/asp:TextBox&gt; &lt;/div&gt; &lt;div class="footer"&gt; &lt;asp:Button ID="btnOk" runat="server" Text="Save" Width="48px" /&gt; &lt;asp:Button ID="btnCancel" runat="server" Text="Cancel" Width="50px" OnClientClick="$find('popup').hide(); return false;" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/asp:Panel&gt; </code></pre> <p>The code on the btnOK is</p> <p>a simple textbox1.text = txtName</p> <p>I even tries setting a breakpoint, the button click event is not being executed. Any ideas?</p> <p>Edit ~ Solution</p> <blockquote> <p>Follow <a href="http://forums.asp.net/t/1070213.aspx" rel="nofollow noreferrer">http://forums.asp.net/t/1070213.aspx</a></p> </blockquote>
<p>Remove the OkControlId property as I think it prevents a postback from occuring.</p>
<p>Remove <code>CausesValidation="false"</code> either make it true. It will work.</p>
37,634
<p>I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. </p> <p>I've placed the validator code in the <code>ascx</code> file, and I have also tried using <code>Page.ClientScript.RegisterClientScriptBlock()</code> and in both cases the validation fires, but cannot find the JavaScript function.</p> <p>The output in Firefox's error console is <code>"feeAmountCheck is not defined"</code>. Here is the function (this was taken directly from firefox->view source)</p> <pre><code>&lt;script type="text/javascript"&gt; function feeAmountCheck(source, arguments) { var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue'); var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid'); if (amountDue.value &gt; 0 &amp;&amp; amountDue &gt;= amountPaid) { arguments.IsValid = true; } else { arguments.IsValid = false; } return arguments; } &lt;/script&gt; </code></pre> <p>Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?</p>
<p>Try changing the argument names to <code>sender</code> and <code>args</code>. And, after you have it working, switch the call over to <code>ScriptManager.RegisterClientScriptBlock</code>, regardless of AJAX use.</p>
<p>While I would still like an answer to why my javascript wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an <code>Asp:CompareValidator</code> instead of an <code>Asp:CustomValidator</code>.</p>
2,380
<p>I'm porting a relatively simple console program written for Unix to the Windows platform (<a href="http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions" rel="noreferrer">Visual C++ 8.0</a>). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about misssing prototypes for 'srandom', 'random', and 'getopt'. I know I can replace the random functions, and I'm pretty sure I can find/hack-up a getopt implementation. </p> <p>But I'm sure others have run into the same challenge. My question is: is there a port of "unistd.h" to Windows? At least one containg those functions which do have a native Windows implementation - I don't need pipes or forking.</p> <p><strong>EDIT</strong>:</p> <p>I know I can create my very own "unistd.h" which contains replacements for the things I need - especially in this case, since it is a limited set. But since it seems like a common problem, I was wondering if someone had done the work already for a bigger subset of the functionality.</p> <p>Switching to a different compiler or environment isn't possible at work - I'm stuck with Visual Studio.</p>
<p>Since we can't find a version on the Internet, let's start one here.<br> Most ports to Windows probably only need a subset of the complete Unix file.<br> Here's a starting point. Please add definitions as needed.</p> <pre><code>#ifndef _UNISTD_H #define _UNISTD_H 1 /* This is intended as a drop-in replacement for unistd.h on Windows. * Please add functionality as neeeded. * https://stackoverflow.com/a/826027/1202830 */ #include &lt;stdlib.h&gt; #include &lt;io.h&gt; #include &lt;getopt.h&gt; /* getopt at: https://gist.github.com/ashelly/7776712 */ #include &lt;process.h&gt; /* for getpid() and the exec..() family */ #include &lt;direct.h&gt; /* for _getcwd() and _chdir() */ #define srandom srand #define random rand /* Values for the second argument to access. These may be OR'd together. */ #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ #define access _access #define dup2 _dup2 #define execve _execve #define ftruncate _chsize #define unlink _unlink #define fileno _fileno #define getcwd _getcwd #define chdir _chdir #define isatty _isatty #define lseek _lseek /* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */ #ifdef _WIN64 #define ssize_t __int64 #else #define ssize_t long #endif #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* should be in some equivalent to &lt;sys/types.h&gt; */ typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif /* unistd.h */ </code></pre>
<p>Create your own unistd.h header and include the needed headers for function prototypes.</p>
44,428
<p>How is it possible to make prototype methods in C#.Net?</p> <p>In JavaScript, I can do the following to create a trim method for the string object:</p> <pre><code>String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } </code></pre> <p>How can I go about doing this in C#.Net?</p>
<p>You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.</p> <p>You can, however, in C# 3.0, use extension methods, which <em>look</em> like new methods, but are compile-time magic.</p> <p>To do this for your code:</p> <pre><code>public static class StringExtensions { public static String trim(this String s) { return s.Trim(); } } </code></pre> <p>To use it:</p> <pre><code>String s = " Test "; s = s.trim(); </code></pre> <p>This looks like a new method, but will compile the exact same way as this code:</p> <pre><code>String s = " Test "; s = StringExtensions.trim(s); </code></pre> <p>What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?</p>
<p>You need to create an extension method, which requires .NET 3.5. The method needs to be static, in a static class. The first parameter of the method needs to be prefixed with "this" in the signature.</p> <pre><code>public static string MyMethod(this string input) { // do things } </code></pre> <p>You can then call it like</p> <pre><code>"asdfas".MyMethod(); </code></pre>
2,658
<p>I am trying to come up with a best practices on project directory structure.</p> <p>my latest thought is that there should be no classes in the root directory of a project. All classes must go under one of the following directories</p> <ul> <li>UI </li> <li>BusinessObjects</li> <li>BusinessLogic</li> <li>DataAccess</li> </ul> <p>i would like to hear other people thought on if there are use cases for putting things at the root level or find classes that wouldn't fit into</p>
<p>If you're talking about C# then I would separate your DAL, BLL, GUI to different projects instead of one project. And have one solution. This will force each code file to be inside of one of the projects. </p> <p>I've added an example:</p> <ul> <li>Solution: ProjectName <ul> <li>Project: DAL (Namespace: ProjectName.DAL) <ul> <li>Folder: Repositories (Namespace: ProjectName.DAL.Repositories)</li> <li>Folder: Contracts (Namespace: ProjectName.DAL.Contracts)</li> <li>Files: Your Entity Mapping configuration</li> </ul></li> <li>Project: BLL (Namespace: ProjectName.BLL) <ul> <li>Folder: Services (Namespace: Project.BLL.Services)</li> <li>Folder: Entities (Namespace: Project.BLL.Entities)</li> <li>Files: IoC configuration classes/general Business Logic</li> </ul></li> <li>Project: Shared (Namespace: ProjectName.Shared) <ul> <li>Files: General shared logic throught your whole application (for instance an InvalidIdentifier constant)</li> <li>This project should not reference other projects in the solution..</li> </ul></li> <li>Project: Website (Namespace: ProjectName.Website) <ul> <li>Your asp.net website UI</li> </ul></li> <li>Project: Winforms (Namespace: ProjectName.Winforms) <ul> <li>Your winforms UI</li> </ul></li> </ul></li> </ul> <p>If possible you should give the website and winforms project a name relative to your application.</p>
<p>The only files I put into root folder are <strong>Program.cs</strong> and <strong>Program.ico</strong> (if it's executable application).</p>
40,116
<p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p> <pre><code>import sys import poplib import string import StringIO, rfc822 import datetime import logging def _dump_pop_emails(self): self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1])) self.popinstance = poplib.POP3(self.account[0]) self.logger.info(self.popinstance.getwelcome()) self.popinstance.user(self.account[1]) self.popinstance.pass_(self.account[2]) try: (numMsgs, totalSize) = self.popinstance.stat() for thisNum in range(1, numMsgs+1): (server_msg, body, octets) = self.popinstance.retr(thisNum) text = string.join(body, '\n') mesg = StringIO.StringIO(text) msg = rfc822.Message(mesg) name, email = msg.getaddr("From") emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml") emailpath = self._replace_whitespace(emailpath) file = open(emailpath,"wb") file.write(text) file.close() self.popinstance.dele(thisNum) finally: self.logger.info(self.popinstance.quit()) def _replace_whitespace(self,name): name = str(name) return name.replace(" ", "_") </code></pre> <p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p> <p>Basically I want to write the email to the inbox directory in a standard way.</p> <p>Am i doing something wrong here?</p>
<p>I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines?</p> <p>A few notes:</p> <ol> <li>Instead of <code>logger.info ("foo %s %s" % (bar, baz))</code>, use <code>"foo %s %s", bar, baz</code>. This avoids the overhead of string formatting if the message won't be printed.</li> <li>Put a <code>try...finally</code> around opening <code>emailpath</code>.</li> <li>Use <code>'\n'.join (body)</code>, instead of <code>string.join (body, '\n')</code>.</li> <li>Instead of <code>msg.getaddr("From")</code>, just <code>msg.From</code>.</li> </ol>
<p>Further to my comment on John's answer</p> <p>I found out what the issue was, there were illegal characters in the name field and Subject field, which caused python to get the hiccups, as it tried to write the email as a directory, after seeing ":" and "/".</p> <p>John point number 4 doesnt work! so I left it as before. Also is point no 1 correct, have I implemented your suggestion correctly?</p> <pre><code>def _dump_pop_emails(self): self.logger.info("open pop account %s with username: %s", self.account[0], self.account[1]) self.popinstance = poplib.POP3(self.account[0]) self.logger.info(self.popinstance.getwelcome()) self.popinstance.user(self.account[1]) self.popinstance.pass_(self.account[2]) try: (numMsgs, totalSize) = self.popinstance.stat() for thisNum in range(1, numMsgs+1): (server_msg, body, octets) = self.popinstance.retr(thisNum) text = '\n'.join(body) mesg = StringIO.StringIO(text) msg = rfc822.Message(mesg) name, email = msg.getaddr("From") emailpath = str(self._emailpath + self._inboxfolder + "\\" + self._sanitize_string(email + " " + msg.getheader("Subject") + ".eml")) emailpath = self._replace_whitespace(emailpath) print emailpath file = open(emailpath,"wb") file.write(text) file.close() self.popinstance.dele(thisNum) finally: self.logger.info(self.popinstance.quit()) def _replace_whitespace(self,name): name = str(name) return name.replace(" ", "_") def _sanitize_string(self,name): illegal_chars = ":", "/", "\\" name = str(name) for item in illegal_chars: name = name.replace(item, "_") return name </code></pre>
27,764
<ol> <li>A client is going to request 1K rows of IDs from the server.</li> <li>I have to make sure we have 1K ID's with clientID = -1, if not, I have to insert 1K new ID's into the table.</li> <li>I then have to link those 1K ID's with the clientID</li> <li>return reserved 1K ID's to the client.</li> </ol> <p>Is it as simple as wrapping all of this into a Transaction?</p>
<p>You want to add a second table that holds the available IDs, like this:</p> <p>AssignedIdsByClient:</p> <ul> <li><p>AssignedId int identity</p></li> <li><p>ClientId int - the customer you gave this ID range to</p></li> </ul> <p>But when you need 1,000 ID's, don't insert 1,000 records into here: instead, take this AssignedID and multiply it times 1,000. So for example, if someone gets AssignedID 15, that means they own IDs from 15,000 to 15,999 in the other table where you actually need the ID's.</p> <p>Otherwise, if you're trying to insert 1,000 records in a single transaction every time somebody wants an ID range, you're going to have a concurrency nightmare.</p>
<p>Yes, you could wrap these all within a single transaction, and other clients will not be able to see them until you commit.</p>
36,565
<p>There should be something akin to <code>\w</code> that can match any code-point in Letters or Marks category (not just the ASCII ones), and hopefully have filters like [[P*]] for punctuation, etc.</p>
<h2>Situation for ES 6</h2> <p>The ECMAScript language specification, edition 6 (also commonly known as ES2015), includes Unicode-aware regular expressions. Support must be enabled with the <code>u</code> modifier on the regex. See <a href="https://mathiasbynens.be/notes/es6-unicode-regex" rel="nofollow noreferrer"><em>Unicode-aware regular expressions in ES6</em></a> for a break-down of the feature and some caveats.</p> <p>ES6 is widely adopted in both browsers and stand-alone Javascript runtimes such as Node.js, so using this feature won't require extra effort in most cases. Full compatibility list: <a href="https://kangax.github.io/compat-table/es6/" rel="nofollow noreferrer">https://kangax.github.io/compat-table/es6/</a></p> <h2>Situation for ES 5 and below (legacy browsers)</h2> <p>There is <a href="http://mths.be/regexpu" rel="nofollow noreferrer">a transpiler named <em>regexpu</em></a> that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. <a href="http://mothereff.in/regexpu" rel="nofollow noreferrer">Try it out online.</a>.</p> <p>Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.</p> <ul> <li><p><a href="https://mathiasbynens.be/notes/javascript-unicode#regex" rel="nofollow noreferrer">Issues with Unicode in JavaScript regular expressions</a></p> </li> <li><p>Check your expectations here: <a href="http://hamstersoup.com/javascript/regexp_character_class_tester.html" rel="nofollow noreferrer">Javascript RegExp Unicode Character Class tester</a> (<em>Edit:</em> the original page is down, <a href="http://web.archive.org/web/20101104085449/http://hamstersoup.com/javascript/regexp_character_class_tester.html" rel="nofollow noreferrer">the Internet Archive still has a copy</a>.)</p> </li> <li><p>Flagrant Badassery has an article on <a href="http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode" rel="nofollow noreferrer">JavaScript, Regex, and Unicode</a> that sheds some light on the matter.</p> </li> <li><p>Also read <a href="https://stackoverflow.com/questions/14389/">Regex and Unicode</a> here on SO. Probably you have to build your own &quot;punctuation character class&quot;.</p> </li> <li><p>Check out the <a href="http://kourge.net/projects/regexp-unicode-block" rel="nofollow noreferrer">Regular Expression: Match Unicode Block Range</a> builder (<a href="https://web.archive.org/web/20191219033259/http://kourge.net/projects/regexp-unicode-block" rel="nofollow noreferrer">archived copy</a>), which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.</p> <p>I just did it for the &quot;General Punctuation&quot; and &quot;Supplemental Punctuation&quot; sub-ranges, and the result is as simple and straight-forward as I would have expected it:</p> <pre><code> [\u2000-\u206F\u2E00-\u2E7F] </code></pre> </li> <li><p>There also is <a href="http://xregexp.com/" rel="nofollow noreferrer">XRegExp</a>, a project that brings <a href="http://xregexp.com/plugins/#unicode" rel="nofollow noreferrer">Unicode support to JavaScript</a> by offering an alternative regex engine with extended capabilities.</p> </li> <li><p>And of course, required reading: <a href="https://mathiasbynens.be/notes/javascript-unicode" rel="nofollow noreferrer">mathiasbynens.be - JavaScript has a Unicode problem</a>:</p> </li> </ul>
<p>You can also use:</p> <pre><code>function myFunction() { var str = "xq234"; var allowChars = "^[a-zA-ZÀ-ÿ]+$"; var res = str.match(allowChars); if(!str.match(allowChars)){ res="true"; } else { res="false"; } document.getElementById("demo").innerHTML = res; </code></pre>
35,503
<p>Is there any way to have a binary compiled from an ActionScript 3 project print stuff to <em>stdout</em> when executed?</p> <p>From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.</p> <p>Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?</p>
<p>With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev.</p> <p>For stdout, open <code>/dev/fd/1</code> or <code>/dev/stdout</code> as a <code>FileStream</code>, then write to that.</p> <p>Example:</p> <pre><code>var stdout : FileStream = new FileStream(); stdout.open(new File("/dev/fd/1"), FileMode.WRITE); stdout.writeUTFBytes("test\n"); stdout.close(); </code></pre> <p><strong>Note:</strong> See <a href="https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3">this answer</a> for the difference between <code>writeUTF()</code> and <code>writeUTFBytes()</code> - the latter will avoid garbled output on stdout.</p>
<p>If you are using a debug Flash Player, you can have the Flash Player log trace messages to a file on your system.</p> <p>If you want real time messages, then you could tail the file.</p> <p>More info:</p> <p><a href="http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/" rel="nofollow noreferrer">http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/</a></p> <p>mike chambers</p> <p>mesh@adobe.com</p>
5,958
<p>I just read up on a performance of LINQ, and there is a HUGE amount to be gained by using Compiled LINQ.</p> <p>Now, why won't I always use compiled LINQ?</p>
<p>Short answer: when it's only going to happen once in a long time.</p> <p><a href="http://blogs.msdn.com/ricom/archive/2008/01/14/performance-quiz-13-linq-to-sql-compiled-query-cost-solution.aspx" rel="nofollow noreferrer">Long Answer</a>.</p>
<p>You should use it when some linq query is executing most of the time. Those can be converted to compiled lynq. Performance will be improved as execution path of query will be set at compile time. I used it in my project and performance went up a notched.</p>
2,962
<p>I am using axis 2 webservice client.</p> <p>The first https call to the webservice throws a exception with the message: "Message did not contain a valid Security Element".</p> <p>I think that the problem could be the security mode: maybe it has to be message level security. In this case, how can I configure it in axis?.</p> <p>The code:</p> <pre><code>System.setProperty("javax.net.ssl.keyStore", jksFile); System.setProperty("javax.net.ssl.keyStorePassword", jksPassword); MyServicePortProxy proxy = new MyServicePortProxy(); Stub stub = (Stub) proxy.getMyServicePort(); proxy.setEndpoint(endpoint); stub.setUsername(username); stub.setPassword(password); // throws exception with the above message: proxy.serviceMethod(...); </code></pre>
<p>If you don't mind using EXT-GWT, a much prettier fully compliant GWT UI toolkit then this might be more what your looking for. </p> <p><a href="http://extjs.com/examples/layouts/accordionlayout.html" rel="nofollow noreferrer">The Example</a>. </p> <p>GXT as it is also called can do lots of good things for a GUI.</p>
<p>I took the TabPanel source code and modified it so it drew the tabs to look like Outlook.</p>
34,146
<p>I'm compiling a simple .c in visual c++ with Compile as C Code (/TC) and i get this compiler error </p> <blockquote> <p>error C2143: syntax error : missing ';' before 'type'</p> </blockquote> <p>on a line that calls for a simple struct </p> <pre><code> struct foo test; </code></pre> <p>same goes for using the typedef of the struct.</p> <blockquote> <p>error C2275: 'FOO' : illegal use of this type as an expression</p> </blockquote>
<p>I forgot that in C you have to declare all your variables before any code.</p>
<p>How is your structure type defined? There are two ways to do it:</p> <pre><code>// This will define a typedef for S1, in both C and in C++ typedef struct { int data; int text; } S1; // This will define a typedef for S2 ONLY in C++, will create error in C. struct S2 { int data; int text; }; </code></pre>
5,579
<p>I'm running Hudson as a windows service through Tomcat, with no slaves involved. The last build step in the job is a batch file that invokes some Java code. The code uses PostgreSQL's command line tool psql (via Runtime.exec()) to create a database on the local machine and eventually run some tests against it.</p> <p>The job will progress to this point, then hang indefinitely without starting to create the database. If I run the batch file from the command line, it works perfectly. I don't think <a href="http://hudson.gotdns.com/wiki/display/HUDSON/Spawning+processes+from+build" rel="nofollow noreferrer">http://hudson.gotdns.com/wiki/display/HUDSON/Spawning+processes+from+build</a> applies, since the process spawned doesn't even seem to begin executing, but I'm new to this so please let me know if I'm wrong.</p> <p>Edit @anjanb: The batch file's only purpose is to invoke the Java code, and the only user input is being passed in as command line arguments, which I can see are going in directly via the build's console output.</p> <p>Process Explorer is showing that psql is being started, but it's obviously not being executed, since the first command psql is given is to create a new database, but that's not happening.</p> <p>Edit 2: I've gotten some tips from the Hudson users mailing list, I'll try them out on Monday and report back.</p> <p>Edit 3: The Java code was already consuming the output streams, I used that article when developing the code. I can't figure out what's going on, so I'm redeveloping the code to use JDBC to create the database, instead of relying on psql and Runtime.exec()</p>
<p>Do you read the output of the process ? If it produces more output than the OS buffers can handle, you need to read it...</p> <p>Also, some processes wait until input has completed. Try to call process.getInputStream().close() after starting the process.</p> <p>Maybe this article is also interesting. It's called "When Runtime.exec() won't": <a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2</a></p>
<p>There is a possibility that the program is waiting on some user input. If the service is not configured to accept user input, it will appear to be hanging.</p> <p>YOu can try by configuring the service to allow USER INPUT(GUI) -- that might help.</p> <p>Also, you could run Sysinternals ProcessExplorer and ProcessMonitor -- they will be able to find out where the .BAT job has stopped.</p>
16,687
<p>I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.</p> <p>Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.</p>
<p>Provided the windows are from the same security domain, and you have a reference to the other window, yes.</p> <p>Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.</p> <p>Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.</p>
<p>The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain. If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).</p>
11,288
<p>I'm using Crystal Reports in vs2008, so I'm using datasets with procedures to get the data from the db, my escenario is the following: </p> <p>In the same Crystal Report, I have to show two reports, basically using the sames datasets, and the same database, but they are different queries (have grouping and summing instead)</p> <p>Is this possible? And if it is how can I solute this, using database expert? or crosstab? What options of crystal reports supports these operations? </p>
<p>You should be able to insert a "sub report" in Crystal on your primary report. You can pass parameters from the main report to the sub report and utilize a whole different command in the sub report. I'm not sure the exact keyboard sequence to insert a sub report in VS2008, but in CR 2008, it's as simple as using the file menu INSERT > SUB REPORT.</p>
<p>Based on my own experiences, I have to agree with Greg - a subreport is probably the easiest-to-maintain solution to your problem. In the case of VS2008, the steps to follow are:<p></p> <ol> <li>Go to the Crystal Reports -> Insert -> Subreport menu option.</li> <li>Click where you want to place the subreport on the main report. </li> <li>The 'Insert Subreport' form will be displayed. Either choose an existing report, or create a new one using the Report Wizard. In the Report Wizard, you can also choose from the existing datasets un your project.</li> </ol> <p>To link your main report to the subreport right-click on the Subreport, and choose 'Change Subreport Links'. </p> <p>Hope that helps.</p>
42,272
<p>I’m looking for a Perl ORM library that has support for reverse engineering of the database schema. All I’ve found so far is <a href="http://perlorm.sourceforge.net/" rel="nofollow noreferrer">http://perlorm.sourceforge.net/</a> and it appears to have no reverse engineering support.</p>
<p>There is a <a href="http://www.perlfoundation.org/perl5/index.cgi?recommended_database_modules" rel="noreferrer">list of recommended ORM modules at the P5P wiki</a>.</p> <p><a href="http://search.cpan.org/dist/Rose-DB-Object" rel="noreferrer">Rose::DB::Object</a> and <a href="http://search.cpan.org/dist/DBIx-Class" rel="noreferrer">DBIx::Class</a> can generate classes for you from an existing database schema, and can also write them out to a set of Perl module files.</p> <ul> <li><a href="http://search.cpan.org/perldoc?Rose::DB::Object::Loader" rel="noreferrer">Rose::DB::Object::Loader</a></li> <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Schema::Loader" rel="noreferrer">DBIx::Class::Schema::Loader</a></li> </ul>
<p>There are three commonly used ORMs in Perl, <a href="http://search.cpan.org/dist/Class-DBI/" rel="nofollow noreferrer">Class:DBI</a>, <a href="http://search.cpan.org/dist/DBIx-Class/" rel="nofollow noreferrer">DBIx::Class</a> and <a href="http://search.cpan.org/dist/Rose-DB-Object/" rel="nofollow noreferrer">Rose::DB::Object</a>. According to <a href="http://www.perlmonks.org/?node_id=700283" rel="nofollow noreferrer">this</a> page at PerlMonks, they can all load the metadata from the database, but it doesn't say how.</p>
47,371
<p>I am trying to create a mechanism with moving parts, and would like to see how it works (whether it even works) before printing it.</p> <p>For example, there's a servo with a bracket, and I would like to see how far can the bracket move before colliding with other objects.</p> <p><a href="https://i.stack.imgur.com/mlheh.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/mlheh.gif" alt="enter image description here"></a></p> <p>Unfortunately I cannot find any information on how to set pivot points and rotate objects around these points in FreeCAD. Is this even possible?</p>
<p>freeCad has a draft rotate function in <strong>DRAFT workbench</strong>:</p> <ol> <li>Select an object;</li> <li>Press the Draft Rotate button, then;</li> <li>Click to set the rotating point and rotate. </li> </ol> <p>You will get used to that after a few trails.</p> <p>There is a <a href="https://www.freecadweb.org/wiki/Draft_Rotate" rel="nofollow noreferrer">step by step guide</a> on freeCad site.</p> <p>There is also a <a href="https://youtu.be/5KDEf16MNc0" rel="nofollow noreferrer">short demo of the function here</a>.</p>
<p>I would also like to take a look at the A2plus Workbench (Freecad Addon). There you can define constraints which can help with this problem. As far as I know, parts cannot be moved with the mouse pointer, but angle parameters can be entered.</p> <p><a href="https://freecadweb.org/wiki/A2plus_Workbench" rel="nofollow noreferrer">https://freecadweb.org/wiki/A2plus_Workbench</a></p>
1,059
<p>Some development skills, like refactoring operations, feel like they have an almost unlimited pontential for learning - only the fool will say he's finished learning that.</p> <p>Other skills are bound to specific tools, and being good developers we learn new tools most of the time.</p> <p>But some skills are related to how you think about code and how you approach coding, sometimes how a specific tool feature can be applied. Rotating pair programming and working closely with other people seem to be the best way of acquiring these skills, though certainly not the only method. (And sometimes you learn things you SHOULD have learned 5 years ago, these are not the ones I am asking about)</p> <p>So I want to pair program with all of StackOverflow:</p> <p>What are your late-acquired coding skills ?</p> <p>Edit: I suppose I'm not thinking about the things you would have learned as a part of the curriculum if you were coming right out of school today.</p>
<p>It's the soft skills around being a better developer in a team than the nuts and bolts of actually being able to make an application that (more or less) meets the spec and compiles and makes the user/tester not shout too much. </p> <ol> <li>when to defensively write extensible code because you know that it will save you time in the end. <ul> <li>when to explicitly not do point (1). </li> <li>how to work in a team</li> <li>how to read and react to a specification that isn't wonderfully exact or clearly written</li> <li>when (and how) to let someone else have the funky project because you are too busy with drudge </li> </ul></li> </ol> <p>Mainly it's about being a better pack animal, there are times and places to be an alpha-male, but too often programmers can't take criticism and we can't always be playing with the projects like they're our toys. </p> <p>If you can't do that, then Guy Kawasaki and Joel Spolsky have written a lot of good stuff on founding your own company. </p>
<p>Working with only the logical structure of my code and ignoring physical file locations as much as possible.</p>
47,290
<p>The following XHTML code is not working:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="/dojotoolkit/dijit/themes/tundra/tundra.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="/dojotoolkit/dojo/resources/dojo.css" /&gt; &lt;script type="text/javascript" src="/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true" /&gt; &lt;script type="text/javascript"&gt; dojo.require("dijit.form.ValidationTextBox"); dojo.require("dojo.parser"); &lt;/script&gt; &lt;/head&gt; &lt;body class="nihilo"&gt; &lt;input type="text" dojoType="dijit.form.ValidationTextBox" size="30" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In Firebug I get the following error message:</p> <blockquote> <p>[Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMNSHTMLElement.innerHTML]" nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame :: <a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> :: anonymous :: line 319" data: no] <a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> Line 319</p> </blockquote> <p>Any idea what is wrong?</p>
<p>The problem seams to be the ending of the file...</p> <ul> <li>If I name the file <a href="http://www.tasix.ch/Greter/test2.html" rel="nofollow noreferrer">test2.html</a> everything works.</li> <li>If I name the file <a href="http://www.tasix.ch/Greter/test2.xhtml" rel="nofollow noreferrer">test2.xhtml</a> I get the error message.</li> </ul> <p>The diverence between the two seams to be the Content-Type in the response header from apache.</p> <ul> <li>For .html it is Content-Type text/html; charset=ISO-8859-1</li> <li>For .xhtml it is Content-Type application/xhtml+xml</li> </ul>
<p>Well, what is dojo.js doing at line 319?</p>
7,097
<p>Every so often when I'm debugging, I get this message in nice brown text on an ASP.NET error page:</p> <blockquote> <p><em>Access to the path "c:\windows\microsoft.net\framework\(version)\Temporary ASP.NET Files\(blah)" is denied.</em></p> </blockquote> <p>I've never been able to figure out what causes it, what really fixes it, and why it happens.</p> <p>Often times the path after the "Temporary ASP.NET Files" portion (the "(blah)") does not exist, so I'm not sure why it's looking there.</p> <p>Sometimes an IISRESET fixes it, and sometimes it doesn't.</p> <p>Sometimes an aspnet_regiis fixes it, and sometimes it doesn't. </p> <p>Sometimes a reboot fixes it, and sometimes it doesn't.</p> <p>For what it's worth I ran into this today with some .NET 1.1 code (yes, still maintaining some - hoping to upgrade it soon) and I'm not sure if I've ever seen it with .NET 2.0 and above. </p> <p>Does anyone know what causes this and what should fix it? I assume it has multiple possible causes but I'm just curious if someone could shed some light on it.</p>
<p>It was my understanding this can be caused by anti-virus running on the machine and intermittently locking the files.</p>
<p>This could also happen when the IIS user doesn't have permissions into the \Temporary ASP.NET Files directory</p>
22,985
<p>When writing manual SQL its pretty easy to estimate the size and shape of data returned by a query. I'm increasingly finding it hard to do this with LINQ to SQL queries. Sometimes I find WAY more data than I was expecting - which can really slow down a remote client that is accessing a database directly.</p> <p>I'd like to be able to run a query and then tell exactly how much data has been returned across the wire, and use this to help me optimize. </p> <p>I have already hooked up a log using the DataContext.Log method, but that only gives me an indication of the SQL sent, not the data received.</p> <p>Any tips?</p>
<p>Looks like you can grab the SqlConnection of your DataContext and turn on statistics.</p> <p>One of the statistics is "bytes returned".</p> <p><a href="http://msdn.microsoft.com/en-us/library/7h2ahss8(VS.80).aspx" rel="nofollow noreferrer">MSDN Reference Link</a></p>
<p>I found no way to grab the SqlConnection of the DataContext, so i created the SqlConnection manually:</p> <pre><code>SqlConnection sqlConnection = new SqlConnection("your_connection_string"); // enable statistics cn.StatisticsEnabled = true; // create your DataContext with the SqlConnection NorthWindDataContext nwContext = new NorthWindDataContext(sqlConnection); var products = from product in nwContext where product.Category.CategoryName = "Beverages" select product; foreach (var product in products) { //do something with product } // retrieve statistics - for keys see http://msdn.microsoft.com/en-us/library/7h2ahss8(VS.80).aspx string bytesSent = sqlConnection.RetrieveStatistics()["BytesSent"].ToString(); string bytesReceived = sqlConnection.RetrieveStatistics()["BytesReceived"].ToString(); </code></pre>
12,179
<p>I had a class with some common error handling code, and I wanted to pass in the method and arguments to call, but I couldn't quite come up with the syntax. What I want to do is roughly this:</p> <pre><code>private void InvokeHelper(Delegate method, params object[] args) { bool retry = false; do { try { method.DynamicInvoke(args); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); } </code></pre> <p>and then be able to do things like:</p> <pre><code>InvokeHelper(foo.MethodA, a, b, c); InvokeHelper(foo.MethodB, x, y ); </code></pre> <p>This gets a compiler error converting foo.MethodA and foo.MethodB into System.Delegate. I came up with the workaround below (and I actually like it better because then I get type checking on my arguments to my methods), but I'm curious if there's a way to do what I was originally trying to do? I know I could use <code>foo.GetType().GetMethod("MethodA")</code> and invoke that, but I was trying to avoid reflection. I mainly just want to understand how methods are dynamically invoked in .net.</p> <p>Workaround:</p> <pre><code>private delegate void EmptyDelegate(); private void InvokeHelper(EmptyDelegate method) { bool retry = false; do { try { method.Invoke(); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); } </code></pre> <p>then call:</p> <pre><code>InvokeHelper(delegate() { foo.MethodA(a, b, c); }); InvokeHelper(delegate() { foo.MethodB(x, y); }); </code></pre>
<p>First off, your signature is </p> <pre><code>private void InvokeHelper(Delegate method, params object[] args) </code></pre> <p>Yet you're making the mistake that you have to group your args into an array to call this method:</p> <pre><code>InvokeHelper(foo.MethodA, new object[] { a, b, c}); </code></pre> <p>The <code>parms</code> keyword tells the compiler to do this for you; you can call this method thusly:</p> <pre><code>InvokeHelper(foo.MethodA, a, b, c); </code></pre> <p>Second, if you're targeting 3.0 or greater, don't use Delegate, use Action:</p> <pre><code>private void InvokeHelper(Action method) </code></pre> <p>and call it this way:</p> <pre><code>InvokeHelper(()=&gt; MyMethodToInvoke(a, b, c)); </code></pre> <p>which is just an overall better way of doing this.</p> <hr> <p>As to why you're getting the compiler issue, its because System.Delegates hate us. Its a simple fact. That, and because there is no implicit cast from method group to Delegate.</p>
<p>Here's a re-write, following Will's advice to use Action:</p> <pre><code> private void InvokeHelper(Action method) { bool retry = false; do { try { method(); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); } public void Test() { FooClass foo = new FooClass(); InvokeHelper( () =&gt; foo.MethodA(1, "b", 3) ); InvokeHelper( () =&gt; foo.MethodB(2, "y")); } </code></pre>
45,542
<p>I have a system that creates an order and that order can be billed to a house account, sent Cash on Delivery (COD), or charged to a credit card. I've created the following tables:</p> <p>ORDERS<br/> order_id<br/> billingoption_id</p> <p>BILLINGOPTIONS<br/> billingoption_id<br/></p> <p>I'm unsure of how the next table should be built for the billing data. Should I build a separate table for each type of billing option (ie. COD, Credit Cards, and House Account)? Then would I have another foreign key column on the Orders table that would refer to a record for the billing data?</p>
<p>You can do it either way: a big honking <code>billingoptions</code> table that has fields that encompasses all of the types, with NULLs for fields that don't apply to a given type, or a bunch of baby tables that "star off" of a parent <code>billingoptions</code> table. Both have their advantages and disadvantages.</p> <p>For the big honking table,</p> <ul> <li>It's nice that all data can easily be referenced in a single table.</li> <li>Tracking foreign key dependencies and performing updates or inserts is efficent.</li> <li>BUT you need to alter the table structure to add new billing options in the future, and there's the possibility of invalid combinations of data being stored (for example, both a credit card type and a COD flag being set in the same record).</li> </ul> <p>For the small baby tables,</p> <ul> <li>It's nice that the data is partitioned and reflects your program's object structure closely.</li> <li>It's nice that you can add new payment options or alter existing ones without worrying about affecting the others.</li> <li>The relationships are VERY explicit. You can't accidentally link a deposit with another deposit, since the foreign key will require that it be linked with an approval.</li> <li>BUT you end up introducing a lot of tables into the design, which require lots of JOINs, can be a pain to navigate, and aren't as efficient when it comes to inserts and updates.</li> </ul> <p>At work, we ended up going with small baby tables. It looks something like this:</p> <pre> Table Orders: --> OrderId PK --> (Lots of Other Fields) Table Payments: --> PaymentId PK --> OrderId (FK) [There may be more than one payment per order] --> PaymentType [Restricted field contains values like 'PAYPAL' or 'CREDIT', you use this to know which baby table to look up that can contain additional information] Table PaymentsPayPal: --> PaymentPayPalId PK --> PaymentId FK points to Table Payments --> TransactionNo --> (Other PayPal specific fields) Table PaymentsCheck: --> PaymentCheckId PK --> PaymentId FK points to Table Payments --> RoutingNo --> (Other e-check specific fields) + other tables for remaining payment types.... </pre> <p>All of the payment types share three transaction related tables:</p> <pre> Table PaymentApprovals: --> PaymentApprovalId PK --> PaymentId FK points to Table Payments --> Status [Some flag meaning 'Succeeded', 'Failed', 'Reversed', etc] --> ProcessorMessage [Something the service sent back, like '(M) CVV2 Matched'] --> Amount --> (Other administrative fields) Table PaymentDeposits: --> PaymentDepositId PK --> PaymentApprovalId FK points to Table PaymentApprovals --> Status --> ProcessorMessage --> Amount --> (Other administrative fields) Table PaymentRefunds: --> PaymentRefundId PK --> PaymentDepositId FK points to Table PaymentDeposits --> Status --> ProcessorMessage --> Amount --> (Other administrative fields) </pre> <p>All of our payment methods (Credit Card, PayPal, Google Checkout, Check, Cash, Store Credit, and Money Order) are abstracted to fit into this Approval --> Deposit --> Refund metaphor, and the UI calls the same methods on an <code>IPayment</code> and <code>IPaymentProcessor</code> interfaces with different implementations (<code>CybersourcePaymentProcessor</code>, <code>PayPalPaymentProcessor</code>, etc). The abstraction has worked pretty well over the past year and a half across these disparate methods, although sometimes the GUI will display different verbiage to the user (for example, it'll say "Authorize" and "Charge" instead of "Approve" and "Deposit" for credit card payments, and the screen for entering cash performs the Approve/Deposit step in one fell swoop.)</p> <p>Hope that makes sense. It sounds like you're not actually storing payment information, but it's useful to think about where these things can end up.</p>
<p>Focus on things. Actual things. Try to describe things simply, directly, and in natural language first.</p> <p>Then, when you ask for design guidance, you can provide definitions. In some cases, the act of writing definitions will make the design crystalize.</p> <p><strong>Orders</strong> are things. What are the attributes of an order? Customer, Product, Payment/Billing options.</p> <p><strong>Billing Options</strong> are (almost) things. You can, apparently, define and identify them. (I'm not sure I could. From your question, it appears that you might be able to. But without a one-sentence summary, I'm not sure what's going on with Billion Options.</p> <p>What's a "billing data?" What kind of thing is this? What attributes (or properties) does it have? </p> <p>How does a "Billing Data" relate to an Order? How does it relate to a Billing Option?</p> <p>Feel free to update the question with definitions for each thing.</p>
40,207
<p>Is it possible to create patch installers for web deployment installers generated in VS2005?</p> <p>I have a situation in which it is undesirable to perform a complete uninstall/reinstall of a web site, but in which periodic bug fixes and minor upgrades are made.</p> <p>I've tried following the instructions in various online posts about using msimsp.exe to generate a patch file, but most/all of them rely on some usage of msiexec.exe to create an administrative install for comparison, since msimsp.exe can't cope with compressed content (e.g. CAB files). Web installations don't really have an administrative install, however, and ultimately the patch creation fails.</p> <p>Of course, I can create an installer containing <em>just</em> the changed files by hand, but that's prone to error, and having an automated process is more desirable.</p> <p>Any help is appreciated.</p>
<p>We deploy using Subversion. </p> <p><a href="http://blog.lavablast.com/post/2008/02/I2c-for-one2c-welcome-our-new-revision-control-overlords!.aspx" rel="nofollow noreferrer">http://blog.lavablast.com/post/2008/02/I2c-for-one2c-welcome-our-new-revision-control-overlords!.aspx</a></p>
<p>The WIX (Windows Installer XML) documentation has a section on Patch Building using a Patch Creation Properties (PCP) authoring file for creating a delta patch file.</p>
19,639
<p>We have a bunch of VB6 applications that access two different database servers (both 32-bit windows 2003, one SQL Server 2000, one SQL Server 2005). About every ten minutes or so, we are getting a few errors:</p> <blockquote> <p>[Microsoft][ODBC SQL Server Driver]Timeout expired [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. [Microsoft][ODBC SQL Server Driver]ConnectionRead()</p> </blockquote> <p>This is happening on more than a dozen different computers at random times. We also have IP phones that all run through the same network and those are not having any problems. We can also VNC into a users computer and reproduce the error they were getting, but VNC still continues to work. Email also works. It just seems to be an ODBC connection to SQL Server that causes the issue. The errors happen for both of our SQL Servers. We have scoured google, but haven't been able to come up with a solution. Is there anything we can try to diagnose the problem? Is there any fix out there?</p> <h3>Update:</h3> <p>We have no internal firewalls on either the servers or clients. We connect through TCP/IP via the dns name of the server (also have tried IP address).</p> <p>One server has Windows 2003 SP2 and the other doesn't.</p> <p>The strange thing is that it has worked fine for years and now all of a sudden these errors are happening. Nothing has changed on those servers for quite some time. That leads us to beleive it is a bad switch, but that seems unlikely since nothing else (email, phones, vnc, file server, etc) all work without problems.</p>
<p>Take a look at this Microsoft Knowledge Base article.</p> <p><a href="http://support.microsoft.com/kb/945977" rel="nofollow noreferrer">Some problems occur after installing Windows Server 2003 SP2</a></p> <p>I would also suggest that you switch to an OLE DB provider. In my experience, it's faster than ODBC and more reliable too.</p> <p><a href="http://connectionstrings.com/sql-server-2005" rel="nofollow noreferrer">Connection Strings</a></p> <p>Scroll down to: SQL Native Client OLE DB Provider</p>
<p>Are you using non-default instances? Or do you have internal firewalls?</p> <p>We changed to "server.fqdn.tld\instance,port" to avoid this exact (IIRC) intermittent connection issue from clients behind internal firewalls.</p> <p>Only SQL connections were affected.</p>
49,633
<p>I have some REST web services implemented in WCF. I wish to make these services return "Bad Request" when the xml contains invalid elements.</p> <p>The xml serialization is being handled by XmlSerializer. By default XmlSerializer ignores unknown elements. I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization. Any ideas how I might implement this behavior.</p>
<p><em>"I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization"</em></p> <p>Its actually possible to do this...</p> <p>In a WCF project that I worked on, we did something similar using the IDispatchMessageFormatter interface.</p> <p>More information can be found here <a href="http://nayyeri.net/blog/use-idispatchmessageformatter-and-iclientmessageformatter-to-customize-messages-in-wcf/" rel="nofollow noreferrer">http://nayyeri.net/blog/use-idispatchmessageformatter-and-iclientmessageformatter-to-customize-messages-in-wcf/</a> </p> <p>It allows you peak at the message headers, control serialization/deserialization, return status codes etc.</p>
<p>Maybe you can return your own type implementing IXmlSerializable and thorw the exception you want in the ReadXml and WriteXml methods...</p>
18,987
<p>This <a href="https://stackoverflow.com/questions/11782/file-uploads-via-web-services">question and answer</a> shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;bytes&gt; &lt;byte&gt;16&lt;/byte&gt; &lt;byte&gt;28&lt;/byte&gt; &lt;byte&gt;127&lt;/byte&gt; ... &lt;/bytes&gt; </code></pre> <p>If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?</p>
<p>Typically a byte array is sent as a <code>base64</code> encoded string, not as individual bytes in tags. </p> <p><a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Base64</a></p> <p>The <code>base64</code> encoded version is about <strong>137%</strong> of the size of the original content.</p>
<p>I use this method for some internal corporate webservices, and I haven't noticed any major slow-downs (but that doesn't mean it's not there). </p> <p>You could probably use any of the numerous network traffic analysis tools to measure the size of the data, and make a judgment call based off that.</p>
3,294
<p>once you have a commit that contains a submodule object, you pretty much cannot get git-svn to commit past it.</p> <p>Any ideas, workarounds, anything that is not "don't use submodules with git-svn"?</p> <p>So far the answer seems to be a big NO.</p> <p>Is there any way to at least allow existing git commits containing submodule data to be committed to svn without the submodule data? Even if it means rewriting the tree.</p>
<p>You'll need to replace the submodules with the <code>svn:externals</code> property to play nice with Subversion.</p> <pre><code>svn propset svn:externals [...] </code></pre> <p>I don't think there's any other way round it.</p>
<p>If you have an access to the SVN server you may install <a href="http://subgit.com" rel="nofollow">SubGit</a> into it. It will create a linked Git repository, such that any push to the Git repository will be translated to the SVN and vice versa. The translation is concurrent-safe, so you may consider this pair of repositories as 2 interfaces (Git and SVN) of the same repository as it is done on GitHub with the difference that the translation is much more transparent (all branches are converted to branches, tags to tags, svn:ignore to .gitginore, svn:eol-style to .gitattributes value and so on).</p> <p>After that you may add submodules to you resulting Git repository and forget about git-svn.</p> <p>If you have no access to the server I know no solution, only for svn:externals support from Git (look at SmartGit and .gitsvnextmodules config).</p>
33,494
<p>I'm currently building a project and I would like to make use of some simple javascript - I know some people have it disabled to prevent XSS and other things. Should I...</p> <p>a) Use the simple javascript, those users with it disabled are missing out</p> <p>b) Don't use the simple javascript, users with it enabled have to click a little more</p> <p>c) Code both javascript-enabled and javascript-disabled functionality</p> <p>I'm not really sure as the web is always changing, what do you recommend?</p>
<p>Degrade gracefully - make sure the site works without JavaScript, then add bells and whistles for those with JavaScript enabled.</p>
<p>As said before, it depends on your target audience.</p> <p>If I'm part of it, you want to make sure that your site works (if not ideally) on my phone, and that it gives me reason to turn Javascript on when I surf there with it off. Nobody expects full functionality with Javascript disabled, and anybody who uses their phone to access websites expects some issues, but you need to at least provide teasers. For a web store, make sure customers can see at least some merchandise anyway, even if they can't buy without Javascript.</p>
43,801
<p>I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.</p>
<pre><code>^(?:(?!boon\.ini|http).)*$\r?\n? </code></pre> <p>(taken from <a href="http://www.regexbuddy.com" rel="noreferrer">RegexBuddy</a>'s library) will match any line that does not contain boon.ini and/or http. Is that what you wanted?</p>
<p>I used this (based on Tim Pietzcker answer) to exclude non-production subdomain URLs for Google Analytics profile filters:</p> <pre><code>^\w+-*\w*\.(?!(?:alpha(123)*\.|beta(123)*\.|preprod\.)domain\.com).*$ </code></pre> <p>You can see the context here: <a href="http://technicaldebt.com/?p=1496" rel="nofollow">Regex to Exclude Multiple Words</a></p>
14,231
<p>I'm working on updating a classic ASP web page used by a number of sub-sites maintained at the company I work for.</p> <p>The purpose of the page is to notify the user that they are leaving "our" site and going to another site. It's basically a disclaimer, but due to resource limitations and time limitations I can't add the disclaimer to every site we manage.</p> <p>This is the crux of the problem. The current code pulls a variable from the query string to create the "continue" link in the new window. This obviously creates many problems in the form of cross site scripting.</p> <p>How do I approach this update to eliminate most (if not all) of the cross site scripting issues using vbScript/ASP.</p> <p>The code I'm using is below.</p> <pre><code>&lt;%@ Language = vbScript %&gt; &lt;% Option Explicit %&gt; &lt;% Dim strLink strLink = Request.QueryString("site") strLink = Replace(strLink, "&lt;", "&amp;lt") strLink = Replace(strLink, "&gt;", "&amp;gt;") strLink = Replace(strLink, chr(34), "") strLink = Replace(strLink, "script", "", 1, -1, 1) strLink = Replace(strLink, "onclick", "", 1, -1, 1) strLink = Replace(strLink, "ondblclick", "", 1, -1, 1) strLink = Replace(strLink, "onmousedown", "", 1, -1, 1) strLink = Replace(strLink, "onmouseover", "", 1, -1, 1) strLink = Replace(strLink, "onmousemove", "", 1, -1, 1) strLink = Replace(strLink, "onmouseout", "", 1, -1, 1) strLink = Replace(strLink, "onkeypress", "", 1, -1, 1) strLink = Replace(strLink, "onkeydown", "", 1, -1, 1) strLink = Replace(strLink, "onkeyup", "", 1, -1, 1) strLink = Replace(strLink, "onfocus", "", 1, -1, 1) strLink = Replace(strLink, "onblur", "", 1, -1, 1) strLink = Replace(strLink, "&amp;&amp;", "") strLink = Replace(strLink, "##", "") strLink = Replace(strLink, "&amp;#", "") %&gt; &lt;a href="&lt;%= strLink %&gt;"&gt;Continue&lt;/a&gt; </code></pre>
<p>This is what I recommend for HTML sanitizing -</p> <p>HTML Whitelist is the latest in the "cool little Python Web service thrown up on App Engine" by my good colleague DeWitt Clinton.</p> <p>It does one thing, and it does it well. You can pass the service HTML and it will return a sanitized version.</p> <p><a href="http://html-whitelist.appspot.com/" rel="nofollow noreferrer">http://html-whitelist.appspot.com/</a></p>
<p>You could add logic to continue page to ensure that it is only called by a page on one of your sites either based on url or IP address. You could also pass a time and hashed code through for added security.</p>
28,619