instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code. </p> <pre><code>var urls = new List&lt;string&gt;(); urls.Add("http://www.google.com"); foreach (string url in urls) { // Get all links from the url List&lt;string&gt; newUrls = GetLinks(url); urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping } </code></pre> <p>How can I rewrite this in a better way? I'm guessing a recursive solution?</p>
<p>You can't, basically. What you really want here is a queue:</p> <pre><code>var urls = new Queue&lt;string&gt;(); urls.Enqueue("http://www.google.com"); while(urls.Count != 0) { String url = url.Dequeue(); // Get all links from the url List&lt;string&gt; newUrls = GetLinks(url); foreach (string newUrl in newUrls) { queue.Enqueue(newUrl); } } </code></pre> <p>It's slightly ugly due to there not being an <code>AddRange</code> method in <code>Queue&lt;T&gt;</code> but I think it's basically what you want.</p>
<p>Don't change the collection you're looping through via for each. Just use a while loop on the Count property of the list and access the List items by index. This way, even if you add items, the iteration should pick up the changes.</p> <p>Edit: Then again, it sort of depends on whether you WANT the new items you added to be picked up by the loop. If not, then this won't help.</p> <p>Edit 2: I guess the easiest way to do it would be to just change your loop to: foreach (string url in urls.ToArray())</p> <p>This will create an Array copy of your list, and it will loop through this instead of the original list. This will have the effect of not looping over your added items.</p>
36,532
<p>I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's <code>text</code>, <code>value</code>, and <code>selected</code> properties, but I don't think that javascript's built in <code>Array.sort()</code> would work correctly.</p>
<p>Extract options into a temporary array, sort, then rebuild the list:</p> <pre><code>var my_options = $("#my_select option"); var selected = $("#my_select").val(); my_options.sort(function(a,b) { if (a.text &gt; b.text) return 1; if (a.text &lt; b.text) return -1; return 0 }) $("#my_select").empty().append( my_options ); $("#my_select").val(selected); </code></pre> <p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort" rel="noreferrer" title="Mozilla&#39;s sort documentation">Mozilla's sort documentation</a> (specifically the compareFunction) and <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="noreferrer">Wikipedia's Sorting Algorithm page</a> are relevant.</p> <p>If you want to make the sort case insensitive, replace <code>text</code> with <code>text.toLowerCase()</code></p> <p>The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the <a href="http://www.unicode.org/reports/tr10/" rel="noreferrer">unicode collation algorithm</a>). Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare" rel="noreferrer">localeCompare</a> in the sort function is a good solution, eg:</p> <pre><code>my_options.sort(function(a,b) { return a.text.localeCompare(b.text); }); </code></pre>
<p>Seems jquery still is not particularly helpful enough for sorting options in a html select element. Here is some plain-plain javascript code for sorting options:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function sortOptionsByText(a,b) { // I keep an empty value option on top, b.value comparison to 0 might not be necessary if empty value is always on top... if (a.value.length==0 || (b.value.length&gt;0 &amp;&amp; a.text &lt;= b.text)) return -1; // no sort: a, b return 1; // sort switches places: b, a } function sortOptionsByValue(a,b) { if (a.value &lt;= b.value) return -1; // a, b return 1; // b, a } function clearChildren(elem) { if (elem) { while (elem.firstChild) { elem.removeChild(elem.firstChild); } } } function sortSelectElem(sel,byText) { const val=sel.value; const tmp=[...sel.options]; tmp.sort(byText?sortOptionsByText:sortOptionsByValue); clearChildren(sel); sel.append(...tmp); sel.value=val; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>RACE: &lt;select id="list" size="6"&gt; &lt;option value=""&gt;--PICK ONE--&lt;/option&gt; &lt;option value="1"&gt;HUMANOID&lt;/option&gt; &lt;option value="2"&gt;AMPHIBIAN&lt;/option&gt; &lt;option value="3"&gt;REPTILE&lt;/option&gt; &lt;option value="4"&gt;INSECTOID&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;button type="button" onclick="sortSelectElem(document.getElementById('list'));"&gt;SORT LIST BY VALUE&lt;/button&gt;&lt;br&gt; &lt;button type="button" onclick="sortSelectElem(document.getElementById('list'),true);"&gt;SORT LIST BY TEXT&lt;/button&gt;</code></pre> </div> </div> </p>
6,790
<p>The NetBeans 6.1 editor doesn't seem to like to wrap comments, and the code formatter seems to ignore them. For JavaDoc comments, this behaviour seems inappropriate, as you can end up spending a lot of wasted time manually reflowing paragraphs.</p> <p>I was wondering if there's some magic setting to get the builtin code formatter, or the editor to wrap/reflow javadoc comments?</p>
<p>This issue has been raised to the Netbeans development team and will likely be added in a "future" release of Netbeans. If you want this feature (or any other feature) to be added to the IDE, go to the issue tracking website and vote for this feature.</p> <p><a href="http://www.netbeans.org/issues/show_bug.cgi?id=11553" rel="nofollow noreferrer">http://www.netbeans.org/issues/show_bug.cgi?id=11553</a></p> <p>Most open-source products use the votes on their issue tracking systems to determine where to allocate resources for the next release.</p>
<p>I'm fairly sure that you can't do this. Comments are not code and javadoc comments are not exactly plain text either as they're intended to be HTML outputted.</p> <p>Maybe write your own plugin for this?</p>
12,415
<p>I'm building a webpage that queries a MySQL database and (currently) produces a text-only list of the findings. The queries to complete a single record are similar to:</p> <ul> <li>movie (title, description, etc) <ul> <li>actors in the movie (name, gender)</li> <li>related movies</li> </ul></li> </ul> <p>Out of curiosity I've used <code>memory_get_peak_usage()</code> and <code>memory_get_usage()</code>:</p> <pre> start 110,440 bytes peak 656,056 bytes end 637,976 bytes time 0.008 seconds </pre> <p>The above is with no records found!</p> <p>With 40 records I'm reaching approximately 2MB, though the time remains the same.</p> <p>I know that premature optimization is evil and all, but I have to ask: </p> <p>Do I need to do some reworking? Is this memory usage normal? What is considered excessive?</p>
<p>Ultimately it's preferable to optimize when convenient of course, but 2MB of memory use sounds fine. PHP4 has a default config of 8mb, and PHP5 16mb. A lot of pre-packaged PHP builds will have different configs, of course, but generally speaking, if you can keep your app under 8mb, you can be sure it'll be highly portable in that regard.</p>
<p>As long as you plan a good caching mechanism (opcode cache, object cache, etc.), memory usage becomes less relevant. You are still way below common php framework memory usage.</p>
28,786
<p>I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table.</p> <p>There must be a simple way of doing this. Something like:</p> <pre><code>INSERT INTO database1.myTable columnINeed SELECT columnINeed from database2.myTable </code></pre>
<p>Inserting won't do it since it'll attempt to insert new rows at the end of the table. What it sounds like your trying to do is add a column to the end of existing rows.</p> <p>I'm not sure if the syntax is exactly right but, if I understood you then this will do what you're after.</p> <ol> <li><p>Create the column allowing nulls in database2.</p></li> <li><p>Perform an update:</p> <p>UPDATE database2.dbo.tablename SET database2.dbo.tablename.colname = database1.dbo.tablename.colname FROM database2.dbo.tablename INNER JOIN database1.dbo.tablename ON database2.dbo.tablename.keycol = database1.dbo.tablename.keycol</p></li> </ol>
<p>insert into Test2.dbo.MyTable (MyValue) select MyValue from Test1.dbo.MyTable</p> <p>This is assuming a great deal. First that the destination database is empty. Second that the other columns are nullable. You may need an update instead. To do that you will need to have a common key.</p>
7,561
<p>I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the <code>asp:</code>-style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my <code>&lt;asp:BulletedList ID="nav"&gt;</code>, when converted into HTML, became <code>&lt;ul id="ct100_nav"&gt;</code>.</p> <p>There are other issues--I noticed that when you auto-populate a DataGrid, it adds attributes to the resulting table that I don't necessarily want there.</p> <p>I know that there is a certain amount of "convention over configuration" that you have to accept when you rely on a framework to take over some of your tedious duties, but the "conventions" in these cases aren't so much any established conventions, but rather unnecessary extras. I know <em>why</em> the ID adds the prefix, but I should be able to tweak and turn things like this off, especially since, as a bit of a web standards evangelist, I don't duplicated HTML id's in a single page anyway.</p> <p>So the question here is for those ASP.NET devs more seasoned than I: in your experiences in developing and deploying apps, how do you leverage these controls? Do you find yourself resorting back to hard-coded HTML? Do you use a blend? I don't want to design my HTML around idiosyncratic quirks in these controls, but, if possible, I'd like to leverage them when possible. </p> <p>What's a boy to do?</p>
<p>Personally, </p> <p>I think the standard ASP.NET controls are fine for inhouse stuff - quick and dirty is good in that scenario. But, I once worked with a web developer who was also a designer and he refused to use the ASP.NET controls and only code in HTML and add runat="server" tags when needed. This was more because he wanted to know exactly how his HTML was going to be rendered, and at the time anyway, some of the ASP.NET controls wouldn't render to standards compliance.</p> <p>I sit somewhere in the middle - use HTML where appropriate and not when not. You can sort of best of both worlds with the <a href="http://weblogs.asp.net/scottgu/archive/2006/05/02/444850.aspx" rel="noreferrer">CSS control Adapters</a></p>
<p>If the ID's prefix added by ASP.NET is an issue for you to access them later using JS or something... you have the .ClientID property server side.</p> <p>If the overhead added by ASP.NET you should consider ASP.NET MVC (still preview) where you have full control over the emitted html.</p> <p>I'm moving to MVC because I don't like all that stuffs added too....</p>
4,209
<p>When starting a new ASP.NET application, with the knowledge that at some point in the future it must scale, what are the most important design decisions that will allow future scalability without wholsesale refactoring?</p>
<p>My Top three decisions are </p> <ol> <li>Disabling or storing session state in a database.</li> <li>Storing as little as possible in session state. </li> <li>Good N-Tier Architecture. Separating business logic and using Webservices instead of directly accessing DLL's ensures that you can scale out both the business layer as well as the presentation layer. Your database will likely be able to handle anything you throw at it although you can probably cluster that too if needed.</li> </ol> <p>You could also look at partitioning data in the database too.</p> <p>I have to admit though I do this regardless of whether the site has to scale or not.</p>
<p>Ensure you have a solid caching policy for transient / static data. Database calls are expensive especially with separate physical servers so be aggressive with your caching.</p>
38,195
<p>Is there a best practice for avoiding a browser freeze when loading an applet?</p> <p>For my precise needs, the applet needs to be loaded when the web application is initialized, and is not a visual component (will be in a hidden div or hidden iframe).</p> <p>As a reference, here is an <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6267809" rel="nofollow noreferrer">old bug on SUN's side</a>.</p>
<p>Essentially, no there is not. Read the evaluation section of the bug you linked to. The issue is one of startup time for the JVM. About the best you can do is to keep the applet small so that it will load quickly. However, the browser freeze is happening because the browser has to wait for the VM to start. You can't ever drop that time to 0, so a short freeze is unavoidable.</p>
<p>Essentially, no there is not. Read the evaluation section of the bug you linked to. The issue is one of startup time for the JVM. About the best you can do is to keep the applet small so that it will load quickly. However, the browser freeze is happening because the browser has to wait for the VM to start. You can't ever drop that time to 0, so a short freeze is unavoidable.</p>
25,534
<p>I have a hyper link like this :</p> <pre><code>&lt;A Href=My_Java_Servlet?User_Action=Admin_Download_Records&amp;User_Id=Admin onClick=\"Check_Password();\" target=_blank&gt;Download Records&lt;/A&gt; </code></pre> <p>When a user clicks on it, a password window will open, the user can try 3 times for the right password.</p> <p>The Javascript looks like this :</p> <pre><code>&lt;Script Language="JavaScript"&gt; function Check_Password() { var testV=1; var pass1=prompt('Password',''); while (testV&lt;3) { if (!pass1) history.go(-1); if (pass1=="password") { return true; } testV+=1; var pass1=prompt('Access Denied - Password Incorrect.',''); } return "false"; } &lt;/Script&gt; </code></pre> <p>If user enters the wrong password 3 times, it's supposed to not do anything, but it still opens a new window and displays the protected info, how to fix the javascript or my html hyper link so only the right password will open a new target window, a wrong password will make it do nothing ?</p>
<p>Clientside JavaScript is perhaps the worst possible way to provide "security". Users can just view the source to see all of your passwords, or just disable JavaScript altogether. <strong>Do not do this.</strong></p>
<p>Why are you returning <strong>"false"</strong> instead of <strong>false</strong> ?</p>
31,236
<p>I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using <em>find</em> piped with <em>xargs grep</em>:</p> <pre><code>find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN' </code></pre> <p>But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.</p>
<p>So I discovered <a href="http://www.pcre.org/" rel="nofollow noreferrer"><em><strong>pcregrep</strong></em></a> which stands for <strong>Perl Compatible Regular Expressions GREP</strong>.</p> <blockquote> <p>the -M option makes it possible to search for patterns that span line boundaries.</p> </blockquote> <p>For example, you need to find files where the '<em>_name</em>' variable is followed on the next line by the '<em>_description</em>' variable:</p> <pre><code>find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description' </code></pre> <p>Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...</p>
<p>This answer might be useful:</p> <p><a href="https://stackoverflow.com/questions/3717772/regex-grep-for-multi-line-search-needed/7167115#7167115">Regex (grep) for multi-line search needed</a></p> <p>To find recursively you can use flags -R (recursive) and --include (GLOB pattern). See:</p> <p><a href="https://stackoverflow.com/questions/221921/grep-exclude-include-syntax-do-not-grep-through-certain-files/221929#221929">Use grep --exclude/--include syntax to not grep through certain files</a></p>
18,425
<p>It's about PHP but I've no doubt many of the same comments will apply to other languages.</p> <p>Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?</p> <pre><code>for ($i = 0; $i &lt; 10; $i++) { # code... } foreach ($array as $index =&gt; $value) { # code... } do { # code... } while ($flag == false); </code></pre>
<p>For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet </p> <p>The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;</p> <pre><code>for ($i = 0; $i &lt; 10; $i++) { # code... } </code></pre> <p>Same thing done with while loop:</p> <pre><code>$i = 0; while ($i &lt; 10) { # code... $i++ } </code></pre> <p>Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block</p> <pre><code>do { # code... } while ($flag == false); </code></pre> <p>foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.</p> <pre><code>foreach ($array as $index =&gt; $value) { # code... } </code></pre> <p>You could do the same thing with while loop, like this </p> <pre><code>while (current($array)) { $index = key($array); // to get key of the current element $value = $array[$index]; // to get value of current element # code ... next($array); // advance the internal array pointer of $array } </code></pre> <p>And lastly: <a href="http://www.php.net/download-docs.php" rel="noreferrer">The PHP Manual</a> is your friend :)</p>
<p>I use the first loop when iterating over a conventional (indexed?) array and the foreach loop when dealing with an associative array. It just seems natural and helps the code flow and be more readable, in my opinion. As for do...while loops, I use those when I have to do more than just flip through an array.</p> <p>I'm not sure of any performance benefits, though.</p>
4,282
<p>In 4D printing technology or by means usage of Shape-memory alloy (non-metal, iron based, copper based or NiTi material) for 3D printing.</p> <p>Is there any software simulation tool which I can use to simulate this material change behavior with respect to time? For example, when introducing a change in humidity or temperature.</p> <p>Note: It would be best if the simulation tools targeted automotive parts (power train, cooling system, interior &amp; exterior etc.).</p>
<p>I am going to say that this probably is a whole dimension out of scope for this group ;-)</p> <p>That said this new type of 3d printing is still at the University level. Also 4d is not necessarily 3d printing related at all. All it has to be is self assembling. Like <a href="http://www.selfassemblylab.net/4DPrinting.php" rel="nofollow noreferrer">http://www.selfassemblylab.net/4DPrinting.php</a></p> <p>Unless you have a connect with MIT. Then you aren't going to be simulating any 4d models.</p> <p>But if you HAD to do this, then you should write a paper about it and become a researcher. You could get published. You might need a PHD in material science. There might be some simulation in solid works.. but I would say you are mostly on your own and have to develop the models as they simply do not exist, especially outside of academia and stratasys.</p> <p>That said if you take the &quot;4d&quot; part and use models based on the current understanding of the raw material you would have more success.</p>
<p>(preface : I originally intent to write this as a comment, but the volume limit reached. In that tone, I'll utilize this answer space writing it..)</p> <blockquote> <p>to simulate those material change behavior in respect to time?</p> </blockquote> <p>COMSOL, ANSYS or equivalent ring a bell to be.. as long as you have the material properties (young's modulus, density, thermal transport &amp; expansion properties, color?) right.</p> <p>Also. depending on your actual implementation resolution (nano-scale production.. macro/mini-lego sized assembly), you may want to adjust the mesh size for the finite element method solver.</p> <blockquote> <p>software for 4D Printing</p> </blockquote> <p>If your 4th D refers to time.. then the discussion ends here.</p> <p>If your 4th D is a space (not time) dimension.. Then you need to convert your 4D geometric object into a 3D shadow (just like generating the normal 2D shadow from a 3D geometric object) 1st to proceed. just like an 3D object (eg cube) can have multiple equivalent 2D form (or shadow). The same applies for 4D to 3D. Once you get the 3D coordinates of the chosen 3D form, you may print it as usual. </p> <p>Software wise.. mathematica (are used in the some of the example I've seen, others unknown/selfcoded) or equivalent will do.. but the key here is not the software.. it's the visualization algorithm. If you can get the "shadowing" algorithm done right, any 3D/math software will do. </p> <p>p/s : I didn't expect the materials modelling question coming when I read the title (I really thought this question refers to extra space dimension) .. but yeah.. why not. It's a good postgraduate/research topic to take on. ( :</p>
404
<p>In C# there is the static property <a href="http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx" rel="noreferrer">Environment.Newline</a> that changed depending on the running platform.</p> <p>Is there anything similar in Java?</p>
<p><strong>As of Java 7 (and Android API level 19):</strong></p> <pre><code>System.lineSeparator() </code></pre> <p>Documentation: <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29" rel="noreferrer">Java Platform SE 7</a></p> <hr> <p><strong>For older versions of Java, use:</strong></p> <pre><code>System.getProperty("line.separator"); </code></pre> <p>See <a href="https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html" rel="noreferrer">https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html</a> for other properties.</p>
<p>Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of <code>\n</code> and <code>\r\n</code>, having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows <code>\r\n</code>, Unix/Linux/OSX <code>\n</code> and pre-OSX Mac <code>\r</code>.</p> <p>When you're <em>writing</em> text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use <code>\r\n</code> because it only recognizes the one kind of separator.</p>
30,679
<p>I just finished reading this post: <a href="https://developer.yahoo.com/performance/rules.html#flush" rel="nofollow noreferrer">https://developer.yahoo.com/performance/rules.html#flush</a> and have already implemented a flush after the top portion of my page loads (head, css, top banner/search/nav).</p> <p>Is there any performance hit in flushing? Is there such a thing as doing it too often? What are the best practices?</p> <p>If I am going to hit an external API for data, would it make sense to flush before hand so that the user isn't waiting on that data to come back, and can at least get some data before hand?</p>
<p>The technique described looks nice, but has several pitfalls:</p> <p>1) the time between PHP script start and end is small compared to transmission time; also, this saves the user about 0.5 seconds, according to your source. Is that a significant amount of time for you?</p> <p>2) this technique doesn't work with gzip output buffering</p> <p>3) if you flush too often, you'll be sending an almost-empty packet on flush, which might actually increase loading time (on slow, noisy connections).</p> <p>4) once you flush, you can't send any more headers</p> <p>5) (minor issue) the server response will come in chunked encoding, which means the client won't know the size in advance (therefore won't display "x% done" when downloading a file).</p> <p>On the other hand, if you expect your script to run for a loooong time (20+ seconds), it may be needed to send some data (spaces, for example) to keep the browser from timing out the connection.</p>
<p>Following Piskvor's point - if you are expecting a 20s+ wait, you may be better off providing a basic page (which can be gzipped) and using Ajax to update the page when the slow process has finished. You do start to infringe the basic usefulness of static html, though.</p>
45,944
<p>I have to read a txt file with lines formated like this:</p> <pre> 1: (G, 2), (F, 3) 2: (G, 2), (F, 3) 3: (F, 4), (G, 5) 4: (F, 4), (G, 5) 5: (F, 6), (c, w) 6: (p, f), (G, 7) 7: (G, 7), (G, 7) w: (c, w), (c, w) </pre> <p>Each line will feed a struct with its data (the 5 numbers or letters in it).<br> What's the best way to read the line and get the strings I want?<br> I'm currently using a long sequence of conditions using <code>fgetc</code> but that seems ugly and not very smart.<br> I can't use arrays because the lines may vary in size if the numbers have two digits.</p>
<p>I think you could parse it along the lines of:</p> <pre><code>fscanf(file,"%c: (%c, %c), (%c, %c)", &amp;first,&amp;second,&amp;third,&amp;fourth,&amp;fifth); </code></pre>
<p>fgets() and sscanf() as I remember</p>
36,352
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
<p>The only language I can think of to attempt such a mid-stream change would be Perl. Of course, Python is beating Perl to that particular finish line by releasing first. It should be noted, however, that Perl's changes are much more extensive than Python's and likely will be harder to detangle.</p> <p>(There's a price for Perl's "There's More Than One Way To Do It" philosophy.)</p> <p>There are examples like the changes from version to version of .NET-based languages (ironic, considering the whole point of .NET was supposed to be API stability and cross-platform compatibility). However, I would hardly call those languages "mature"; it's always been more of a design-on-the-go, build-the-plane-as-we-fly approach to things.</p> <p>Or, as I tend to think of it, most languages come from either "organic growth" or "engineered construction." Perl is the perfect example of organic growth; it started as a fancy text processing tool ala awk/sed and grew into a full language.</p> <p>Python, on the other hand, is much more engineered. Spend a bit of time wandering around the extensive whitepapers on their website to see the extensive debate that goes into every even minor change to the language's syntax and implementation.</p> <p>The idea of making these sorts of far-reaching changes is somewhat new to programming languages because programming languages themselves have changed in nature. It used to be that programming methodologies changed only when a new processor came out that had a new instruction set. The early languages tended to either be so low-level and married to assembly language (e.g. C) or so utterly dynamic in nature (Forth, Lisp) that such a mid-stream change wouldn't even come up as a consideration.</p> <p>As to whether or not the changes are good ones, I'm not sure. I tend to have faith in the people guiding Python's development, however; the changes in the language thus far have been largely for the better.</p> <p>I think in the days to come the Global Interpreter Lock will prove more central than syntax changes. Though the new multiprocessor library might alleviate most of that.</p>
<p>gcc regularly changes how it handles C++ almost every minor release. Of course, this is more a consequence of gcc tightening how they follow the rules, and less of C++ itself changing.</p>
34,462
<p>Could somebody give me a brief overview of the differences between HTTP 1.0 and HTTP 1.1? I've spent some time with both of the RFCs, but haven't been able to pull out a lot of difference between them. Wikipedia says this:</p> <blockquote> <p><strong>HTTP/1.1 (1997-1999)</strong></p> <p>Current version; persistent connections enabled by default and works well with proxies. Also supports request pipelining, allowing multiple requests to be sent at the same time, allowing the server to prepare for the workload and potentially transfer the requested resources more quickly to the client.</p> </blockquote> <p>But that doesn't mean a lot to me. I realize this is a somewhat complicated subject, so I'm not expecting a full answer, but can someone give me a brief overview of the differences at a bit lower level?<br /> By this I mean that I'm looking for the info I would need to know to implement either an HTTP server or application. I'm mostly looking for a nudge in the right direction so that I can figure it out on my own.</p>
<p><strong>Proxy support and the Host field:</strong></p> <p>HTTP 1.1 has a required Host header by spec.</p> <p>HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.</p> <p>Example:</p> <pre><code>GET / HTTP/1.1 Host: www.blahblahblahblah.com </code></pre> <p>This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.</p> <p>So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants. </p> <p><strong>Persistent connections:</strong></p> <p>HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection. </p> <p>In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of <a href="http://en.wikipedia.org/wiki/Slow-start" rel="noreferrer">TCP Slow Start</a>.</p> <p><strong>OPTIONS method:</strong></p> <p>HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.</p> <p><strong>Caching:</strong></p> <p>HTTP 1.0 had support for caching via the header: If-Modified-Since.</p> <p>HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags. </p> <p>HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers. </p> <p>There are also further additions relating to caching like the Cache-Control header. </p> <p><strong>100 Continue status:</strong></p> <p>There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body. </p> <p><strong>Much more:</strong></p> <ul> <li>Digest authentication and proxy authentication</li> <li>Extra new status codes</li> <li>Chunked transfer encoding</li> <li>Connection header</li> <li>Enhanced compression support</li> <li>Much much more. </li> </ul>
<p>HTTP 1.1 is the latest version of Hypertext Transfer Protocol, the World Wide Web application protocol that runs on top of the Internet's TCP/IP suite of protocols. compare to HTTP 1.0 , HTTP 1.1 provides faster delivery of Web pages than the original HTTP and reduces Web traffic.</p> <p>Web traffic Example: For example, if you are accessing a server. At the same time so many users are accessing the server for the data, Then there is a chance for hanging the Server. This is Web traffic.</p>
30,647
<p>I have been maintaining <a href="http://github.com/Pistos/watir-mirror" rel="noreferrer">the git mirror</a> of <a href="http://wtr.rubyforge.org/" rel="noreferrer">the watir project</a>. Some time a couple weeks ago, we had someone ready to submit their first git-based patch. Unfortunately, we ran into some issues regarding line endings (CRLF vs. LF, etc.) because of the multi-platform nature of the project.</p> <p>I tried what I could to set <a href="http://git-scm.com/docs/gitattributes" rel="noreferrer">the autocrlf option</a> (to 'input'), and do some --hard resets. However, a few days later, the daily update (git svn rebase) is spewing this error:</p> <pre><code>Incomplete data: Delta source ended unexpectedly </code></pre> <p>I've tried googling around for what to do, but even removing the autocrlf setting in the .git/config hasn't helped. I fear the working copy is corrupt, but I hope it is not unrecoverable.</p> <p>Obviously, a possible course of action is to just re-import from svn and start a fresh mirror, but I hope we don't have to do that, since the current watir-mirror has already been forked, and people have developed new code in their forks.</p> <p>Thanks in advance for any help.</p>
<p>I had this same problem in trying to create a git repository from the brlcad svn repository. I solved it by doing <code>git svn reset --r XXXXX</code>, where I set XXXXX to be about 50 revisions prior to the one that originally produced the error. </p> <p>Stepping back a single revision was not successful in resolving the error. As part of the process, I received errors from git about HEAD not being defined. To resolve this, I did a <code>git svn find-rev XXXXX</code> to determine the hash corresponding to the revision I wanted, then git checkout. After this, the errors about HEAD were gone and the <code>git svn reset -r XXXXX</code> worked.</p>
<p>i had the same problem and like Todd's case, going to a previous revision fixed the problem. </p> <p>I think the solution is to go to two steps previous revision of the problematic file.</p>
25,913
<p>I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.</p> <p>In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.</p> <p>Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.</p> <p>These are the settings that I'm using on both IIS 6.0 and 7.0:</p> <pre><code>&lt;authentication mode="Windows"&gt; &lt;identity impersonate="true"&gt; </code></pre> <p>What changed from 6.0 to 7.0?</p>
<p>There has been changes between IIS7 and IIS6.0. I found for you one blog post that might actually help you (<a href="http://mvolo.com/blogs/serverside/archive/2007/12/08/IIS-7.0-Breaking-Changes-ASP.NET-2.0-applications-Integrated-mode.aspx" rel="noreferrer">click here to see it</a>).</p> <p>Are you running your application in Integrated Mode or in Classic Mode? From what I saw, putting the Impersonate attribute at true should display you a 500 error with the following error message:</p> <blockquote> <p>Internal Server Error. This is HTTP Error 500.19: The requested page cannot be accessed because the related configuration data for the page is invalid.</p> </blockquote> <p>Here is the workaround that is proposed:</p> <blockquote> <p>Workaround:</p> <p>1) If your application does not rely on impersonating the requesting user in the BeginRequest and AuthenticateRequest stages (the only stages where impersonation is not possible in Integrated mode), ignore this error by adding the following to your application’s web.config: </p> <pre><code>&lt;validation validateIntegratedModeConfiguration="false" </code></pre> <p>/></p> <p></p> <p>2) If your application does rely on impersonation in BeginRequest and AuthenticateRequest, or you are not sure, move to classic mode.</p> </blockquote> <p>I hoped that was useful to understand how IIS 7.0 now works.</p>
<p>Interesting... I have the opposite problem - <strong>Not being able</strong> to get the authentication to be passed from the client browser, through the webserver and onto the database within a large corporate network over firewalls.</p> <p>I also feel that "end to end user" authentication to the database is a bad idea and a potential security risk. There is nothing to stop the end user from loading up SQL Query and connecting directly to your database, so you'd better have your schema locked down!</p> <p>@Esteban - Clarified my <em>not very useful in helping you</em> answer.</p>
3,161
<p>Sounds like a weird question, but say I have something like this:</p> <pre><code>$.post( "/myajax.php", { "param1": value1, "param2": value2 }, function( data, status ) { if( status == "success" ) { $("#someid").html( data ); } }, "html" ); </code></pre> <p>While myajax.php is doing whatever it needs to do, it decides that it does not need to make any changes to <code>#someid</code>. If it just returns, the <code>someid</code> element is blanked, but I want to leave it alone. How can the php query return in such a way that <code>status != "success"</code>? </p>
<p>When a user accesses an application URL without a session cookie, he is redirected to the SSO system. He then logs into the SSO form, which then redirects him back to your app with a ticket ID that you can look up in the SSO system to get cridentials.</p> <p>Also, take a look at <a href="http://www.atlassian.com/software/crowd/" rel="nofollow noreferrer">Crowd</a> and <a href="http://www.ja-sig.org/products/cas/" rel="nofollow noreferrer">CAS</a>.</p>
<p>Check out <a href="http://www.ja-sig.org/products/cas/index.html" rel="nofollow noreferrer">JA-SIG CAS</a>. Even if you build your own, you should look at their architecture for ideas on how to implement.</p>
37,236
<p>Is it possible to check if a dynamically loaded assembly has been signed with a specific strong name?</p> <p>Is it enough / secure to compare the values returned from <strong>AssemblyName.GetPublicKey()</strong> method?</p> <pre><code>Assembly loaded = Assembly.LoadFile(path); byte[] evidenceKey = loaded.GetName().GetPublicKey(); if (evidenceKey != null) { byte[] internalKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey(); if (evidenceKey.SequenceEqual(internalKey)) { return extension; } } </code></pre> <p>Can't this be spoofed? I am not sure if the SetPublicKey() method has any effect on a built assembly, but even the MSDN documentation shows how you can use this on a dynamically generated assembly (reflection emit) so that would mean you could extract the public key from the host application and inject it into an assembly of your own and run mallicious code if the above was the safe-guard, or am I missing something?</p> <p>Is there a more correct and secure approach? I know if the reversed situation was the scenario, that is, where I wanted to secure the assembly from only being called by signed hosts then I could tag the assembly with the StrongNameIdentityPermission attribute.</p>
<p><a href="http://www.codinghorror.com/blog/archives/000749.html" rel="noreferrer">This Post</a> by Jeff Atwood on his blog <a href="http://www.codinghorror.com" rel="noreferrer">Coding Horror</a> goes into the purpose of comments in general. Something you might think is 'duh' really isn't -- especially in the 'real world' when you see comments like the one below:</p> <pre><code>//Connect to the Database Db.Connect(); </code></pre> <p>And of course, there's the corollary to that post: <a href="http://www.codinghorror.com/blog/archives/001150.html" rel="noreferrer">Coding Without Comments</a>.</p>
<h2>Inside VS</h2> <p>Comments are relatively simple.</p> <p>You can use for <strong>single line</strong> :</p> <pre><code>//This is a single line comment </code></pre> <p>You can use for <strong>multiple line</strong>:</p> <pre><code>/* Multiple lines */ </code></pre> <p>For <strong>method</strong> you can use : </p> <pre><code> /// &lt;summary&gt; /// This is a description /// &lt;/summary&gt; /// &lt;param name="sender"&gt;Description of variable SENDER&lt;/param&gt; /// &lt;param name="e"&gt;Description of variable E&lt;/param&gt; </code></pre> <h2>Outside VS</h2> <p>When you go in the <strong>Project Property</strong> you can output all comments into XML and manipulate them.</p> <h2>Good practice</h2> <p>Comments should not be used to describe WHAT the code do but WHY or HOW if it's not clear.</p>
39,779
<p>Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?</p> <p>Examples: </p> <p>10.23 becomes $10.23<br> $1.45 stays $1.45<br> 10.a raises error due to not being a valid number </p> <p>I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.</p>
<p>The ASP.NET <a href="https://github.com/DevExpress/AjaxControlToolkit/wiki/MaskedEdit" rel="nofollow noreferrer">MaskedEdit</a> control from the <a href="https://github.com/DevExpress/AjaxControlToolkit/wiki" rel="nofollow noreferrer">AJAX Control Toolkit</a> can accomplish what you're asking for.</p>
<p>In the .CS you could do a pattern match along the lines of,</p> <pre><code>string value = text_box_to_validate.Text; string myPattern = @"^\$(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})|\d{1,3}(\.\d{2})|\.\d{2})$"; Regex r = new Regex(myPattern); Match m = r.Match(value); if (m.Success) { //do something -- everything passed } else { //did not match //could check if number is good, but is just missing $ in front } </code></pre>
24,694
<p>I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..).</p> <h1>1 - Via Message map:</h1> <pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() </code></pre> <h1>2 - Via afx_message:</h1> <pre><code>afx_msg type OnSize(...); </code></pre> <p>They seem to be used interchangeably, which one should be used or does it depend on other factors?</p>
<p>Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, <code>OnSize</code>).</p> <pre><code>class CClassWnd : public CBaseClassWnd { ... afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP }; </code></pre> <p><code>afx_msg</code> is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention.</p> <p>The message map is then defined in the class's .cpp file:</p> <pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ON_WM_SIZE() END_MESSAGE_MAP() </code></pre> <p>These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The <code>ON_WM_SIZE</code> macro allows the <code>wParam</code> and <code>lParam</code> message parameters in the <code>WM_SIZE</code> message to be decoded into more meaningful values for the message handler function (<code>nType</code>, <code>cx</code>, and <code>cy</code> in this case). MFC provides macros for most window messages (<code>WM_LBUTTONDOWN</code>, <code>WM_DESTROY</code>, etc).</p> <p>You can find more information on how message maps work in MFC <a href="http://msdn.microsoft.com/en-us/library/0x0cx6b1.aspx" rel="nofollow noreferrer">here</a> on MSDN.</p>
<p>Some of the Windows message are already handled by <strong>MFC</strong>, so in these cases you can get away with adding just the method to your derived class. </p> <p>For example the <strong>CWnd</strong> class (as do many other MFC classes) already maps a few Windows messages into it's message map (i.e. <em>ON_WM_DRAWITEM</em>, <em>ON_WM_MEASUREITEM</em>, <em>ON_WM_ENTERIDLE</em> etc, etc). </p> <p>But any other message not already mapped by MFC will need to have both a class method and an entry in the message map for it to work.</p>
24,472
<p>Ok, so I have this regex:</p> <pre><code>( |^|&gt;)(((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6}))|((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8})))( |$|&lt;) </code></pre> <p>It formats Dutch and Belgian phone numbers (I only want those hence the 31 and 32 as country code).</p> <p>Its not much fun to decipher but as you can see it also has a lot duplicated. but now it does handles it very accurately</p> <p>All the following European formatted phone numbers are accepted</p> <pre><code>0031201234567 0031223234567 0031612345678 +31(0)20-1234567 +31(0)223-234567 +31(0)6-12345678 020-1234567 0223-234567 06-12345678 0201234567 0223234567 0612345678 </code></pre> <p>and the following false formatted ones are not</p> <pre><code>06-1234567 (mobile phone number in the Netherlands should have 8 numbers after 06 ) 0223-1234567 (area code with home phone) </code></pre> <p>as opposed to this which is good.</p> <pre><code>020-1234567 (area code with 3 numbers has 7 numbers for the phone as opposed to a 4 number area code which can only have 6 numbers for phone number) </code></pre> <p>As you can see it's the '-' character that makes it a little difficult but I need it in there because it's a part of the formatting usually used by people, and I want to be able to parse them all.</p> <p>Now is my question... do you see a way to simplify this regex (or even improve it if you see a fault in it), while keeping the same rules?</p> <p>You can test it at <a href="http://regextester.com/" rel="nofollow noreferrer">regextester.com</a></p> <p>(The '( |^|>)' is to check if it is at the start of a word with the possibility it being preceded by either a new line or a '>'. I search for the phone numbers in HTML pages.) </p>
<p>First observation: reading the regex is a nightmare. It cries out for Perl's /x mode.</p> <p>Second observation: there are lots, and lots, and lots of capturing parentheses in the expression (42 if I count correctly; and 42 is, of course, "The Answer to Life, the Universe, and Everything" -- see Douglas Adams "Hitchiker's Guide to the Galaxy" if you need that explained).</p> <p>Bill the Lizard notes that you use '<code>(-)?( )?</code>' several times. There's no obvious advantage to that compared with '<code>-? ?</code>' or possibly '<code>[- ]?</code>', unless you are really intent on capturing the actual punctuation separately (but there are so many capturing parentheses working out which '$<em>n</em>' items to use would be hard).</p> <p>So, let's try editing a copy of your one-liner:</p> <pre><code>( |^|&gt;) ( ((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{2})(-)?( )?)?)([0-9]{7})) | ((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{3})(-)?( )?)?)([0-9]{6})) | ((((((\+|00)(31|32)( )?(\(0\))?)|0)([0-9]{1})(-)?( )?)?)([0-9]{8})) ) ( |$|&lt;) </code></pre> <p>OK - now we can see the regular structure of your regular expression.</p> <p>There's much more analysis possible from here. Yes, there can be vast improvements to the regular expression. The first, obvious, one is to extract the international prefix part, and apply that once (optionally, or require the leading zero) and then apply the national rules.</p> <pre><code>( |^|&gt;) ( (((\+|00)(31|32)( )?(\(0\))?)|0) (((([0-9]{2})(-)?( )?)?)([0-9]{7})) | (((([0-9]{3})(-)?( )?)?)([0-9]{6})) | (((([0-9]{1})(-)?( )?)?)([0-9]{8})) ) ( |$|&lt;) </code></pre> <p>Then we can simplify the punctuation as noted before, and remove some plausibly redundant parentheses, and improve the country code recognizer:</p> <pre><code>( |^|&gt;) ( (((\+|00)3[12] ?(\(0\))?)|0) (((([0-9]{2})-? ?)?)[0-9]{7}) | (((([0-9]{3})-? ?)?)[0-9]{6}) | (((([0-9]{1})-? ?)?)[0-9]{8}) ) ( |$|&lt;) </code></pre> <p>We can observe that the regex does not enforce the rules on mobile phone codes (so it does not insist that '06' is followed by 8 digits, for example). It also seems to allow the 1, 2 or 3 digit 'exchange' code to be optional, even with an international prefix - probably not what you had in mind, and fixing that removes some more parentheses. We can remove still more parentheses after that, leading to:</p> <pre><code>( |^|&gt;) ( (((\+|00)3[12] ?(\(0\))?)|0) # International prefix or leading zero ([0-9]{2}-? ?[0-9]{7}) | # xx-xxxxxxx ([0-9]{3}-? ?[0-9]{6}) | # xxx-xxxxxx ([0-9]{1}-? ?[0-9]{8}) # x-xxxxxxxx ) ( |$|&lt;) </code></pre> <p>And you can work out further optimizations from here, I'd hope.</p>
<p>Split it into multiple expressions. For example (pseudo-code)...</p> <pre><code>phone_no_patterns = [ /[0-9]{13}/, # 0031201234567 /+(31|32)\(0\)\d{2}-\d{7}/ # +31(0)20-1234567 # ..etc.. ] def check_number(num): for pattern in phone_no_patterns: if num matches pattern: return match.groups </code></pre> <p>Then you just loop over each pattern, checking if each one matches..</p> <p>Splitting the patterns up makes its easy to fix specific numbers that are causing problems (which would be horrible with the single monolithic regex)</p>
33,734
<p>I use SQLite for a number of application on the desktop and PDA. Most operations are readonly, as SQLite functions as a data store for reference material in my applications.</p> <p>Basically, I am looking for suggestions on improving performance in a scenario where you know the access to the data is only read-only.</p> <p>Maybe via various pragma settings? etc...</p> <p>SQLite performance is excellent, however on the PDA when you have multiple databases I can see a small performance hit. I dont think this is a problem with SQLite, just the reality of the speed of a PDA. However, having said that, maybe there are ways to improve it.</p> <hr> <p>Good advice and well put. I am hoping for something more specific in telling the engine about what I am doing. For example, telling the engine there will be no multiple writes to the DB, or modifying the cache handling in some way.</p> <p>However, I am glad you called attention to the "design" aspect of the database as a leading issue.</p>
<p>The standard database performance tips still apply:</p> <ul> <li>Make sure your queries use indexes rather than full table scans</li> <li>Be as selective as you can in your queries so you aren't pulling unneeded rows from the db</li> <li>Select only the columns you want</li> </ul>
<p>You can call <a href="http://sqlite.org/c3ref/open.html" rel="nofollow noreferrer">sqlite3_open_v2()</a> with the flag <a href="http://sqlite.org/c3ref/c_open_create.html" rel="nofollow noreferrer">SQLITE_OPEN_READONLY</a>. I have no idea if sqlite3 actually uses that to optimize its behavior, or just as way to set the appropriate permissions on the open call it makes to the OS.</p>
32,230
<p>I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.</p> <p>In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.</p> <p>Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?</p>
<p>The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with <a href="http://docs.python.org/library/stringio.html" rel="nofollow noreferrer">StringIO</a>:</p> <pre><code>from cStringIO import StringIO s = "My very long string I want to read like a file" file_like_string = StringIO(s) data = file_like_string.read(10) </code></pre> <p>Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.</p>
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-pickle.html" rel="nofollow noreferrer">Pickle and cPickle</a> modules may also be helpful to you.</p>
40,025
<p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p> <p>The implementation can be in c# or python.</p> <p>Thanks.</p>
<p>In Python, there is <a href="https://docs.python.org/3/library/difflib.html" rel="nofollow noreferrer">difflib</a>, as also others have suggested.</p> <p><code>difflib</code> offers the <a href="https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher" rel="nofollow noreferrer">SequenceMatcher</a> class, which can be used to give you a similarity ratio. Example function:</p> <pre><code>def text_compare(text1, text2, isjunk=None): return difflib.SequenceMatcher(isjunk, text1, text2).ratio() </code></pre>
<p>One method I've employed for a different functionality, to calculate how much data was new in a modified file, could perhaps work for you as well.</p> <p>I have a diff/patch implementation C# that allows me to take two files, presumably old and new version of the same file, and calculate the "difference", but not in the usual sense of the word. Basically I calculate a set of operations that I can perform on the old version to update it to have the same contents as the new version.</p> <p>To use this for the functionality initially described, to see how much data was new, I simple ran through the operations, and for every operation that copied from the old file verbatim, that had a 0-factor, and every operation that inserted new text (distributed as part of the patch, since it didn't occur in the old file) had a 1-factor. All characters was given this factory, which gave me basically a long list of 0's and 1's.</p> <p>All I then had to do was to tally up the 0's and 1's. In your case, with my implementation, a low number of 1's compared to 0's would mean the files are very similar.</p> <p>This implementation would also handle cases where the modified file had inserted copies from the old file out of order, or even duplicates (ie. you copy a part from the start of the file and paste it near the bottom), since they would both be copies of the same original part from the old file.</p> <p>I experimented with weighing copies, so that the first copy counted as 0, and subsequent copies of the same characters had progressively higher factors, in order to give a copy/paste operation some "new-factor", but I never finished it as the project was scrapped.</p> <p>If you're interested, my diff/patch code is available from my Subversion repository.</p>
17,554
<p>I've been pulling my hear out over this problem for a few hours yesterday:</p> <p>I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to <b>latin2</b>. But, the web application (CMS Made Simple written in PHP) using it displays pages in <b>utf8</b>...</p> <p>However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used).</p> <p>I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which:</p> <ul> <li>looks perfect in any editor (like Notepad+) when displaying in <b>UTF-8</b> - all characters display properly</li> <li>all tables in the script have default charset set to <b>latin2</b></li> <li>it has "/*!40101 SET NAMES latin2 */;" line at the beginning (among other settings)</li> </ul> <p>Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname &lt; dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages.</p> <p>I tried setting:<br> SET character_set_client = utf8;<br> SET character_set_connection = latin2;</p> <p>And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :).</p> <p>I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing.</p> <p>Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html" rel="noreferrer">9.1.4. Connection Character Sets and Collations</a> but found nothing helpful there.</p> <p>Thanks, Matt</p>
<p>Did you try adding the --default-character-set=name option, like this:</p> <pre><code>mysql --default-character-set=utf8 -h ddd -u zzz -p dbname &lt; dump.sql </code></pre> <p>I had that problem before and it worked after using that option.</p> <p>Hope it helps!</p>
<p>SOLUTION for me:</p> <p>set this option in your php file, after <strong>mysql_connect</strong> (or after <strong>mysql_select_db</strong>)..</p> <pre><code>mysql_query("SET NAMES 'utf8'"); </code></pre>
18,371
<p>I have a bunch of java files from which I want to remove the javadoc lines with the license [am changing it on my code].</p> <p>The pattern I am looking for is</p> <p><code>^\* \* ProjectName .* USA\.$</code> </p> <p>but matched across lines</p> <p>Is there a way sed [or a commonly used editor in Windows/Linux] can do a search/replace for a multiline pattern?</p>
<p>Here's the <a href="http://www.grymoire.com/Unix/Sed.html#uh-47" rel="nofollow noreferrer">appropriate reference point</a> in my favorite sed tutorial.</p>
<p>Yes. Are you using sed, awk, perl, or something else to solve this problem?</p> <p>Most regular expression tools allow you to specify multi-line patterns. Just be careful with regular expressions that are too greedy, or they'll match the code between comments if it exists. </p> <p>Here's an example: </p> <pre><code>/\*(?:.|[\r\n])*?\*/ perl -0777ne 'print m!/\*(?:.|[\r\n])*?\*/!g;' &lt;file&gt; </code></pre> <blockquote> <p>Prints out all the comments run together. The (?: notation must be used for non-capturing parenthesis. / does not have to be escaped because ! delimits the expression. -0777 is used to enable slurp mode and -n enables automatic reading.</p> </blockquote> <p>(From: <a href="http://http:/ostermiller.org/findcomment.html" rel="nofollow noreferrer">http://ostermiller.org/findcomment.html</a> )</p>
21,031
<p>What are the key strengths of ASP.NET Webforms (2.0-3.5)? I'm not looking for comparisons to other frameworks, I'm just am looking for feedback on ASP.NET as it stands today.</p>
<p>One key strength (to some) is a drag-and-drop development environment integrated into Visual Studio. This allows you to get simple things up and running quickly, but can also be a liability when the time comes that you actually need to understand the underlying code.</p>
<p>It lets you build web applications without having a good understanding of the underlying concepts such as HTTP. This has its own downsides.</p>
13,469
<p>I'm hosting Python script with Python for Delphi components inside my Delphi application. I'd like to create background tasks which keep running by script.</p> <p>Is it possible to create threads which keep running even if the script execution ends (but not the host process, which keeps going on). I've noticed that the program gets stuck if the executing script ends and there is thread running. However if I'll wait until the thread is finished everything goes fine.</p> <p>I'm trying to use "threading" standard module for threads.</p>
<p>Python has its own threading module that comes standard, if it helps. You can create thread objects using the threading module.</p> <p><a href="https://docs.python.org/2/library/threading.html" rel="nofollow noreferrer">threading Documentation</a></p> <p><a href="https://docs.python.org/3/library/threading.html" rel="nofollow noreferrer">thread Documentation</a></p> <p>The thread module offers low level threading and synchronization using simple Lock objects.</p> <p>Again, not sure if this helps since you're using Python under a Delphi environment.</p>
<p>Threads by definition are part of the same process. If you want them to keep running, they need to be forked off into a new process; see os.fork() and friends.</p> <p>You'll probably want the new process to end (via exit() or the like) immediately after spawning the script.</p>
8,907
<p>In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.</p> <p>Here's the method provided:</p> <pre><code>unsigned int getbits(unsigned int x, int p, int n) { return (x &gt;&gt; (p + 1 - n)) &amp; ~(~0 &lt;&lt; n); } </code></pre> <p>The idea is that, for the given number <em>x</em>, it will return the <em>n</em> bits starting at position <em>p</em>, counting from the right (with the farthest right bit being position 0). Given the following <code>main()</code> method:</p> <pre><code>int main(void) { int x = 0xF994, p = 4, n = 3; int z = getbits(x, p, n); printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z); return 0; } </code></pre> <p>The output is:</p> <blockquote> <p><code>getbits(63892 (f994), 4, 3) = 5 (5)</code></p> </blockquote> <p>I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.</p> <p>The part I'm specifically having issues with is the complements piece: <code>~(~0 &lt;&lt; n)</code>. I think I get the first part, dealing with <em>x</em>; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)</p> <p>Any help?</p>
<p>Let's use 16 bits for our example. In that case, <code>~0</code> is equal to</p> <pre><code>1111111111111111 </code></pre> <p>When we left-shift this <code>n</code> bits (3 in your case), we get:</p> <pre><code>1111111111111000 </code></pre> <p>because the <code>1</code>s at the left are discarded and <code>0</code>s are fed in at the right. Then re-complementing it gives:</p> <pre><code>0000000000000111 </code></pre> <p>so it's just a clever way to get <code>n</code> 1-bits in the least significant part of the number.</p> <p>The &quot;x bit&quot; you describe has shifted the given number (<code>f994 = 1111 1001 1001 0100</code>) right far enough so that the least significant 3 bits are the ones you want. In this example, the input bits you're requesting are there, all other input bits are marked <code>.</code> since they're not important to the final result:</p> <pre><code>ff94 ...........101.. # original number &gt;&gt; p+1-n [2] .............101 # shift desired bits to right &amp; ~(~0 &lt;&lt; n) [7] 0000000000000101 # clear all the other (left) bits </code></pre> <p>As you can see, you now have the relevant bits, in the rightmost bit positions.</p>
<p>In <code>ANSI C ~0 &gt;&gt; n</code> causes undefined behavior </p> <p>// the post about left shifting causing a problem is wrong.</p> <p>unsigned char m,l;</p> <p>m = ~0 >> 4; is producing 255 and its equal to ~0 but, </p> <p>m = ~0; l = m >> 4; is producing correct value 15 same as:</p> <p>m = 255 >> 4;</p> <p>there is no problem with left shifting negative <code>~0 &lt;&lt;</code> whatsoever </p>
24,045
<p>I have a layout which uses min-width and works great. So I came to add a footer which I want to stick to the bottom. Firefox will display everything perfectly while with IE, when min-width takes in effect and the vertical scroll bar kicks in, the horizontal scroll bar also appears even thought my content isn't even close to needing it.</p> <p>I have tried every solution I could find about the bottom footer and they all seem to behave that way.</p> <p>Is there a solution to this problem or will I have to realize once again that IE is not-so-good? ;)</p> <p>Thank you.</p>
<p>Have you tried using overflow:hidden;?</p> <p><em>Edit</em>: You might also want to try overflow:auto; with your margins set to margin:0;</p>
<p>I know that jquery ui has a slider plugin that can duplicate the functionality. Here's a demo that does something similar. <a href="http://ui.jquery.com/repository/real-world/product-slider/" rel="nofollow noreferrer">http://ui.jquery.com/repository/real-world/product-slider/</a> Might be a bit heavy for your application, but it's worth a look. </p>
26,202
<p>Excel macros do not seem to allow the use of "undo" after running them. Is there any way to bake <code>undo</code> functionality into a VBA macro in Excel?</p>
<p>Excel VBA has the <code>Application.OnUndo</code> function to handle this:</p> <pre><code>Public Sub DoSomething ... do stuff here Application.OnUndo "Undo something", "UnDoSomething" End Sub Public Sub UnDoSomething ... reverse the action here End Sub</code></pre>
<p>I always save immediately before running my macros (during testing at least) then, if everything goes pear-shaped, I can just exit without saving and re-open it.</p> <p>Baking it into the actual macro, you'll have to basically record the old state of everything that changes (cell contents, formulae, formatting and so on) in a list then have an undo macro which plays back that list in reverse order.</p> <p>For example if your macro changes a cell C22 contents from "3" to "7" and formatting from "general" to "number, 2 decimals), your list would be:</p> <pre><code>C22 value 3 C22 format general </code></pre> <p>Playing this back in reverse order (with another macro) would revert the changes.</p> <p>You could have a whole extra sheet to hold the macro undo information such as:</p> <pre><code>Step Cell Type Value ---- ---- ----- ------- 1 C22 value 3 C22 format general 2... </code></pre> <p>It wouldn't integrate very well with the 'real' undo unfortunately, but I don't think there's any way around that.</p>
44,053
<p>Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:</p> <pre><code>window.open(src, 'newWin', 'fullscreen="yes"') </code></pre> <p>apparently only worked for old version of IE.</p>
<p>Use <code>screen.availWidth</code> and <code>screen.availHeight</code> to calculate a suitable size for the height and width parameters in <code>window.open()</code></p> <p>Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.</p>
<p><strong>Try this. This works for me and with any link you want, or anything in the popup</strong></p> <p>Anything you chose will be shown in a PopUp window in a full screen size within a PopUp Window.</p> <pre><code>&lt;script language="JavaScript"&gt; function Full_W_P(url) { params = 'width='+screen.width; params += ', height='+screen.height; params += ', top=0, left=0' params += ', fullscreen=yes'; params += ', directories=no'; params += ', location=no'; params += ', menubar=no'; params += ', resizable=no'; params += ', scrollbars=no'; params += ', status=no'; params += ', toolbar=no'; newwin=window.open(url,'FullWindowAll', params); if (window.focus) {newwin.focus()} return false; } &lt;/script&gt; &lt;input type="button" value="Open as Full Window PopUp" onclick="javascript:Full_W_P('http://www.YourLink.com');"&gt;&lt;/input&gt; </code></pre>
20,812
<p>When I create a new project (or even when I edit the Sample Project) there is no way to add Description to the project.</p> <p>Or am I blind to the obvious?</p>
<p>There's no such thing as a project description, really. There's a column in the Projects page which is used so you can see which project is the default, built-in inbox, and we couldn't think of anything better to put as the column header for that column.</p>
<p>The description is mostly for system projects, like e-mail inbox.</p> <p>You might be able to set one in the underlying DB table.</p>
3,545
<p>Many of our transactions are comprised of calculations that are comprised of other calculations. How did you represent the hierarchy / execution graph to users? Was there a specific control you found that worked well? </p> <p>How would you project the result of a change to one of the formulas before committing that alteration? One suggestion was to show the altered formula in a different color. For a large set off formulas, how would you make alterations prominent?</p>
<p>I haven't had to do this, but I'd do something like the following:</p> <p>Use a tree view-type control. Have each inner calculation be separately collapsible. The control can start out with everything collapsed, then the user can click through to see the inner calculations. (If the inner calculations have names, then use these as labels. If they don't, you can use the first few characters from the calculation to represent it).</p> <p>I'm not sure what you mean by your last question, but would this work? Every time the user changes an inner calculation, mark everything that is affected by it with red. This way it'll be immediately obvious what has changed, and whether there were any unintended side effects.</p>
<p>I haven't had to do this, but I'd do something like the following:</p> <p>Use a tree view-type control. Have each inner calculation be separately collapsible. The control can start out with everything collapsed, then the user can click through to see the inner calculations. (If the inner calculations have names, then use these as labels. If they don't, you can use the first few characters from the calculation to represent it).</p> <p>I'm not sure what you mean by your last question, but would this work? Every time the user changes an inner calculation, mark everything that is affected by it with red. This way it'll be immediately obvious what has changed, and whether there were any unintended side effects.</p>
42,300
<p>For my Frankenstein's printer I am at a loss with the hotend mount. I cannot drill holes of 16 (upper diameter) and 12 mm (clamping diameter, 6mm high) which i would need to mount the E3D V6 clone I have.</p> <p>What I am looking for: a hotend mount plate that tightly fixes the hotend while having some holes for screws to mount it to the horizontally moving x-y drives. As I cannot print yet, it needs to be manufacturable at home. I thought of something like this:<br> <a href="http://www.thingiverse.com/thing:285405" rel="nofollow">http://www.thingiverse.com/thing:285405</a><br> I could get a piece of wood thin enough to fit the 6mm gap for the hotend, would not really be able to put any screws through it along the flat axis. also I would have to glue the layer with a 16mm hole on top. Not to say that I don't own a drillbit of 16mm diameter...</p> <p>Are there some completely different ideas around which I didn't think of yet?</p> <p>Additional info: the x-y axes are made from a scanner bed and an underneath mounted dvd drive laser positioner. Ideally, I'd want to mount the hotend directly to the DVD drive but a) there is almost no space for that, and b) I'm pretty sure I will burn the DVD drive's motor somewhere along the way, so I don't want to put too much work in the individual DVD drive.</p>
<p>If you do not have the tools to fabricate this component yourself, but have a 3D model available, I would suggest getting someone else to 3D print it for you.</p> <p>There are multiple options for getting your model printed, such as:</p> <ul> <li>Friends</li> <li>Your local makerspace, library or similar</li> <li><a href="https://www.3dhubs.com/" rel="nofollow">3D Hubs</a> </li> <li><a href="https://www.makexyz.com/" rel="nofollow">MakeXYZ</a></li> <li><a href="http://www.shapeways.com/" rel="nofollow">Shapeways</a></li> <li><a href="http://www.sculpteo.com/en/" rel="nofollow">Sculpteo</a></li> <li>and so on..</li> </ul> <p>Good luck!</p>
<p>If you do not have the tools to fabricate this component yourself, but have a 3D model available, I would suggest getting someone else to 3D print it for you.</p> <p>There are multiple options for getting your model printed, such as:</p> <ul> <li>Friends</li> <li>Your local makerspace, library or similar</li> <li><a href="https://www.3dhubs.com/" rel="nofollow">3D Hubs</a> </li> <li><a href="https://www.makexyz.com/" rel="nofollow">MakeXYZ</a></li> <li><a href="http://www.shapeways.com/" rel="nofollow">Shapeways</a></li> <li><a href="http://www.sculpteo.com/en/" rel="nofollow">Sculpteo</a></li> <li>and so on..</li> </ul> <p>Good luck!</p>
227
<p>Using C# .NET 2.0, I have an owner-drawn ListView where I'm overriding the OnDrawColumnHeader, OnDrawItem and OnDrawSubitem events. If I set the View property to Details at design-time, everything works beautifully and I can switch the View property and all view modes display as they should (I'm not using Tile view). However, if I start in any other View, both the List and Details views are blank.</p> <p>I know you'll probably want to see code, but there's a lot of it, so I'm hesitant to post that much, but can if necessary. I'm more curious if someone has seen this before, and/or might have an inkling of how to fix it. The View property will be a user-saved setting, so I won't always be able to start in Details view by default.</p>
<p>The WinForms ListView is mostly a layer of abstraction of the top of the actual Windows control, so there are aspect of its behaviour that are, well, counterintuitive is a polite way of putting things.</p> <p>I have a vague recollection, from back in my days as a Delphi developer, that when you are Owner drawing a ListView, the subitems of the control aren't actually populated unless your Listview is in "Details" mode when you load the items.</p> <p>Things to try ... </p> <p>... force the WinForms control to recreate the underlying windows handle after you change the display style. If memory serves, DestroyHandle() is the method you want.</p> <p>... assuming you have a "Refresh" in your application to reload the data, do things work properly when you refresh after changing the display style?</p> <p>... if all else fails, beg borrow or steal a copy of Charles' Petzolds classic on windows programming.</p>
<p>If you configure it correctly using the designer, just go into the generated designer code and see what code was emitted by Visual Studio to get it to work right. THen just emulate that code.</p>
19,760
<p>What are your opinions (as users as well as developers) on begware that e.g. at the start screen or intermittently shows a modal dialog for x seconds? What about other methods of getting the user to pay (or send you a postcard or any other kind of appreciation) instead of using the trail version?</p>
<p>Nagware is a bit pointless Imo, any thing you do to limit the software so that the "free" version is somehow encumbered will ultimately lead to it being reverse engineered and people will just download the <strong>out dated</strong> and possibly <strong>virus infected</strong> alternative of your software, which although not your doing, makes your software look bad. </p> <p>I know this isn't viable for all software types, but whats nice is to just give up that fight, and give your software away for free, and then find other circumstances that make you money from the software. </p> <ul> <li>Dual License, Free for Private/Non-Profit use, Licensed for Corporations/Companies. </li> <li>Charge for consumable releated services , ie: <ul> <li>Support </li> <li>Subscription to online service ( many games do this )</li> </ul></li> <li>Aferro GPL: Anybody can use it but must share their source to all people using it. People wanting to <em>not</em> share have to contribute a licensing fee.</li> </ul> <p>Many ideas just have different payoff rates, the "give it away" and then collect funds on related services may sound like it will never help you, but being free gets it out there faster, and then its a numbers game as to when you'll have a large enough base to fuel the other services. </p> <p>( The contra-idea is having a product that costs millions, you sell once, and it doesn't spread because of the high cost )</p>
<p>I really don't find they actually accomplish that much. I've gone on using things like WinZip, without paying for a license, for years, watching it count up all 1000 days I've been using it, simply because I didn't think the price they were asking was worth not seeing the nag screen. If the person doesn't want to buy your program, showing them a nag screen won't give them any extra incentive to buy it.</p>
32,155
<p>Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include</p> <pre><code>\ / &lt; &gt; ? * : </code></pre> <p>I know HOW to validate names (a regular expression).</p> <p>I need to validate filenames entered by users. </p> <p>My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!</p>
<p>No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.</p> <p>Also, if trying to port an Windows app to Mac or Unix it is best to use:</p> <pre><code>File.separator </code></pre> <p>To determine the correct file separator to use on each platform.</p>
<p>When you create a <code>new File</code> the inputted arguments will be normalized by a platform specific implementation of the <code>java.io.FileSystem</code> class. There are no Java specific restrictions that I know of.</p> <p>and yes, always use <code>File.separator</code>.</p>
8,926
<p>Is there a way to call an external script or program from Flash CS3 every time it builds a SWF file? I'd like to add subversion information using subwcrev - the SVN keywords don't work because they only update when the version class file is updated.</p>
<p>I'm not sure what are JSFL capabilities these days, but I'd say inside Flash IDE is your only bet. JSFL is a language to extend the Flash IDE, but I'm not sure you can do this.</p> <p>On a related note, adding SVN information to your SWFs is not trivial. You'd probably need SVN hooks to put the information <em>before</em> actually compiling the SWF itself. </p> <p>I doubt you can do this compiling with Flash IDE but I'd be more than happy to hear otherwise.</p>
<p>With thanks to Zárate, it looks like JSFL is the answer, or at least part of it. I can't get flash to run external scripts, but I <em>can</em> get external scripts to run flash; so I have two scripts now; build.bat and build.jsfl</p> <p>build.bat:</p> <pre><code>subwcrev . Version.svn.as Version.as IF ERRORLEVEL 1 EXIT /B $ErrLev flash.exe ./build.jsfl IF ERRORLEVEL 1 EXIT /B $ErrLev </code></pre> <p>build.jsfl:</p> <pre><code>fl.openDocument("file:///movie.fla"); var documentDom = fl.getDocumentDOM(); documentDom.exportSWF("file:///movie.swf",true); documentDom.close(false); FLfile.remove("file:///Version.as"); </code></pre> <p>I've added build.bat to my project; if I double-click on build.bat, the project builds the SWF movie with the SVN version info. That works from within the Flash IDE or from the file explorer. If I forget, and click on 'test project', then the build fails because it can't find Version.as.</p> <p>Thanks again, Zárate!</p>
10,679
<p>I'm the developer of twittertrend.net, I was wondering if there was a faster way to get headers of a URL, besides doing curl_multi? I process over 250 URLs a minute, and I need a really fast way to do this from a PHP standpoint. Either a bash script could be used and then output the headers or C appliation, anything that could be faster? I have primarily only programmed in PHP, but I can learn. Currently, CURL_MULTI (with 6 URLs provided at once, does an ok job, but I would prefer something faster? Ultimately I would like to stick with PHP for any MySQL storing and processing.</p> <p>Thanks, James Hartig</p>
<p>I think you need a multi-process batch URL fetching daemon. PHP does not support multithreading, but there's nothing stopping you from spawning multiple PHP daemon processes.</p> <p>Having said that, PHP's lack of a proper garbage collector means that long-running processes can leak memory.</p> <p>Run a daemon which spawns lots of instances (a configurable, but controlled number) of the php program, which will of course have to be capable of reading a work queue, fetching the URLs and writing the results away in a manner which is multi-process safe; multiple procs shouldn't end up trying to do the same work.</p> <p>You'll want all of this to run autonomously as a daemon rather than from a web server. Really.</p>
<p>If you don't mind going into really low level stuff, you could send pipelined raw HTTP 1.1 requests using the socket functions.</p> <p>It'd help to know where the bottleneck is in what you're currently using - network, CPU, etc...</p>
47,134
<p>We're developing a product that relies on the Microsoft Sync Framework to keep the data on a client app and on the server in sync. What we have noticed is when syncing about 16 tables and ~2200 records it will take about 4 minutes, which is not acceptable.</p> <p>Using the SQL Server Profiler we found it is using sp_executesql to execute the queries. when run without sp_executesql a specific query runs in &lt;1s, but with it takes over 10s.</p> <p>So the question is: What are we doing wrong and is there anything we can do to speed it up.</p>
<p>sp_executesql is using dynamic sql. each row is being processed singularly.</p> <p>4 minutes seems rather long, you should look at the design of your 16 tables and check the performance on them. Try using the execution plan to view where the bottleneck may be occurring.</p> <p>check out this link that covers the basics:</p> <p><a href="http://www.simple-talk.com/sql/performance/execution-plan-basics/" rel="nofollow noreferrer">SQL Execution Plan basics</a></p> <p>Try scrolling down to the bottom of the article, where there are screen shots of the actual graphical interface in SQL Management Studio. There are some boring parts of the article, but you can atleast see the graphical execution plan and its benefits.</p>
<p>Performance improvements are listed on MSDN in the 'What's New' section for <a href="http://msdn.microsoft.com/en-us/library/bb902854(SQL.105).aspx" rel="nofollow noreferrer">Sync Framework 2.0</a>.</p> <blockquote> <p><strong>Performance Improvements</strong></p> <p>The new database providers in this release have been thoroughly tested in large scale out scenarios in which a single server supports thousands of clients with hundreds of concurrent synchronization operations. This testing resulted in a large number of internal performance improvements enable Sync Framework database providers to perform as well as other Microsoft technologies like Remote Data Access (RDA) while offering a wide range of capabilities that compete with end-to-end solutions like merge replication.</p> </blockquote>
36,092
<p>Are there any good tools to generate JavaScript? I remember in .NET, there was Script# - don't know its status today. </p> <p>Anyone have experience with any tools? </p>
<p>I use my keyboard, a text editor and my brain to generate JavaScript.</p> <p>:P</p>
<p>There is currently a lot of tools to generate JavaScript, like GWT.</p> <p>But giving you a good answer really depends on what is your originator language and what king of JavaScript functionnality you want to use.</p>
10,571
<p>I'm running an SQL query against a mainframe DB2 database using the OdbcDataReader class and ExecuteReader() method. This code is in production and has been running fine for months.</p> <p>The query normally takes 1-2 minutes to execute. This past Friday, the query encountered a ThreadAbortException. Below is the formatted stack trace. The ApplicationException in the trace is created in my catch block.</p> <p>In case it is important, the query is run when a client calls a web service method. The web service is hosted in a Windows Service. The web service is hosted in a Windows Service using the soap.tcp protocol.</p> <p>Any ideas why the TreadAbortException is happening?</p> <blockquote> <p>Stack trace for 2 exception(s). Root cause at the top.</p> <p>Exception 2: Thread was being aborted.<br> System.Threading.ThreadAbortException inside C:\WINDOWS\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll at System.Data.Common.UnsafeNativeMethods.SQLExecDirectW(OdbcStatementHandle StatementHandle, String StatementText, Int32 TextLength) at System.Data.Odbc.OdbcStatementHandle.ExecuteDirect(String commandText) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader) at System.Data.Odbc.OdbcCommand.ExecuteReader(CommandBehavior behavior) at MyCompany.MyDatabase.GetFolioList(String sqlWhereClause)</p> <p>Exception 1: Unable to retrieve the folio summary list where STAT_CD='V'.<br> System.ApplicationException inside D:\Production\DBGateway\bin\MyDatabase.dll at MyCompany.MyDatabase.GetFolioList(String sqlWhereClause) at MyCompany.MyDatabase.&lt;>c__DisplayClass18.b__17() at MyCompany.WebUtilities.WebServiceBase.WebMethodTemplate[T](String methodName, String exceptionFormat, WebMethodWorker<code>1 Worker, StringFormatter</code>1 FormatterMethod)</p> </blockquote>
<p>Here is the answer to my own question.</p> <p>When hosting a web service, there is some process monitoring how long a web service call is taking. If a call is taking too long, then it is killed and a ThreadAbortException will occur. The timeout can be increased.</p> <p>For a WSE3 web service running outside of ASP.NET, e.g. hosted as soap.tcp (like mine), the configuration property is executionTimeoutInSeconds:</p> <pre><code>&lt;configuration&gt; &lt;microsoft.web.services3&gt; &lt;messaging&gt; &lt;executionTimeoutInSeconds value="360" /&gt; &lt;/messaging&gt; &lt;/microsoft.web.services3&gt; &lt;/configuration&gt; </code></pre> <p>For a web service hosted in ASP.NET, the configuration property is executionTimeout:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;httpRuntime executionTimeout=”360” /&gt; &lt;/system.web&gt; &lt;/configuration </code></pre>
<p>It might be possible that your thread was chosen as the victim in a deadlock situation resulting from optimistic locking, though in that case I would have expected the responsible layer to handle it.</p> <p>ThreadAbortExceptions can be caused by many things, including other applications or the CLR host aborting the thread. Is your code being hosted by another application? (The seminal example would be Sql Server, though that doesn't appear to be the situation in your case.)</p>
37,953
<p>I want to start using dependency injection in my WPF application, largely for better unit testability. My app is mostly constructed along the M-V-VM pattern. I'm looking at <a href="https://code.google.com/p/autofac/" rel="nofollow noreferrer">Autofac</a> for my IoC container, but I don't think that matters too much for this discussion.</p> <p>Injecting a service into the start window seems straightforward, as I can create the container and resolve from it in App.xaml.cs.</p> <p>What I'm struggling with is how I can DI ViewModels and Services into User Controls? The user controls are instantiated via XAML markup, so there's no opportunity to <code>Resolve()</code> them.</p> <p>The best I can think of is to place the container in a Singleton, and have the user controls resolve their ViewModels from the global container. This feels like a half-way solution, at best, as it still required my components to have a dependency on a ServiceLocator.</p> <p>Is full IoC possible with WPF?</p> <p>[edit] - Prism has been suggested, but even evaluating Prism seems like a big investment. I'm hoping for something smaller.</p> <p>[edit] here's a code fragment where I'm stopped</p> <pre class="lang-cs prettyprint-override"><code>//setup IoC container (in app.xaml.cs) var builder = new ContainerBuilder(); builder.Register&lt;NewsSource&gt;().As&lt;INewsSource&gt;(); builder.Register&lt;AViewModel&gt;().FactoryScoped(); var container = builder.Build(); // in user control ctor - // this doesn't work, where do I get the container from VM = container.Resolve&lt;AViewModel&gt;(); // in app.xaml.cs // this compiles, but I can't use this uc, //as the one I want in created via xaml in the primary window SomeUserControl uc = new SomeUserControl(); uc.VM = container.Resolve&lt;AViewModel&gt;(); </code></pre>
<p>It's actually very easy to do. We have examples of this in Prism as jedidja mentioned. You can either have the ViewModel get injected with the View or the View get injected with the ViewModel. In the Prism StockTraderRI, you will see that we inject the View into the ViewModel. Essentially, what happens is that the View (and View interface) has a Model property. That property is implemented in the code-behind to set the DataContext to the value, for example: <code>this.DataContext = value;</code>. In the constructor of the ViewModel, the View gets injected. It then sets <code>View.Model = this;</code> which will pass itself as the DataContext.</p> <p>You can also easily do the reverse and have the ViewModel injected into the View. I actually prefer this because it means that the ViewModel no longer has any back reference to the view at all. This means when unit-testing the ViewModel, you don't have a view to even Mock. Additionally, it makes the code cleaner, in that in the constructor of the View, it simply sets the DataContext to the ViewModel that was injected.</p> <p>I talk a bit more about this in the video recording of the Separated Presentation Patterns talk that Jeremy Miller and I gave at Kaizenconf. The first part of which can be found here <a href="https://vimeo.com/2189854" rel="nofollow noreferrer">https://vimeo.com/2189854</a>.</p>
<p>I think You have to Decide on View First or Viewmodel First then as given the other answer it Can be decide.. There are several open source framework does it same . I use Caliburn where ViewModel first is taken and its really good approach</p>
36,164
<p>I'm trying to place 4 of my image containers into a new pane, having a total of 16 images. The jQuery below is what I came up with to do it. The first pane comes out correctly with 4 images in it. But the second has 4 images, plus the 3rd pane. And the 3rd pane has 4 images plus the 4th pane. I don't know exactly why the nesting is occurring. My wrapping can't be causing their index to change. I added css borders to them and it appears to be indexed correctly. How should I be going about this? What I want is to have 1-4 in one pane, 5-8 in another, 9-12, and 13-16. It needs to be dynamic so that I can change the number in each pane, so just doing it in the HTML isn't an option.</p> <p>A demo of the issue can be seen here: <a href="http://beta.whipplehill.com/mygal/rotate.html" rel="noreferrer">http://beta.whipplehill.com/mygal/rotate.html</a>. I'm using firebug to view the DOM.</p> <p>Any help would be splentabulous!</p> <p>The jQuery Code</p> <pre><code>$(function() { $(".digi_image:gt(-1):lt(4)").wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid red"); $(".digi_image:gt(3):lt(8)").wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid blue"); $(".digi_image:gt(7):lt(12)").wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid green"); $(".digi_image:gt(11):lt(16)").wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid orange"); $(".digi_pane").append("&lt;div style=\"clear: both;\"&gt;&lt;/div&gt;"); }); </code></pre> <p>The HTML (abbreviated), but essentially repeated 16 times.</p> <pre><code>&lt;div class="digi_image"&gt; &lt;div class="space_holder"&gt;&lt;img src="images/n883470064_4126667_9320.jpg" width="100" /&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
<p>I think your problem is your use of the gt() and lt() selectors. You should look up slice() instead. </p> <p>Check out this post: <a href="http://docs.jquery.com/Traversing/slice" rel="nofollow noreferrer">http://docs.jquery.com/Traversing/slice</a></p>
<p>For those who are curious... this is what I did.</p> <pre><code>$(".digi_image").slice(0, 4).wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid red"); $(".digi_image").slice(4, 8).wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid blue"); $(".digi_image").slice(8, 12).wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid green"); $(".digi_image").slice(12, 16).wrapAll("&lt;div class=\"digi_pane\"&gt;&lt;/div&gt;").css("border", "2px solid orange"); $(".digi_pane").append("&lt;div style=\"clear: both;\"&gt;&lt;/div&gt;"); </code></pre> <p>And it works precisely how I need it to. Could probably be made a bit more efficient, but it works.</p>
18,522
<p>I am trying to import an STL file, I created in FreeCAD. It has a hole in the hull of the object and behind that hole there are two pins inside the object (see attached FreeCAD screenshot).</p> <p>When I import the STL in Cura, there are no walls around the whole object where there is the hole in the hull (see attached Cura screenshots). However the wall and the hole are visible in light grey, Cura just doesn't print it.</p> <p>Update:</p> <p> I understand the problem. It's not a watertight solid. I found a way to import it somewhat fine using meshmixer to create a hollow with an offset which makes the outer Hull actually have a thickness to it. Now the problem is, that's not really what I want. The result in cura now can't be printed with infill since the actual inside of the model is only within the walls. Also cura sees both sides of the wall as outer Perimeter. I understand the problem but actually am looking for a way to just prevent printing part of the regular model's wall.. In other words: I would basically like to set the whall line count to zero in that particular area. I just tried to use the support blocker and "Modify settings for overlap" but that doesn't do anything.</p> <p>CURA:</p> <p><a href="https://i.stack.imgur.com/hrCAY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hrCAY.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/7ETuW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7ETuW.png" alt="enter image description here"></a></p> <p>FreeCAD: <a href="https://i.stack.imgur.com/Lddxh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lddxh.png" alt="enter image description here"></a></p>
<p>This is clearly overextrusion relative to the volume the material is being deposited into, but that doesn't necessarily mean your extrusion rate is wrong. It could be:</p> <ul> <li>Nozzle smashed down into the bed (bed way too high) but somehow still extruding</li> <li>Problem in Z axis movement preventing the head from moving up the right amount for each layer (possibly not moving up at all?)</li> <li>Extrusion (flow) increased significantly above 100% in slicer</li> <li>Wrong extruder steps/mm setting (usually controlled on printer not slicer, though you can send a setting in the start gcode)</li> <li>Misconfigued filament diameter (unlikely since there's no common setting smaller than 1.75 mm; larger setting would under-extrude)</li> </ul>
<p>Bad filament is my answer. I bought PRLine and both print terrible like your picture. Suspect 2 factors, one is that the line is less than 1.75, so they underextrude and so you see those lines and in some cases gaps, second is the material itself is slippery suggesting to me that it has florinated additives.</p>
1,622
<p>According to the adobe flex docs: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html</a></p> <p>Using an image multiple times</p> <p>You can use the same image multiple times in your application by using the normal image import syntax each time. Flex only loads the image once, and then references the loaded image as many times as necessary.</p> <p>However, in testing we have found that if you request the same image (same url, etc.) in IE flash 9/10 a new http request will not be issued, but with Firefox, Safari (PC and MAC) a new request is always issued.</p> <p>I want to prevent the image from being pulled from the server each time I try and use it anyone have any idea why this is working only in IE?</p>
<p>The best way to load an image a single time and then reuse that image multiple times in a flex application is to embed the image and tie it to a class representation, then just reference that class from then on.</p> <p>Example:</p> <pre><code>[Embed(source="myImage.jpg")] [Bindable] public var myImageClass:Class; </code></pre> <p>HTH</p>
<p>The problem is the Expiration Time of your images. Configure in the application server the policy for images expiration time and the cache runs OK in all browsers.</p>
38,931
<p>We have been reading and writing Sticky Notes/Annotations/Comments to pdfs via an activex control in our application for a number of years. We have recently upgraded to Delphi2009 with Unicode Support. The following is causing problems.</p> <p>When we call </p> <p>CAcroPDAnnot.GetContents </p> <p>The results seem to be rather strange and we lose our Unicode Chars. It is not like saving as an ansi string which would usually result in returning ????? instead we get a string such as </p> <p>‚És‚­“ú‚É•—Ž×‚ð‚Ђ¢‚½‚ç</p> <p>For a string of Japanese characters.</p> <p>However if I save the comments in the pdf to a datafile via the menu in the pdf itself it is written to file as something like </p> <p>0kˆL0Oeå0k˜¨ª0’0r0D0_0‰</p> <p>The latter can be export and reimported into an acrobat pdf and will recreate the correct unicode characters. However once I call CAcroPDAnnot.GetContents in my code it is coming back as something else.</p> <ol> <li>Is CAcroPDAnnot.GetContents broken?</li> <li>Is there an encoding scheme I should be aware of?</li> <li>Is there an alternative I might be able to do?</li> </ol> <p>Thanks</p>
<blockquote> <p>‚És‚­“ú‚É•—Ž×‚ð‚Ђ¢‚½‚ç</p> </blockquote> <p>That's the string:</p> <p>に行く日に風邪をひいたら</p> <p>in CP-932 aka Shift-JIS encoding, an awful but lamentably still-popular encoding in Japan.</p> <p>You're currently interpreting it in as CP-1252 (Windows Western European). If your PDF-reading component won't convert it for you automatically, you'll need to find a way to detect what encoding the document is in and convert it manually.</p> <p>I don't know what Delphi provides for reading encodings, but have you got the encodings for Shift-JIS installed in Windows, from the Control Panel -> Regional Options -> "Install files for East Asian languages" option? If not, that might explain why it'd be failing to convert automatically, perhaps.</p>
<p>Ok, one of the main differences between Delphi 2009 and the earlier versions is that the default string type is an unicode string. That means that if you use the same ActiveX component as in previous versions, you are passing unicode strings to ascii strings and that is usually not a good idea.</p> <p>There are a couple of solutions for this problem:</p> <ul> <li>Try if you can upgrade your activeX component so that it supports full unicode strings.</li> <li>Use AnsiString and not string to communicate with the activeX component. In this case, you can still use the old interface, but you are still bound to the same limitations.</li> <li>Use an other control that creates pdf. There is a lot to find, but be prepared to change a big chunk of your software. (Some controls are XML based and use encoding. )</li> </ul>
49,113
<p>My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.</p> <p>My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.</p> <p>Any ideas?</p>
<p>Taken from the <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init" rel="noreferrer">Spring Reference Manual</a>:</p> <blockquote> <p>The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).</p> <p>However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.</p> <p>When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:</p> </blockquote> <pre><code>&lt;bean id=&quot;lazy&quot; class=&quot;com.foo.ExpensiveToCreateBean&quot; lazy-init=&quot;true&quot;/&gt; </code></pre> <p>But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles.</p>
<p>Depends upon the objects.</p> <p>But, unused code is 'cruft' and will increase the cost of maintenance.</p> <p>Better to delete the refs and classes. You can always restore from version control if they are needed later.</p>
12,376
<p>I am trying to use regular expressions to find a UK postcode within a string.</p> <p>I have got the regular expression working inside RegexBuddy, see below:</p> <pre><code>\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b </code></pre> <p>I have a bunch of addresses and want to grab the postcode from them, example below:</p> <blockquote> <p>123 Some Road Name<br /> Town, City<br /> County<br /> PA23 6NH</p> </blockquote> <p>How would I go about this in Python? I am aware of the <code>re</code> module for Python but I am struggling to get it working.</p> <p>Cheers</p> <p>Eef</p>
<p>repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is..</p> <pre><code>import re s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\ "County\nPA2 6NH\n123 Some Road Name\nTown, City\nCounty\nPA2Q 6NH" #custom print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s) #regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s) </code></pre> <p>the result is </p> <pre><code>['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] ['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] </code></pre> <p>both the regex's give the same result.</p>
<p>Try</p> <pre><code>import re re.findall("[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}", x) </code></pre> <p>You don't need the \b. </p>
49,529
<p>I have an ASPX page where I am uploading an image to server for on a serverside button click event. In my page, it will show the available image if it exists. When I upload an image, it will replace the old one with the new one. Now after uploading also the same image is getting displayed. How can tackle this? I used window.location.reload() javascript function to refresh, but then it is not working. It is posting the page again.</p> <p>This is my code</p> <pre><code> Do UploadImage(studentId,mode); // Function to upload image StringBuilder sbc = new StringBuilder(); sbc.Append("&lt;script language='javascript'&gt;"); sbc.Append("alert('Upload process completed successfully!');"); sbc.Append("window.location.reload()"); sbc.Append("&lt;/script&gt;"); HttpContext.Current.Response.Write(sbc); </code></pre>
<p>It's being cached in the browser. To overcome this - alter the url of the image. This can be done by including a timestamp, version number, or guid in the image file name.</p>
<p>You can reload from the server side</p> <pre><code>Response.Redirect(Request.URL) </code></pre>
42,571
<p>Using web forms I know that you can only have one ASP.NET form on a page. I've done some implementations where I've used Javascript to add other forms to a page to support things like logon controls (that post back to Logon.aspx instead of the current page). I'm wondering if the single form per page is still present in ASP.NET MVC or if this restriction has been lifted.</p>
<p>You'll probably want to use regular HTML forms in your MVC code with the action attribute pointing to the appropriate controller action. So you can have as many forms on the page as you want.</p>
<p>You can have as many Html forms as you see <strong>responsible</strong> to use.</p>
23,741
<p>I'm writing out XML files using the MSXML parser, with a wrapper I downloaded from here: <a href="http://www.codeproject.com/KB/XML/JW_CXml.aspx" rel="noreferrer">http://www.codeproject.com/KB/XML/JW_CXml.aspx</a>. Works great except that when I create a new document from code (so not load from file and modify), the result is all in one big line. I'd like elements to be indented nicely so that I can read it easily in a text editor.</p> <p>Googling shows many people with the same question - asked around 2001 or so. Replies usually say 'apply an XSL transformation' or 'add your own whitespace nodes'. Especially the last one makes me go %( so I'm hoping that in 2008 there's an easier way to pretty MSXML output. So my question; is there, and how do I use it?</p>
<p>Try this, I found this years ago on the web.</p> <pre><code>#include &lt;msxml2.h&gt; bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream) { // Create the writer CComPtr &lt;IMXWriter&gt; pMXWriter; if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) { return false; } CComPtr &lt;ISAXContentHandler&gt; pISAXContentHandler; if (FAILED (pMXWriter.QueryInterface(&amp;pISAXContentHandler))) { return false; } CComPtr &lt;ISAXErrorHandler&gt; pISAXErrorHandler; if (FAILED (pMXWriter.QueryInterface (&amp;pISAXErrorHandler))) { return false; } CComPtr &lt;ISAXDTDHandler&gt; pISAXDTDHandler; if (FAILED (pMXWriter.QueryInterface (&amp;pISAXDTDHandler))) { return false; } if (FAILED (pMXWriter -&gt;put_omitXMLDeclaration (VARIANT_FALSE)) || FAILED (pMXWriter -&gt;put_standalone (VARIANT_TRUE)) || FAILED (pMXWriter -&gt;put_indent (VARIANT_TRUE)) || FAILED (pMXWriter -&gt;put_encoding (L"UTF-8"))) { return false; } // Create the SAX reader CComPtr &lt;ISAXXMLReader&gt; pSAXReader; if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) { return false; } if (FAILED (pSAXReader -&gt;putContentHandler (pISAXContentHandler)) || FAILED (pSAXReader -&gt;putDTDHandler (pISAXDTDHandler)) || FAILED (pSAXReader -&gt;putErrorHandler (pISAXErrorHandler)) || FAILED (pSAXReader -&gt;putProperty ( L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) || FAILED (pSAXReader -&gt;putProperty ( L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)))) { return false; } // Perform the write return SUCCEEDED (pMXWriter -&gt;put_output (CComVariant (pStream))) &amp;&amp; SUCCEEDED (pSAXReader -&gt;parse (CComVariant (pDoc))); } </code></pre>
<p>Unless the library has a format option then the only other way is to use XSLT, or an external pretty printer ( I think htmltidy can also do xml) There doen't seem to be an option in the codeproject lib but you can specify an XSLT stylesheet to MSXML.</p>
19,893
<p>I've read (and re-read) Martin Fowler's <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Mocks Aren't Stubs</a>. In it, he defines <a href="http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting" rel="noreferrer">two different approaches to TDD: "Classical" and "Mockist"</a>. He attempts to answer the question "<a href="http://martinfowler.com/articles/mocksArentStubs.html#SoShouldIBeAClassicistOrAMockist" rel="noreferrer">So should I be a classicist or a mockist?</a>", but he admits that he has never tried mockist TDD on "anything more than toys." So I thought I'd ask the question here. Good answers may repeat Fowler's arguments (but hopefully more clearly) or add arguments that he didn't think of or that others have come up with since Fowler last updated the essay back in January 2007.</p>
<p>I don't think you need to choose one over the other. Both have their advantages and disadvantages and both are tools for your toolbox. "Mockist" tdd makes you a bit more flexible in what you can test while classical TDD makes your tests a bit less brittle because they tend to look more at the input/vs output instead of looking at the actual implementation. When doing mockist unit testing I seem to have more tests break when changing the implementation.</p> <p>I try to use classical tdd whenever possible (although i often use a mocking framework to set up the stubs quickly). Sometimes I notice I start testing too much at one time or i need too many objects to set up a test. That's when mockist testing can often help you set up smaller tests.</p> <p>This is all quite abstract so I hope i make sense</p>
<p>I am still relatively new at TDD - but the way I was taught/introduced to the differences was to think of it in terms of testing the integration between classes and so that you are not dependent on live data. For instance if I have a class that is pretty much stand-alone - not dependent on other classes I have built for a project and it doesn't go out to a live data/dev environment for input (like a DB or an API to a system) then I would only use classical unit tests in something like NUnit or JUnit - but when I start to test interaction between built classes - that's when it can get real handy to mock other custom classes and/or outside interaction - so that you can single out and test your current classes' code without trying to chase down a a potential bug in other classes you are calling.</p>
22,330
<p>I am using boost::signal in a native C++ class, and I now I am writing a .NET wrapper in C++/CLI, so that I can expose the native C++ callbacks as .NET events. When I try to use boost::bind to take the address of a member function of my managed class, I get compiler error 3374, saying I cannot take the address of a member function unless I am creating a delegate instance. Does anyone know how to bind a member function of a managed class using boost::bind?</p> <p>For clarification, the following sample code causes Compiler Error 3374:</p> <pre><code>#include &lt;boost/bind.hpp&gt; public ref class Managed { public: Managed() { boost::bind(&amp;Managed::OnSomeEvent, this); } void OnSomeEvent(void) { } }; </code></pre>
<p>While your answer works, it exposes some of your implementation to the world (Managed::OnSomeEvent). If you don't want people to be able to raise the OnChange event willy-nilly by invoking OnSomeEvent(), you can update your Managed class as follows (based on <a href="http://msdn.microsoft.com/en-us/library/367eeye0(VS.80).aspx" rel="noreferrer">this advice</a>):</p> <pre><code>public delegate void ChangeHandler(void); typedef void (__stdcall *ChangeCallback)(void); public ref class Managed { public: Managed(Native* Nat); ~Managed(); event ChangeHandler^ OnChange; private: void OnSomeEvent(void); Native* native; Callback* callback; GCHandle gch; }; Managed::Managed(Native* Nat) : native(Nat) { callback = new Callback; ChangeHandler^ handler = gcnew ChangeHandler( this, &amp;Managed::OnSomeEvent ); gch = GCHandle::Alloc( handler ); System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler ); ChangeCallback cbFunc = static_cast&lt;ChangeCallback&gt;( ip.ToPointer() ); *callback = native-&gt;RegisterCallback(boost::bind&lt;void&gt;( cbFunc ) ); } Managed::~Managed() { native-&gt;UnregisterCallback(*callback); delete callback; if ( gch.IsAllocated ) { gch.Free(); } } void Managed::OnSomeEvent(void) { OnChange(); } </code></pre> <p>Note the alternate <code>bind&lt;R&gt;()</code> form that's used.</p>
<p>After googling some more, I finally found a <a href="http://mr-sharpoblunto.junkship.org/2007/11/mapping-boostsignals-to-net-events.html" rel="nofollow noreferrer">nice blog post</a> about how to do this. The code in that post was a little more than I needed, but the main nugget was to use a global free function that takes an argument of the managed this pointer wrapped in a gcroot&lt;> template. See the <strong>SomeEventProxy(...)</strong> in the code below for an example. This function then turns around and calls the managed member I was trying to bind. My solution appears below for future reference.</p> <pre><code>#include &lt;msclr/marshal.h&gt; #include &lt;boost/bind.hpp&gt; #include &lt;boost/signal.hpp&gt; #include &lt;iostream&gt; #using &lt;mscorlib.dll&gt; using namespace System; using namespace msclr::interop; typedef boost::signal&lt;void (void)&gt; ChangedSignal; typedef boost::signal&lt;void (void)&gt;::slot_function_type ChangedSignalCB; typedef boost::signals::connection Callback; class Native { public: void ChangeIt() { changed(); } Callback RegisterCallback(ChangedSignalCB Subscriber) { return changed.connect(Subscriber); } void UnregisterCallback(Callback CB) { changed.disconnect(CB); } private: ChangedSignal changed; }; delegate void ChangeHandler(void); public ref class Managed { public: Managed(Native* Nat); ~Managed(); void OnSomeEvent(void); event ChangeHandler^ OnChange; private: Native* native; Callback* callback; }; void SomeEventProxy(gcroot&lt;Managed^&gt; This) { This-&gt;OnSomeEvent(); } Managed::Managed(Native* Nat) : native(Nat) { native = Nat; callback = new Callback; *callback = native-&gt;RegisterCallback(boost::bind( SomeEventProxy, gcroot&lt;Managed^&gt;(this) ) ); } Managed::~Managed() { native-&gt;UnregisterCallback(*callback); delete callback; } void Managed::OnSomeEvent(void) { OnChange(); } void OnChanged(void) { Console::WriteLine("Got it!"); } int main(array&lt;System::String ^&gt; ^args) { Native* native = new Native; Managed^ managed = gcnew Managed(native); managed-&gt;OnChange += gcnew ChangeHandler(OnChanged); native-&gt;ChangeIt(); delete native; return 0; } </code></pre>
19,797
<p>I would like to Debug .NET Mobile Device Application using multiple instances of Device Emulator. If I right click the project and go to Debug -> Start new instance in Visual Studio 2008 when an instance is already running I get the error</p> <blockquote> <p>Unable to copy file "obj\Debug\MyMobileApp.exe" to "bin\Debug\MyMobileApp.exe". The process cannot access the file 'bin\Debug\MyMobileApp.exe' because it is being used by another process.</p> </blockquote> <p>Does anyone know if and how I can do this?</p>
<p>I just discovered a way you can (sort of) do this. You can't deploy from two instances of Visual Studio to two instances of the same type of emulator, but you <em>can</em> deploy to instances of two <em>different</em> types of emulator. Although not without a small trick.</p> <p>To see how this works, open two instances of Visual Studio, and open the same CF project in each. Next, you need to manually start two emulators. Find the file <strong>dvcemumanager.exe</strong> (it should be in <strong>C:\Program Files\Microsoft Device Emulator\1.0</strong>) and run it. To start an emulator, select it and then click Actions | Connect. For this example, start the regular emulator and the VGA emulator (and wait for them to fully come up, of course).</p> <p>Back in Visual Studio, set one instance's deployment target to the regular emulator, and the other instance's target to the VGA emulator, and start each. Each app will be deployed to the appropriate already-running instance of the emulator.</p> <p>You can't use this technique to run two versions of the same type of emulator, because there doesn't seem to be any way of doing that from the device manager interface. Also, you can't just start two instances of VS and set them to different emulators - I tried that and it doesn't work. For some reason the second one tries to deploy to the same emulator as the first, and you get the error you saw.</p>
<p>disconnect device, go to explore and delete all files and folder than was created. Be sure the aplication isnt runing, (taskadmin). Conect again, rebuild, deploy, then f5.</p> <p>Good Luck</p>
43,806
<p>Does IIS create the session id when a request is received and where is that saved (client or server)?</p> <p>How does server recognize that the request is coming from the same user/session?</p>
<p>The answer to your first question is Yes -- if sessions are used, and Both.</p> <p>A cookie is a short bit of text passed back and forth between client and server with every request/response.</p> <p>IIS generates a session id, saves it, and any associated data, and passes the in a cookie to the client (browser).</p> <p>When the client makes another request, it sends the cookie, containing the sessionID back to the server. The server can then look at the cookie and find the session (and the associated data) which is saved on the server.</p>
<p>In ASP.net, there are multiple places for the session to be saved, but it's always within the server infrastructure.</p> <p>The default is the memory of the IIS Process. This means: if you reset IIS (or the whole PC) or even just the application pool within IIS, all sessions are deleted, and the session data is lost forever. Also, if you have a LOT of sessions and store a lot of data in each session, the process will require a lot of memory, which can be a problem. This is called "In-Proc" Sessions.</p> <p>The main alternative is a SQL Server Database. That way, sessions are kept even after a restart and it does not really matter how large each session is. The main downside is the added latency: Fetching data from a database is slower that the In-Proc solution of course.</p> <p>There are also some other methods how to store sessions (including the option to write a completely new session provider), but the two common ones are "The Memory of the Server" and "A MS SQL Database".</p>
47,510
<p>What to do automatic nightly build of .NET web application and upload to the test server. </p> <p>Or, if this tool is overkill, please suggest something else.</p>
<p>I have found this great tutorial: <a href="http://weblogs.asp.net/jdanforth/pages/How-to-Hook-Up-a-VS.NET-2005-Solution-With-CruiseControl.NET-in-a-Few-Minutes.aspx" rel="noreferrer">How to Hook Up a VS.NET 2005 Solution With CruiseControl.NET in a Few Minutes</a>. It's short but uses a real .Net project to illustrate the set up.</p> <p>After that refine your configuration by reading each relevant section of <a href="http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server" rel="noreferrer">CruiseControl.NET : Configuring the Server</a></p> <p>And for a really nice and recent tutorial check <a href="http://www.dougrohm.com/blog/post/2006/01/29/Integrating-MSBuild-with-CruiseControlNET.aspx" rel="noreferrer">Integrating MSBuild with CruiseControl.NET</a>. Very good one!</p>
<p>I used the instructions and example on the CruiseControl.Net website</p> <p><a href="http://confluence.public.thoughtworks.org/display/CCNET/Setting+up+from+scratch++Part+01" rel="nofollow noreferrer">Setting up from scratch Part 01</a>.</p>
34,008
<p>I have a domain that will be accessed by a small, private group of people. So I want to control access via authentication.</p> <p>The domain has a collection of applications installed that each have their own sub-domain. Eg: domain.com, app1.domain.com, app2.domain.com, app3.domain.com</p> <p>I'd love to have a single sign-on solution so they don't have to authenticate themselves for each application. Also, the applications are written in different languages (PHP, Python and Perl) so authenticating users through an Apache module is ideal.</p> <p>I am new to digest authentication, but it seems like a good solution. I have used <code>htdigest</code> to create my users. I have configured my domain and sub-domains (See below).</p> <p>If I go to the domain or any of the sub-domains it will prompt for a username and password. If I enter a correct username and password, it will authenticate me and the page will load. However, if I go to another sub-domain, it will ask for me to enter a username and password again. If I enter the same username and password, it will work.</p> <p>So the password file is OK, and authentication is OK, but the problem seems to lie in the configuration of the <code>AuthDigestDomain</code>.</p> <p>I have searched all over the net to find an example of using Digest authentication on multiple domains, but I cannot find a specific example that solves my problem.</p> <p>I am hoping someone here can assist. Do I put the same authentication information in every <code>Directory</code>? Should I be using <code>Directory</code> or <code>Location</code> or <code>Files</code>? Have I missed something all-together?</p> <p>Thanks in advance!</p> <p>Below is an example of my Apache config for domain.com:</p> <pre><code>&lt;Directory /var/www&gt; AuthType Digest AuthName "realm" AuthDigestAlgorithm MD5 AuthDigestDomain / http://domain.com/ http://app1.domain.com/ http://app2.domain.com/ http://app3.domain.com/ AuthDigestNcCheck Off AuthDigestNonceLifetime 0 AuthDigestQop auth AuthDigestProvider file AuthUserFile /etc/apache2/.htpasswd-digest AuthGroupFile /dev/null Require valid-user &lt;/Directory&gt; </code></pre> <p>And here is an example of app1.domain.com:</p> <pre><code>&lt;Directory /var/lib/app1&gt; AuthType Digest AuthName "realm" AuthDigestAlgorithm MD5 AuthDigestDomain / http://domain.com/ http://app1.domain.com/ http://app2.domain.com/ http://app3.domain.com/ AuthDigestNcCheck Off AuthDigestNonceLifetime 0 AuthDigestQop auth AuthDigestProvider file AuthUserFile /etc/apache2/.htpasswd-digest AuthGroupFile /dev/null Require valid-user &lt;/Directory&gt; </code></pre> <p>To baffle things even further, this works when using IE6, but not Firefox or Chrome. Is it the clients not sending the authentication properly, or is is the server not sending the correct credentials?</p> <p>I have also been reading up on <a href="http://www.faqs.org/rfcs/rfc2617.html" rel="noreferrer">RFC 2617</a> and written the authentication headers using PHP to ensure that the request/response challenge is correct. This hasn't helped at all!</p>
<p>Most browsers do not respect the Digest "domain" directive and will not resend credentials for other URIs. As far as I know, Opera is the only browser that honors it.</p> <p>For Opera, the server(s) must respond with the same "realm" string for each URI in the domain list. In other words, if domain="/test /example", the server needs to send "Test Realm - example.com" in the WWW-Authenticate header for both of those URIs. I assume Opera does this because it stores H(A1) instead of the actual password for security. Read into RFC2617 for more on this.</p> <p>Here's my cross-browser solution to this problem: <a href="http://travisce.com/arest/" rel="noreferrer">http://travisce.com/arest/</a></p>
<p>I have no experience with something like this myself. But I just took a look at the <a href="http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html" rel="nofollow noreferrer">Apache documentation</a> and found this:</p> <blockquote> <p>The AuthDigestNonceLifetime directive controls how long the server nonce is valid. [...] If seconds is less than 0 then the nonce never expires.</p> </blockquote> <p>So it seems to me that 0 seconds (the value you are using) is either illegal or really tells Apache to expire the nonce after 0 seconds which would exactly explain the behavior you are geting. </p>
46,676
<p>We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.</p> <p>Currently we use the commands in the test:</p> <pre><code>// force new window to open at this point - so we can select it later selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')"); selenium().click("//input[@value='Submit']"); selenium().waitForPopUp("enquiryPopup", getWaitTime()); selenium().selectWindow("enquiryPopup"); </code></pre> <p>...which works <em>most of the time</em>. Occasionally the test will fail on the <code>waitForPopUp()</code> line with </p> <pre><code>com.thoughtworks.selenium.SeleniumException: Permission denied </code></pre> <p>Can anyone suggest a better, more <em>reliable</em> method?</p> <p>Also, we primarily run these tests on IE6 and 7.</p>
<p>It works!! Just to make it easier for the folks who prefer selenese.</p> <p>This worked for me using IE7(normal mode). </p> <p>What a freaking hassle. Thank the spaghetti monster in the sky for SO or there is no way I would have got this working in IE.</p> <pre><code>&lt;tr&gt; &lt;td&gt;getEval&lt;/td&gt; &lt;td&gt;selenium.browserbot.getCurrentWindow().open('', 'windowName');&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;click&lt;/td&gt; &lt;td&gt;buttonName&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;windowFocus&lt;/td&gt; &lt;td&gt;windowName&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;waitForPopUp&lt;/td&gt; &lt;td&gt;windowName&lt;/td&gt; &lt;td&gt;3000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;selectWindow&lt;/td&gt; &lt;td&gt;windowName&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre>
<p>Try adding some wait statements around the calls that are causing you issues.</p> <p>I've had the same errors before and the only way I was able to <i>reliably</i> resolve them was by making calls to System.Threading.Thread.Sleep(5000)..</p>
12,431
<p>I have huge number of Word files I need to merge (join) into one file, and will be time consuming to use the Word merger (one by one). Have you experienced any tool that can handle this job?</p>
<pre class="lang-vb prettyprint-override"><code>Sub MergeAllDocuments(AllDocumentsPath as String, MasterDocumentPath as String) Dim MasterDocument As Document Set MasterDocument = Documents.Open(FileName:=MasterDocumentPath) TheDocumentPath = Dir(AllDocumentsPath , vbNormal) While TheDocumentPath &lt;&gt; "" ' Append the next doc to the end of the master doc. (The ' special "\EndOfDoc" bookmark is always available!) MasterDocument.Bookmarks("\EndOfDoc").Range.InsertFile TheDocumentPath TheDocumentPath = Dir Wend MasterDocument.Save End Sub MergeAllDocuments "C:\MySeparateDocuments\*.doc", "C:\MasterDocument.doc" </code></pre> <p>I have one question - why do you want do do such a thing (with a "huge number" of documents, at least)?</p>
<p>Have you tried using the Word COM api? You can automate lots of things - maybe you can automate a merge.</p> <p>Do you really need to do an actual merge, or do you want to join the files together. The two things are quite different.</p> <p>Merging is used when you have two versions of an original file with (potentially conflicting) changes. I can't really see how you would have a "huge number" of files that you needed to merge all together. This would be an absolute nightmare of conflicts. Do you mean to merge sets of them into individual files?</p> <p>Joining would be when you want to concatenate them one after the other. This would be a lot easier to do. This is quite possible using the COM api.</p>
35,007
<p>We run an old Windows NT Machine, fully patched running IIS4.0.</p> <p>Today we were hit by "linuXploit_crew", and they took down our websites for a minute or two. (luckily we were quick to notice a change on the websites and fix it within minutes of the attack).</p> <p>However -- After fixing the website, I'm left with trying to figure out <strong><em>HOW</em></strong> this happened.</p> <p>Looking in our FTP Logs, there's no changes in our default.asp files, and I see nothing out of the ordinary for Web Logs. Any ideas on how to pinpoint how they got in? We've only got 3 ports open, FTP, HTTP, and HTTPS (21,80,443) on a Cisco Firewall. </p>
<p>NT/IIS4 no longer get security updates. Any <em>new</em> exploits will remain <strong>unpatched</strong>. Time to upgrade.</p> <p>Once you've been "owned" enough to change your site, you can't necessarily trust your logs anymore- they could have been "cleaned" by the attacker.</p>
<p>IIS 7 + .NET 3.5 SP1 should be a nice upgrade :)</p>
19,313
<p>With reference to <a href="https://stackoverflow.com/questions/280597/problem-with-date-daymonth-reversing-on-save">Problem with date day/month reversing on save</a></p> <p>I have further noted that even setting the Session.LCID on the page itself is making no difference what so ever.</p> <p>How could the environments be such that between test and live the asp site on live is reversing dates entered via SQL but not on test.</p> <p>Both have the IUSR set to UK, both have all users set to UK, both have the SQL Account set to US English and both have Session.LCID set to 3081 (Australian English)</p> <p>Why is test running " insert into datecolumn values '01/03/2008' and inserting '01/03/2008' and live is inserting '03/01/2008' "</p> <p>The setups look totally identical. This must be figured out soon i'm getting quite scared that we'll never know. The problem is we may not change code or anything else. All I can do is investigate and tell them the cause. But I can't find it!</p> <p>It's VB6/ASP and it's driving me do lally.</p> <p>Access to the database is via a System DSN configured to use the correct SQL account.</p> <p>What other info might you need.</p>
<p>In SQL Server Management Studio, in Security - Logins, right-click the user you're connecting as and click 'Properties'. The bottom combo box is marked 'Default language', change this to "British English" (<em>not</em> just "English").</p> <p><code>sp_configure 'default language'</code> sets the default language <em>for newly created logins</em>, and it is this that is stored in <code>sysconfigures</code>.</p> <p>I'm assuming here that the language isn't being set in the query string?</p>
<p>I encourage you to modify the code that interacts with the database. There are 2 unambiguous date formats that you can use with SQL Server.</p> <p>You can use yyyy-mm-ddThh:mi:ss.mmm or YYYYMMDD hh:mi:ss.mmm</p> <p>SQL Server will never mis-interpret dates if you use one of the 2 formats listed above.</p> <p>In vb, you can use the following format function to format the date in to an un-ambiguous date format that SQL Server will never mis-interpret.</p> <pre><code>Format(YourDateVariable, "yyyymmdd hh:nn:ss") </code></pre>
35,994
<p>I am trying to visualize some values on a form. They range from 0 to 200 and I would like the ones around 0 be green and turn bright red as they go to 200. </p> <p>Basically the function should return color based on the value inputted. Any ideas ?</p>
<p>Basically, the general method for smooth transition between two values is the following function:</p> <pre><code>function transition(value, maximum, start_point, end_point): return start_point + (end_point - start_point)*value/maximum </code></pre> <p>That given, you define a function that does the transition for triplets (RGB, HSV etc).</p> <pre><code>function transition3(value, maximum, (s1, s2, s3), (e1, e2, e3)): r1= transition(value, maximum, s1, e1) r2= transition(value, maximum, s2, e2) r3= transition(value, maximum, s3, e3) return (r1, r2, r3) </code></pre> <p>Assuming you have RGB colours for the <i>s</i> and <i>e</i> triplets, you can use the transition3 function as-is. However, going through the HSV colour space produces more "natural" transitions. So, given the conversion functions (stolen shamelessly from the Python colorsys module and converted to pseudocode :):</p> <pre><code>function rgb_to_hsv(r, g, b): maxc= max(r, g, b) minc= min(r, g, b) v= maxc if minc == maxc then return (0, 0, v) diff= maxc - minc s= diff / maxc rc= (maxc - r) / diff gc= (maxc - g) / diff bc= (maxc - b) / diff if r == maxc then h= bc - gc else if g == maxc then h= 2.0 + rc - bc else h = 4.0 + gc - rc h = (h / 6.0) % 1.0 //comment: this calculates only the fractional part of h/6 return (h, s, v) function hsv_to_rgb(h, s, v): if s == 0.0 then return (v, v, v) i= int(floor(h*6.0)) //comment: floor() should drop the fractional part f= (h*6.0) - i p= v*(1.0 - s) q= v*(1.0 - s*f) t= v*(1.0 - s*(1.0 - f)) if i mod 6 == 0 then return v, t, p if i == 1 then return q, v, p if i == 2 then return p, v, t if i == 3 then return p, q, v if i == 4 then return t, p, v if i == 5 then return v, p, q //comment: 0 &lt;= i &lt;= 6, so we never come here </code></pre> <p>, you can have code as following:</p> <pre><code>start_triplet= rgb_to_hsv(0, 255, 0) //comment: green converted to HSV end_triplet= rgb_to_hsv(255, 0, 0) //comment: accordingly for red maximum= 200 … //comment: value is defined somewhere here rgb_triplet_to_display= hsv_to_rgb(transition3(value, maximum, start_triplet, end_triplet)) </code></pre>
<p>Looking through <a href="http://en.wikipedia.org/wiki/Color_space" rel="nofollow noreferrer">this wikipedia article</a> I personally would pick a path through a color space, and map the values onto that path. </p> <p>But that's a straight function. I think you might be better suited to a javascript color chooser you can find with a quick color that will give you the Hex, and you can store the Hex.</p>
20,381
<p>In ASPNET, I grew to love the Application and Cache stores. They're awesome. For the uninitiated, you can just throw your data-logic objects into them, and hey-presto, you only need query the database once for a bit of data. </p> <p>By far one of the best ASPNET features, IMO.</p> <p>I've since ditched Windows for Linux, and therefore PHP, Python and Ruby for webdev. I use PHP most because I dev several open source projects, all using PHP.</p> <p>Needless to say, I've explored what PHP has to offer in terms of caching data-objects. So far I've played with:</p> <ol> <li>Serializing to file (a pretty slow/expensive process)</li> <li>Writing the data to file as JSON/XML/plaintext/etc (even slower for read ops)</li> <li>Writing the data to file as pure PHP (the fastest read, but quite a convoluted write op)</li> </ol> <p>I should stress now that I'm looking for a solution that doesn't rely on a third party app (eg memcached) as the apps are installed in all sorts of scenarios, most of which don't have install rights (eg: a cheap shared hosting account).</p> <p>So back to what I'm doing now, <strong>is persisting to file secure?</strong> <code>Rule 1</code> in production server security has always been disable file-writing, but I really don't see any way PHP <em>could</em> cache if it couldn't write. Are there any tips and/or tricks to boost the security?</p> <p><strong>Is there another persist-to-file method that I'm forgetting?</strong></p> <p><strong>Are there any better methods of caching in "limited" environments?</strong></p>
<p>Serializing is quite safe and commonly used. There is an alternative however, and that is to cache to memory. Check out <a href="http://pecl.php.net/package/memcache" rel="noreferrer">memcached</a> and <a href="http://www.php.net/manual/en/book.apc.php" rel="noreferrer">APC</a>, they're both free and highly performant. <a href="http://blog.digitalstruct.com/2008/02/27/php-performance-series-caching-techniques/" rel="noreferrer">This article</a> on different caching techniques in PHP might also be of interest.</p>
<p>It's in theory possible to store objects in sessions. That might get you past the file writing disabled problem. Additionally you could store the session in a mysql memory backed table to speed up the query.</p>
15,443
<p>I know a lot about C# but this one is stumping me and Google isn't helping.</p> <p>I have an IEnumerable range of objects. I want to set a property on the first one. I do so, but when I enumerate over the range of objects after the modification, I don't see my change.</p> <p>Here's a good example of the problem:</p> <pre><code> public static void GenericCollectionModifier() { // 1, 2, 3, 4... 10 var range = Enumerable.Range(1, 10); // Convert range into SubItem classes var items = range.Select(i =&gt; new SubItem() {Name = "foo", MagicNumber = i}); Write(items); // Expect to output 1,2,3,4,5,6,7,8,9,10 // Make a change items.First().MagicNumber = 42; Write(items); // Expect to output 42,2,3,4,5,6,7,8,9,10 // Actual output: 1,2,3,4,5,6,7,8,9,10 } public static void Write(IEnumerable&lt;SubItem&gt; items) { Console.WriteLine(string.Join(", ", items.Select(item =&gt; item.MagicNumber.ToString()).ToArray())); } public class SubItem { public string Name; public int MagicNumber; } </code></pre> <p>What aspect of C# stops my "MagicNumber = 42" change from being output? Is there a way I can get my change to "stick" without doing some funky converting to List&lt;> or array?</p> <p>Thanks! -Mike</p>
<p>When you call First() it enumerates over the result of this bit of code:</p> <pre><code>Select(i =&gt; new SubItem() {Name = "foo", MagicNumber = i}); </code></pre> <p>Note that the Select is a lazy enumerator, meaning that it only does the select when you ask for an item from it (and does it <em>every</em> time you ask it). The results are not stored anywhere, so when you call items.First() you get a new <code>SubItem</code> instance. When you then pass items to Write, it gets a whole bunch of new <code>SubItem</code> instances - not the one you got before.</p> <p>If you want to store the result of your select and modify it, you need to do something like:</p> <pre><code>var items = range.Select(i =&gt; new SubItem() {Name = "foo", MagicNumber = i}).ToList(); </code></pre>
<p>I suspect something going in the background. Most likely due to the fact the IEnumerables can only be iterated once.</p> <p>Does it work if you add a 'ToList()' after the call to Select() when assigning to 'items'?</p>
41,013
<p>With stackoveflow.com in perspective (team of 2-3 engineers building a website project intended to scale) does it make sense to spend effort early in the process of development to build a search based on Lucene/Autonomy… as opposed to a database based full text search. </p> <p>Pros/Cons:<br> With a mature Lucene implementation like nutch or autonomy, the cost of moving to Lucene (which is inevitable) at a later stage is negligible.<br> In large volumes adding additional index servers (say with nutch) to maintain the growing search index is relatively easy.<br> With a Lucene implementation I’ll mostly likely need an additional server to main the in-memory index (much early in the process of scaling). </p>
<p>Database fulltext search performance varies from database to database, but it's by far the easiest option to setup. So start with that, and move to lucene or sphinx if it proves to be too slow.</p>
<p>You should keep it isolated though - don't start throwing SELECTS all over your code if you know you will replace them with a search engine query. Wrap your DB's full text search with a thin abstraction layer that makes sure you don't use database capabilities where you shouldn't.</p> <p>I second the accepted answer though - premature optimization here is definitely evil.</p>
38,315
<p>I'm making a twitter client, and I'm evaluating the various ways of protecting the user's login information.</p> <ul> <li>Hashing apparently doesn't do it</li> <li>Obfuscating in a reversable way is like trying to hide behind my finger</li> <li>Plain text sounds and propably is promiscuous</li> <li>Requiring the user to type in his password every time would make the application tiresome</li> </ul> <p>Any ideas ?</p>
<p>You could make some OS calls to encrypt the password for you.</p> <p>On Windows:</p> <ul> <li>You can encrypt a file (on a NTFS filesystem)</li> <li>Use the <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx" rel="nofollow noreferrer">DPAPI</a> from C</li> <li>Use the DPAPI in .Net by using the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx" rel="nofollow noreferrer">ProtectedData</a> class</li> </ul>
<p>You can't have your cake and eat it too. Either store the password (which you've ruled out), or don't and require it to be typed in every time (which you've ruled out.)</p>
27,868
<p>I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.</p> <p>I don't think I can use:</p> <pre><code>$dbh-&gt;{Name} </code></pre> <p>because I call <a href="http://dev.mysql.com/doc/refman/5.0/en/use.html" rel="noreferrer"><code>USE new_database</code></a> and <code>$dbh-&gt;{Name}</code> only reports the database that I initially connected to.</p> <p>Is there any trick or do I need to keep track of the database name?</p>
<p>Try just executing the query </p> <pre><code>select DATABASE(); </code></pre> <p>From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)</p>
<p>When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL <code>USE database_name</code> will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.</p>
39,652
<p>is there a managed code (without adding COM component or wrapped called to C++ routines) way to add integrated security to a C# Managed code assembly? </p> <p>i.e. I want to write a client-server system where the server uses Remoting instead of IIS, but I want the client to automatically pass it's credentials to the server just like a browser does when communicating with an IIS server that has Integrated security enabled... </p> <p>Can this be done? and if so, where is there some examples ?</p>
<p>No - there is no pure managed interface to <a href="http://msdn.microsoft.com/en-us/library/aa380493(VS.85).aspx" rel="noreferrer">SSPI</a>. But, there is an MSDN sample that <a href="http://msdn.microsoft.com/en-us/library/ms973911.aspx" rel="noreferrer">wraps SSPI for you</a>, and then <a href="http://msdn.microsoft.com/en-us/library/ms973909.aspx" rel="noreferrer">uses the wrapper for remoting</a>.</p>
<p>When you say "remoting instead of IIS," what exactly do you mean? A remoting endpoint (the server end) is typically hosted in IIS since this gives you lots of stuff for free, like authentication, scaling through load balancing - especially for singlecall type objects - that is to say, you don't want to keep state for successive calls to the endpoint. </p> <p>You can host a remoting endpoint using the http stack in a client app also in xp/sp2 and beyond utilising the http.sys driver directly (which is handleded automatically for you btw).</p> <p>Regardless, for automatic logon with NTLM credentials, I suggest you host remoting in IIS, and use System.Net.CredentialCache.DefaultCredentials for the client's credentials your client app. This will pass the context credentials to the server app, presuming the current security zone (intranet/internet/trusted/etc) allows it.</p> <p>-Oisin</p>
38,277
<p>What I want is lots of nodes which can expand making a mind map.</p> <p>I'd ideally like to expand and collapse nodes. I would like to be able to navigate by either dragging around the page, or by following expanded nodes.</p>
<p>I have a colleague who needed that kind of functionalities to graph Maven dependencies between projects. He ended up using <a href="http://freemind.sourceforge.net/" rel="nofollow noreferrer">FreeMind</a> to do the visualization. He just had to write an XML file conforming to the FreeMind format. I even think you can just use <a href="http://www.opml.org/" rel="nofollow noreferrer">OPML</a> as the file format and find a ready to use XSLT to transform it to the FreeMind format. Maybe FreeMind actually supports OPML directly (I havent used it for a long time).</p> <p>Once you have your data in FreeMind, you can either export them, or use the <a href="http://freemind.sourceforge.net/docs/Serving%20Freemind%20maps%20in%20a%20browser/freemind%20applet.html" rel="nofollow noreferrer">FreeMind applet</a> to display an interactive MindMap on your website.</p>
<p>I think you are asking for a component that does what Visio can do, except that it can be displayed on a web page. Most likely you would have to create one from scratch, because mind mapping tools are always released as products per se and not customizable components. I suggest looking for a basic drawing/illustration component, and then putting your mind-mapping logic in it.</p>
8,750
<p>How does sharepoint identify a file type? For example, SharePoint will not allow you to upload executable files. Suppose if i rename a file extension from .exe to say, .doc, will the sharepoint allow the upload of this file? </p>
<p>Sharepoint recognize file types using their extensions.</p> <p>If you are worried about users spreading malicious application/code in your Sharepoint Sites. I suggest you to take a look at <a href="http://www.microsoft.com/forefront/sharepoint/en/us/default.aspx" rel="nofollow noreferrer">Microsoft Forefront For Sharepoint</a>.</p> <p>You can modify the excluded extension list under <strong>Central Administration > Operations > Blocked File Types</strong>.</p>
<p>I believe there are two ways to identify file types. A naive approach is to check the extension. A more secure approach would be to examine the bits of the file and see what type the file is as many file types have a few bits (<a href="http://en.wikipedia.org/wiki/File_format#Magic_number" rel="nofollow noreferrer">magic numbers</a>) in the header that identify the format.</p> <p>Depending on how SharePoint checks the file, that will determine how you can cheat the system.</p>
25,218
<p>I have seen Jetbrain's ReSharper tool on many "must-have" tool lists. I've installed it on a few occasions over the last few years and it's turned my Visual Studio sluggish and erratic. I generally uninstall it after a week or two because it make VS flaky, I want to like it, but I can't get past the instability. </p> <p>So what's the deal? Am I having bad luck? Does the tool have issues but the usefulness out weighs the issues? Anyone else out there have trouble with it? Are there some troublesome options to turn off?</p>
<p>These previously asked questions should help in answering your <strong>duplicate</strong> question:</p> <ul> <li><a href="https://stackoverflow.com/questions/23737/do-you-have-any-tips-to-improve-resharper-andor-visual-studio-performance">Do you have any tips to improve resharper and/or visual studio performance ?</a></li> <li><a href="https://stackoverflow.com/questions/84009/resharper-sluggishness">ReSharper sluggishness</a></li> </ul>
<p>I've experienced a lot of what you're talking about over the years as well, but I have to say having recently moved to the 4.0 version of ReSharper, a lot of that overhead has been cut down dramatically and it seems to be quite a bit more functional to boot.</p> <p>Try it again. What's the worst that can happen? You'll uninstall it again? No big loss.</p>
20,432
<p>I have a .NET application that is meant to be run on a local PC and started from a file share on the LAN.</p> <p>It works fine on 32 bit Windows XP and Vista workstations.</p> <p>But it fails with a System.InvalidOperationException on 64 bit Windows Server 2008.</p> <p>It runs fine locally on all three configurations.</p> <p>What could be the cause?</p> <p>.NET 2.0 is installed an all machines involved.</p> <p>Summary:</p> <p>32 bit XP: runs locally and remotely 32 bit Vista: runs locally and remotely 64 bit 2008: runs locally, fails remotely</p> <p>"remotely" means running locally but launched from a file share rather than a local drive.</p> <p>Zone security is set to "full trust" for "Local Intranet" on all machines involved including the 64 bit 2008 machine.</p> <p>Any ideas?</p>
<p>Are the projects set to run in x86 mode? Use the configuration Manager to check.</p>
<p>My first guess would be Internet Explorer security settings. Try adding your server as a Trusted Site.</p>
17,823
<p>Let's say I have one class <code>Foo</code> that has a bunch of logic in it and another class <code>Bar</code> which is essentially the same. However, as <code>Foo</code> and <code>Bar</code> are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a <code>Foo</code> or a <code>Bar</code>)</p> <p>As I was whacking this together without much thought I ended up with the following:</p> <pre><code>public class Foo { /* constructors, fields, method, logic and what-not */ } public class Bar extends Foo { /* nothing here but constructors */ } </code></pre> <p>Is this OK? Is it better to make <code>Bar</code> a composite class? e.g:</p> <pre><code>public class Bar { private Foo foo; /* constructors and a bunch of wrapper methods that call into foo */ } </code></pre> <p>Or even, while we're at it, something much more low-tech:</p> <pre><code>public class Foo { /* constructors, fields, method, logic and what-not */ private boolean isABar; // Could be an enum } </code></pre> <p>What do you think? <strong>How do you deal with these 'marker classes'?</strong></p> <hr> <p>As an example of how my code may wish to treat <code>Foo</code> and <code>Bar</code> differently, my code would need to be able to do stuff like <code>List&lt;Foo&gt;</code> and <code>List&lt;Bar&gt;</code>. A <code>Foo</code> couldn't go in a <code>List&lt;Bar&gt;</code> and vice versa.</p>
<p>In my opinion, it's best if <code>Foo</code> and <code>Bar</code> subclass off a common ancestor class (maybe <code>AbstractFoo</code>), which has all the functionality. What difference in behaviour should exist between <code>Foo</code> and <code>Bar</code>? Code that difference as an abstract method in <code>AbstractFoo</code>, not by using a <code>if</code> statement in your code.</p> <p>Example: Rather than this:</p> <pre><code>if (foo instanceof Bar) { // Do Bar-specific things } </code></pre> <p>Do this instead:</p> <pre><code>class Bar extends AbstractFoo { public void specialOp() { // Do Bar-specific things } } // ... foo.specialOp(); </code></pre> <p>The benefit of this approach is that if you need a third class, that's much like <code>Foo</code> but has just a little bit of difference, you don't have to go through all your code and add edit all the <code>if</code> statements. :-)</p>
<p>Definitely use a boolean property. It's the simplest solution, unless you foresee the Bar class needing to change it's interface later (e.g. override it's methods).</p>
17,284
<p>okee, I followed all instructions I could find <a href="https://stackoverflow.com/questions/279170/utf-8-all-the-way-through">here</a> and i could display all kinds of multilingual characters on my pages...<br> The problem is in phpmyadmin the japanese characters are replaced by question marks, as in a bunch of <code>???? ???</code> pieced together. I think there's a problem with my database's collation but I just wanted to verify that here.</p> <p>We've had this database set before on a default collation which is <code>latin_swedish_ci</code> and it already has a lot of data. Now we had to add some tables that require support for special characters, so I definitely just couldn't set the database's collation to <code>utf8</code>. My solution was to use <code>utf8</code> only on the tables which required such support and the specific columns where we expected special characters to be contained.<br> But still phpmyadmin displayed them as <code>????</code>.</p> <p>Another question that I have is will these fields be searchable?<br> I mean if the field contains some japanese characters and I typed <code>sayuri</code> as keyword, will the japanese character equivalent to their syllables pronounced in english?</p>
<p>Mmm, as to your first question do you have Japanese fonts installed on your system? They aren't installed by default on most OSs, but I have no idea what your OS is. Next one is silly but are your Browser settings Ok?</p> <p>Next question, the answer is no, if you search for 吉永 小百合 it wont' match with Yoshinaga Sayuri. </p> <p>Note: Can you see my Japanese characters?</p>
<p>The problem is that your connection collation is not set to utf-8 (most probably latin1), which you need to display the Japanese characters. You could set it manually by issuing the queries:</p> <pre><code>SET CHARACTER SET utf8; SET NAMES utf8; </code></pre> <p>Or in your MySQL configuration file:</p> <pre><code>default-character-set=utf8 skip-character-set-client-handshake </code></pre>
43,123
<p>On my homepage I got:</p> <pre><code>&lt;ul id="login"&gt; &lt;li&gt; &lt;a id="loginswitch" href="./login-page"&gt;log-in&lt;/a&gt; | &lt;/li&gt; &lt;li&gt; &lt;a id="signupswitch" href="./signup-page"&gt;sign-up&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course) and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc..</p> <p>The ajax call is initiated by the MooTools AJAX class and <code>evalScripts</code> option is set to true. The AJAX page returns the script code:</p> <pre><code>&lt;script type="text/javascript"&gt;window.location = self.location;&lt;/script&gt; </code></pre> <p>This system works perfectly - now I'm wondering why if I change the anchors' <code>href</code> values to <code>href="#"</code> my scripts won't work anymore?</p> <p>Does it have anything to do with the window?</p> <p>Did it change its property when I clicked a link or so even when the event's propagation was stopped??</p>
<pre><code>window.location = self.location; </code></pre> <p><strong>This JavaScript is executing</strong>.</p> <p>When it executes, the browser is being told to replace the value of <code>window.location</code> with a new value. <strong>Not all browsers</strong> will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. <strong>The browser knows</strong> what page it's on, and it knows that you're just asking for it to go to the same page.</p> <p><strong>Browser Cache</strong></p> <p>The browser even has a copy of your current page in <strong>cache</strong>. It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this:</p> <pre><code>GET /stackoverflow.com/posts/196643/index.html HTTP/1.1 Host: www.stackoverflow.com User-Agent: Mozilla/5.0 If-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT </code></pre> <p>This is called a <strong>conditional GET request</strong>. By saying <em>If-Modified-Since</em>, your browser is saying, &quot;Give me that file, but only if it has been modified since the last time I saw it.&quot;</p> <p>Long story short, you haven't explicitly told the browser to reload the page.</p> <p><strong>Here's how you can:</strong></p> <pre><code>location.reload( true ); </code></pre> <p>The &quot;true&quot; is an <strong>optional parameter</strong>, for <strong>forcing a reload</strong>. The browser won't even look at the cache. It will just do as you say.</p>
<p>If they handed me this particular task at work I'd kick it back to design. Unless we're talking about a secure page, or an OpenID login, you should not pop up a log-in or sign-in form. Users need to learn to look for that https: at the top of their page, and never sign in if they don't see it.</p>
21,856
<p>Say I have a package "mylibrary".</p> <p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p> <p>I.e., I do:</p> <pre><code>import sys, types sys.modules['mylibrary.config'] = types.ModuleType('config') </code></pre> <p>Given that setup:</p> <pre><code>&gt;&gt;&gt; import mylibrary.config # -&gt; works &gt;&gt;&gt; from mylibrary import config &lt;type 'exceptions.ImportError'&gt;: cannot import name config </code></pre> <p>Even stranger:</p> <pre><code>&gt;&gt;&gt; import mylibrary.config as X &lt;type 'exceptions.ImportError'&gt;: cannot import name config </code></pre> <p>So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?</p>
<p>You need to monkey-patch the module not only into sys.modules, but also into its parent module:</p> <pre><code>&gt;&gt;&gt; import sys,types,xml &gt;&gt;&gt; xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config') &gt;&gt;&gt; import xml.config &gt;&gt;&gt; from xml import config &gt;&gt;&gt; from xml import config as x &gt;&gt;&gt; x &lt;module 'xml.config' (built-in)&gt; </code></pre>
<p>You can try something like this:</p> <pre><code>class VirtualModule(object): def __init__(self, modname, subModules): try: import sys self._mod = __import__(modname) sys.modules[modname] = self __import__(modname) self._modname = modname self._subModules = subModules except ImportError, err: pass # please signal error in some useful way :-) def __repr__(self): return "Virtual module for " + self._modname def __getattr__(self, attrname): if attrname in self._subModules.keys(): import sys __import__(self._subModules[attrname]) return sys.modules[self._subModules[attrname]] else: return self._mod.__dict__[attrname] VirtualModule('mylibrary', {'config': 'actual_module_for_config'}) import mylibrary mylibrary.config mylibrary.some_function </code></pre>
48,047
<p>I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.</p> <p>How can I add cookies from a Python CookieJar to ZSI requests?</p>
<p>If you read the <a href="https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py" rel="nofollow noreferrer">_Binding class in client.py of ZSI</a> you can see that it has a variable cookies, which is an instance of <a href="http://docs.python.org/lib/module-Cookie.html" rel="nofollow noreferrer">Cookie.SimpleCookie</a>. Following the <a href="http://pywebsvcs.sourceforge.net/zsi.html#SECTION003210000000000000000" rel="nofollow noreferrer">ZSI example</a> and the <a href="http://docs.python.org/lib/cookie-example.html" rel="nofollow noreferrer">Cookie example</a> that is how it should work:</p> <pre><code>b = Binding(url='/cgi-bin/simple-test', tracefile=fp) b.cookies['foo'] = 'bar' </code></pre>
<p>Additionally, the Binding class also allows any header to be added. So I figured out that I can just add a "Cookie" header for each cookie I need to add. This worked well for the code generated by wsdl2py, just adding the cookies right after the binding is formed in the SOAP client class. Adding a parameter to the generated class to take in the cookies as a dictionary is easy and then they can easily be iterated through and added.</p>
16,846
<p>Consider the following piece of Java code.</p> <pre><code>int N = 10; Object obj[] = new Object[N]; for (int i = 0; i &lt; N; i++) { int capacity = 1000 * i; obj[i] = new ArrayList(capacity); } </code></pre> <p>Because in Java, all objects live on the Heap, the array does not contain the objects themselves, but references to the objects. Also, the array itself is also an object, thus it lives on the heap.</p> <p>What is the equivalent in C++, but keeping the array and objects on the stack, to avoid as much as possible needing new and delete ?</p> <p>Edit: changed the code to use a custom constructor.</p>
<p>Simply declaring</p> <pre><code>Object array_of_objects[10]; </code></pre> <p>in C++ creates 10 default-constructed objects of type Object on the stack.</p> <p>If you want to use a non-default constructor, that's not so easy in C++. There might be a way with placement new but I couldn't tell you off the top of my head.</p> <p><strong>EDIT: Link to other question on StackOverflow</strong> How to use placement new for the array is explained in the answer to <a href="https://stackoverflow.com/questions/15254/can-placement-new-for-arrays-be-used-in-a-portable-way">this question</a> here on StackOverflow.</p>
<p>If you happen to use Qt, you can use the <a href="http://qt-project.org/doc/qt-5.1/qtcore/qvarlengtharray.html" rel="nofollow">QVarLengthArray</a></p> <p>It takes a size as a second template parameter, and it will statically allocate an array with that size, and use that as the backing for the array instead of the heap like a std::vector or QVector does. If you add more than the template-specified size, it'll use heap allocation instead.</p> <p>Example: </p> <pre><code>//the following ints will all be stored on the stack, //and a heap allocation is never performed to store the array QVarLengthArray&lt;int, 10&gt; objArray; for (int i = 0; i &lt; 8; i++) { int capacity = 1000 * i; objArray.push_back(capacity); } //since it's a class and not a raw array, we can get the array's size std::cout &lt;&lt; objArray.size(); //result is 8 //a heap allocation will be performed if we add an eleventh item, //since the template parameter of 10 says to only statically allocate 10 items objArray.push_back(0); //9 items objArray.push_back(0); //10 items objArray.push_back(0); //11 items - heap allocation is performed </code></pre> <p>If you stay below the template parameter size, you'll avoid the performance hit of a heap allocation - you'll effectively have a dynamically allocated stack-based array. The only disadvantage is that it's wasteful of memory if you don't use exactly as many items as the template parameter specifies: If you use too few, then the empty spaces are wasted. if you use too many, then the entire stack allocated area is wasted.</p> <p>Sometimes trading performance for memory is worth it, and sometimes it isn't. I would recommend against blindly using this class - only use it if you <em>know</em> via profiling that the heap allocation of std::vector is one of your program's bottlenecks.</p>
41,463
<p>Is there a standard Java library that handles common file operations such as moving/copying files/folders?</p>
<p>Here's how to do this with <code>java.nio</code> operations:</p> <pre><code>public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); // previous code: destination.transferFrom(source, 0, source.size()); // to avoid infinite loops, should be: long count = 0; long size = source.size(); while((count += destination.transferFrom(source, count, size-count))&lt;size); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } </code></pre>
<p>Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.</p> <p>Duration using FileOutputStream byte stream: 4 965 078</p> <p>Duration using BufferedOutputStream: 1 237 206</p> <p>Duration using (character text Reader: 2 858 875</p> <p>Duration using BufferedReader(Buffered character text stream: 1 998 005</p> <p>Duration using (Files NIO copy): 18 351 115</p> <p>when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.</p>
38,531
<p>If I have an inner class, like this:</p> <pre><code>public class Test { public class Inner { // code ... } public static void main(String[] args) { // code ... } } </code></pre> <p>When I compile it, I expect it should generate two files:</p> <pre><code>Test.class Test$Inner.class </code></pre> <p>So why do I sometimes see classfiles like SomeClass$1.class, even though SomeClass does not contain an inner class called "1"?</p>
<p>The SomeClass$1.class represent anonymous inner class</p> <p>hava a look at the anonymous inner class section <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html" rel="noreferrer">here</a> </p>
<p>to build up on hhafez : SomeClass$1.class represents anonymous inner classes. An example of such a class would be </p> <pre><code>public class Foo{ public void printMe(){ System.out.println("redefine me!"); } } public class Bar { public void printMe() { Foo f = new Foo() { public void printMe() { System.out.println("defined"); } }; f.printMe(); } } </code></pre> <p>From a normal Main, if you called new Bar().printMe it would print "defined" and in the compilation directory you will find Bar1.class</p> <p>this section in the above code : </p> <pre><code> Foo f = new Foo() { public void printMe() { System.out.println("defined"); } }; </code></pre> <p>is called an anonymous inner class.</p>
49,848
<p>I'm writing a shell script to do some web server configuration. I need to disable all currently active virtual hosts. <code>a2dissite</code> doesn't accept multiple arguments, so I can't do</p> <pre><code>a2dissite `ls /etc/apache2/sites-enabled` </code></pre> <p>Should I use <code>find</code>? Is it safe to manually delete the symlinks in <code>/etc/apache2/sites-enabled</code>?</p>
<p>Is your script Debian only? If so, you can safely delete all the symlinks in sites-enabled, that will work as long as all sites have been written correctly, in the sites-available directory.</p> <p>For example:</p> <pre><code> find /etc/apache2/sites-enabled/ -type l -exec rm -i "{}" \; </code></pre> <p>will protect you against someone who has actually written a file instead of a symlink in that directory.</p> <p>(remove the -i from rm for an automatic script, of course)</p>
<p>you can edit the httpd.conf and delete the include line for the virtual hosts (at the bottom of the file) </p>
22,137
<p>I want to skin a vb.net app I made ive googled some stuff and I've seen skinned vb.net apps. </p> <p>However it seems like any time i try to find someone explaining it its a link to a pay for product.</p> <p>Does anyone have anything useful on this?</p> <hr> <p>I have seen some free ways to do this programatically I cannot seem to make it translate entirely over to my own unique program.</p>
<p>I remember making a "skinnable" vb.net winforms app (a media player) when I was still a student (maybe 6 years ago).</p> <p>It was ugly, but the way I did it was as follows:</p> <ol> <li><p>Select a transparency color. Wherever you use this color the app will be transparent (I used Fuchsia (#FF00FF), which I recall being a standard for video games back in the day.</p></li> <li><p>Use a naming convention for child controls (particular buttons, sliders, etc).</p></li> <li><p>Create images for the controls in step 2.</p></li> <li><p>Set 1 pixel wide color coated place holders for those controls. Eg a blue pixel was my play button, a green pixel was my pause button, etc. The placeholder marked the upper left corner of the control.</p></li> <li><p>At runtime dynamically generate the controls (really images with onclick events) and place them on top of the place holders.</p></li> </ol> <p>I'm sure there is a nicer way to do this, but that was my crude approach.</p>
<p>Unfortunatly VB.NET does not provide 'skinning' out of the box. It simply uses the standard windows interface. The only changes to the UI are made when you change the display properties.</p> <p>I'm not aware of an open source project that provides skinning functionality, however I have used a number of commercial products. By far, one of the best I have used is the Application Styling Framework found in <a href="http://www.infragistics.com/dotnet/netadvantage.aspx#Overview" rel="nofollow noreferrer">NET Advantage</a> by Infragistics.</p>
29,517
<p>I'm currently designing a database schema that's used to store recipes. In this database there are different types of entities that I want to be able to tag (ingredients, recipe issuers, recipes, etc). So a tag has multiple n:m relations. If I use the "three table design", this would result in tables (cross table) for every entity type (recipes, ingredients, issuers) that I have. In other words every time I introduce an entity I have to add a cross table for it.</p> <p>I was thinking of creating one table which has a unique id, that all the entities refer to, and a n:m relation between the tags table and the "unique id"-table. This way there is just one cross table between the "unique id"-table and the tag table.</p> <p>Just in case that some people will think this question already was asked. I already read <a href="https://stackoverflow.com/questions/48475/database-design-for-tagging">Database Design for Tagging</a>. And there the three table design is mentioned.</p>
<p>I don't see anything wrong with having a single table for all tag assignments (as opposed to multiple tables - one for each taggable entity). </p> <p>However, one important detail in your design remains ambiguous to me: if you are going to have something along these lines</p> <pre><code>- - - - - - - - - - Tag ID // PK Name ... - - - - - - - - - - Taggable ID // PK ... - - - - - - - - - - TagAssignment Tag_ID // FK -&gt; Tag.ID Taggable_ID // FK -&gt; Taggable.ID ... - - - - - - - - - - EntityOne Taggable_ID // FK -&gt; Taggable.ID ... - - - - - - - - - - EntityTwo Taggable_ID // FK -&gt; Taggable.ID ... </code></pre> <p>then are your entity classes going to have their own primary keys or are you going to use <code>EntityOne.TaggableID</code> and <code>EntityTwo.TaggableID</code> as de facto primary keys for <code>EntityOne</code> and <code>EntityTwo</code>?</p> <p>In most general case, I would be cautious and let entities have their own IDs:</p> <pre><code>- - - - - - - - - - EntityOne ID // PK Taggable_ID // FK -&gt; Taggable.ID (Nullable) ... - - - - - - - - - - EntityTwo ID // PK Taggable_ID // FK -&gt; Taggable.ID (Nullable) ... </code></pre> <p>This would not require each entity to have a corresponding instance of <code>Taggable</code> and therefore this would not require every piece of code concerned with an entity to also be aware of tags. However, if tagging is going to be really ubiquitous in the system, and if you are sure that you won't need any other "common ancestors" for entities (that is, other than <code>Taggable</code>), then you might get away without "intrinsic" IDs for entities.</p> <p><strong>NB</strong>: I never tried to implement anything like this, so all my recommendations are purely theoretical. So please do not shoot me if I do not see some obvious flaws. :-)</p> <hr> <p>In response to Bill Karwin's comment: </p> <p>You are right: the design described above does not prevent multiple entities to refer to same <code>Taggable</code>. But:</p> <ol> <li><p>Like I said, all depends on requirements. If we are sure that <code>Taggable</code> is going to be the only "common ancestor" of entities, then it is okay to use <code>Taggable_ID</code> FKs as PKs for entities. But, for example, what if some entities that happen to be "taggable" also have to be "watchable" (think notifications, notification schedules, etc.) or "whatever-able" :-)? Can we cut all those "abilities" off by tying any entity hard to <code>Taggable</code>? </p></li> <li><p>If you really want to have DB-level enforcement of one-taggable-one-entity constraint... AFAIK, there is at least one common way to do that without making FKs serve as PKs: by introducing "types" of taggables (which may be useful for some other functionality anyway). </p></li> </ol> <p>Something along these lines would let us have a cake and eat it:</p> <pre><code>- - - - - - - - - - Taggable ID // PK Type ... - - - - - - - - Constraint: (ID, Type) is unique - - - - - - - - - - EntityOne ID Taggable_ID Taggable_Type // Constraint: always = 'EntityOne' ... - - - - - - - - FK: (Taggable_ID, Taggable_Type) -&gt; (Taggable.ID, Taggable.Type) </code></pre> <p>Of course, all this is more complicated than just having entities tied to taggables. But I was just trying to discuss what, in my humble opinion, should be considered in addition to the narrow picture provided by the original question.</p>
<p>Howabout this?</p> <p>Types( PK:<strong>Type</strong>,set_id[,TypeDesc])</p> <p>Attributes( PK:(<strong>set_id</strong>,FK:<strong><em>Type</em></strong>),Value)</p> <p>PS: Bold/Italics Realy Suck</p>
38,786
<p>Now this is all way simplified, but here goes:</p> <p>I have a User Control that consists only of a single *.ascx file. The control has no code-behind: it's just a script with a few functions, like this:</p> <pre><code>&lt;%@ Control Language="VB" EnableViewState="False" ClassName="MyControlType" %&gt; &lt;script runat="server"&gt; Public Function MyFunction() As String return "CalledMyFunction!" End Function &lt;/script&gt; </code></pre> <p>That's the entire file. I can successfully add this control to an aspx page using markup like so:</p> <pre><code>&lt;%@ Register Src="~/path/to/Control.ascx" TagPrefix="aaa" TagName="MyControl" %&gt; ... &lt;aaa:MyControl runat="server" id="MyControl1" /&gt; </code></pre> <p>Now what I want to do is call MyFunction from the page's code-behind, like this:</p> <pre><code>Dim someString As String = MyControl1.MyFunction() </code></pre> <p>Unfortunately, I can't do that. Instead, I get a compile error to the effect of "<code>'MyFunction' is not a member of 'System.Web.UI.UserControl'.</code>"</p> <p>I've also tried this:</p> <pre><code>Dim someString As String = DirectCast(MyControl1, MyControlType).MyFunction() </code></pre> <p>and then the compiler tells me, "<code>Type 'MyControlType' is not defined.</code>"</p> <p>I've played with this a lot, and I just can't make it work. All efforts to cast MyControl1 to a more exact type have failed, as have other work-arounds. I suspect the problem is that the ascx file without a code-behind is unable to be compiled to an assembly but the code-behind wants to be compiled to an assembly and therefore the compiler gets confused about what type the control is.</p> <p>What do I need to do to be able to call that function?</p> <p>[edit]<br> So I'm just gonna have to add code-behind for the user control. It's what I wanted to do anyway. I'd still like to know how to do this without needing one, though.</p>
<p>Weird works for me.</p> <pre><code>Imports Microsoft.VisualBasic Public Class MyControlType Inherits UserControl End Class </code></pre> <p>.</p> <pre><code>&lt;%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %&gt; &lt;%@ Register Src="~/WebUserControl.ascx" TagPrefix="aaa" TagName="MyControl" %&gt; ... &lt;aaa:MyControl runat="server" id="MyControl1" /&gt; </code></pre> <p>.</p> <pre><code>Partial Class _Default Inherits System.Web.UI.Page Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) Dim someString As String = MyControl1.MyFunction() End Sub End Class </code></pre> <p>.</p> <pre><code>&lt;%@ Control Language="VB" EnableViewState="False" %&gt; &lt;script runat="server"&gt; Public Function MyFunction() As String return "CalledMyFunction!" End Function &lt;/script&gt; </code></pre>
<p>Place this in your code behind declarations </p> <pre><code>protected &lt;solutionName&gt;.&lt;controlName&gt; myControl1; /*C#*/ </code></pre> <p>here myControl1 is the id of your user control. Now you may call public functions of this control. </p>
47,090
<p>Has anyone successfully talked <a href="http://www.profibus.com/" rel="noreferrer">profibus</a> from a .NET application?</p> <p>If you did, what device/card did you use to accomplish this, what was the application, and did you use any kind of preexisting or available code?</p>
<p>We've not used Profibus, but have used <strong>DeviceNET</strong> (another CAN based protocol), <strong>Ethernet/IP</strong> and <strong>ControlNet</strong> which all have similar challenges.</p> <p>We've been doing this since the late 1990's and therefore rely mainly on our own generated code using off-the-shelf hardware. The companies that have shown longevity during that period that I remember are:-</p> <ul> <li>AnyBus (HMS, <a href="http://www.anybus.com" rel="noreferrer">www.anybus.com</a>) we've recently started using their gateway products as we can place fieldbus interfaces close to the hardware and then communicate over normal Ethernet (usually using Ethernet/IP <a href="http://www.odva.org" rel="noreferrer">www.odva.org</a>). This has the advantage of separating hardware and PC using only a network cable. The Ethernet/IP .NET classes were written by ourselves as nothing much was on the market at the time. I'm sure a quick google search would find suitable class libraries</li> <li>SST (<a href="http://www.mysst.com" rel="noreferrer">www.mysst.com</a>) have had fieldbus interfaces for more than a decade. The last SST card we used for DeviceNET still only had VB6 sample code. A good selection of fieldbus support and different form-factors e.g. PC104, PCI, PMCIA</li> <li>Beckhoff/Wago (<a href="http://www.beckhoff.com" rel="noreferrer">www.beckhoff.com</a>, <a href="http://www.beckhoff.com" rel="noreferrer">www.wago.com</a>) we typically use Beckhoff for the I/O more than the interface cards but again a company that has been around a long time. They also have products that support exposing using OPC (another way for you to get I/O information without directly communicating with the hardware/devicedrivers)</li> </ul> <p>I suggest not using OPC interfaces to the hardware directly (it’s OK for communication using PC (.NET)->PLC->Profibus) as you need to ensure that the control system responds to loss of control from your .NET application. I’m assuming that you are needing a profibus Master here (not a slave), so as long as your control system is intrinsically fail safe, then loss of communication should mean the control system enters an "Idle" state and therefore most of the I/O will return to the fails safe state.</p> <p>We also try to ensure that we do not put safety related code in .NET. Most of our .NET code is userinterface from a PLC, but in some places we do control the fieldbus directly but ensure hardware interlocks will prevent un-safe operation, either using safety switches/relays or a small PLC with the the task of interlocking only. <strong>And above all make the system fail-safe!</strong> Loss of comms from the .NET code should shutdown the automation to the fail-safe state.</p>
<p>Try this: <a href="http://libnodave.sourceforge.net" rel="nofollow noreferrer">http://libnodave.sourceforge.net</a></p>
9,220
<p>How do I check if a given object is nullable in other words how to implement the following method...</p> <pre><code>bool IsNullableValueType(object o) { ... } </code></pre> <p>I am looking for nullable <em>value types.</em> I didn't have reference types in mind.</p> <pre><code>//Note: This is just a sample. The code has been simplified //to fit in a post. public class BoolContainer { bool? myBool = true; } var bc = new BoolContainer(); const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ; object obj; object o = (object)bc; foreach (var fieldInfo in o.GetType().GetFields(bindingFlags)) { obj = (object)fieldInfo.GetValue(o); } </code></pre> <p><code>obj</code> now refers to an object of type <code>bool</code> (<code>System.Boolean</code>) with value equal to <code>true</code>. What I really wanted was an object of type <code>Nullable&lt;bool&gt;</code></p> <p>So now as a work around I decided to check if o is nullable and create a nullable wrapper around obj.</p>
<p>There are two types of nullable - <code>Nullable&lt;T&gt;</code> and reference-type.</p> <p>Jon has corrected me that it is hard to get type if boxed, but you can with generics: - so how about below. This is actually testing type <code>T</code>, but using the <code>obj</code> parameter purely for generic type inference (to make it easy to call) - it would work almost identically without the <code>obj</code> param, though.</p> <pre><code>static bool IsNullable&lt;T&gt;(T obj) { if (obj == null) return true; // obvious Type type = typeof(T); if (!type.IsValueType) return true; // ref-type if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable&lt;T&gt; return false; // value-type } </code></pre> <p>But this won't work so well if you have already boxed the value to an object variable.</p> <p>Microsoft documentation: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type</a></p>
<p>a simple way to do this:</p> <pre><code> public static bool IsNullable(this Type type) { if (type.IsValueType) return Activator.CreateInstance(type) == null; return true; } </code></pre> <p>these are my unit tests and all passed</p> <pre><code> IsNullable_String_ShouldReturn_True IsNullable_Boolean_ShouldReturn_False IsNullable_Enum_ShouldReturn_Fasle IsNullable_Nullable_ShouldReturn_True IsNullable_Class_ShouldReturn_True IsNullable_Decimal_ShouldReturn_False IsNullable_Byte_ShouldReturn_False IsNullable_KeyValuePair_ShouldReturn_False </code></pre> <p>actual unit tests</p> <pre><code> [TestMethod] public void IsNullable_String_ShouldReturn_True() { var typ = typeof(string); var result = typ.IsNullable(); Assert.IsTrue(result); } [TestMethod] public void IsNullable_Boolean_ShouldReturn_False() { var typ = typeof(bool); var result = typ.IsNullable(); Assert.IsFalse(result); } [TestMethod] public void IsNullable_Enum_ShouldReturn_Fasle() { var typ = typeof(System.GenericUriParserOptions); var result = typ.IsNullable(); Assert.IsFalse(result); } [TestMethod] public void IsNullable_Nullable_ShouldReturn_True() { var typ = typeof(Nullable&lt;bool&gt;); var result = typ.IsNullable(); Assert.IsTrue(result); } [TestMethod] public void IsNullable_Class_ShouldReturn_True() { var typ = typeof(TestPerson); var result = typ.IsNullable(); Assert.IsTrue(result); } [TestMethod] public void IsNullable_Decimal_ShouldReturn_False() { var typ = typeof(decimal); var result = typ.IsNullable(); Assert.IsFalse(result); } [TestMethod] public void IsNullable_Byte_ShouldReturn_False() { var typ = typeof(byte); var result = typ.IsNullable(); Assert.IsFalse(result); } [TestMethod] public void IsNullable_KeyValuePair_ShouldReturn_False() { var typ = typeof(KeyValuePair&lt;string, string&gt;); var result = typ.IsNullable(); Assert.IsFalse(result); } </code></pre>
49,005
<p>I have a filename in a format like:</p> <blockquote> <p><code>system-source-yyyymmdd.dat</code></p> </blockquote> <p>I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.</p>
<p>You can use the <a href="http://en.wikipedia.org/wiki/Cut_(Unix)" rel="noreferrer">cut command</a> to get at each of the 3 'fields', e.g.:</p> <pre><code>$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2 source </code></pre> <p>"-d" specifies the delimiter, "-f" specifies the number of the field you require</p>
<p>The simplest (and IMO best way) to do this is simply to use <code>read</code>:</p> <pre><code>$ IFS=-. read system source date ext &lt;&lt; EOF &gt; foo-bar-yyyymmdd.dat &gt; EOF $ echo $system foo $ echo $source $date $ext bar yyyymmdd dat </code></pre> <p>There are many variations on that theme, many of which are shell dependent:</p> <p><code>bash$ IFS=-. read system source date ext &lt;&lt;&lt; foo-bar-yyyymmdd.dat</code></p> <pre><code>echo "$name" | { IFS=-. read system source date ext echo In all shells, the variables are set here...; } echo but only in some shells do they retain their value here </code></pre>
7,194
<p>I am having a problem getting a list of fields from a query defined at run time by the users of my program. I let my users enter a SQL query into a memo control and then I want to let them go through the fields that will return and do such things as format the output, sum column values and so forth. So, I have to get the column names so they have a place to enter the additional information.</p> <p>I would do fine if there were no parameters, but I also have to let them define filter parameters for the query. So, if I want to set the parameters to null, I have to know what the parameter's datatype is.</p> <p>I am using Delphi 2006. I connect to a Firebird 2.1 database using the DBExpress component TSQLConnection and TSQLQuery. Previously, I was successful using:</p> <p>for i := 0 to Qry.Params.Count - 1 do Qry.Params[i].value := varNull;</p> <p>I discovered I had a problem when I tried to use a date parameter. It was just a coincidence that all my parameters up until then had been integers (record IDs). It turns out that varNull is just an enumerated constant with a value of 1 so I was getting acceptable results (no records) was working okay.</p> <p>I only need a list of the fields. Maybe I should just parse the SELECT clause of the SQL statement. I thought setting Qry.Prepared to True would get me a list of the fields but no such luck. It wants values for the parameters. </p> <p>If you have an idea, I would sure like to hear it. Thanks for any help.</p>
<p>Replied again 'coz I'm interested. My methods works (with my queries) because they have been pre-defined with the params' datatypes preset to the correct type:)</p> <p>I'm not sure how you are expecting the query to know or derive the datatype of the param given that you are not even selecting the field that it operates against.</p> <p>So I think your query setup and user input method will need more attention. I've just looked up how I did this a while ago. I do not use a parameterised query - I just get the "parameter values" from the user and put them directly into the SQL. So your sql would then read: </p> <p>SELECT s.hEmployee, e.sLastName<br> FROM PR_Paystub s<br> INNER JOIN PR_Employee e ON e.hKey = s.hEmployee<br> WHERE s.dtPaydate > '01/01/2008'</p> <p>therefore no parameter type knowledge is necessary. Does not stop your users entering garbage but that goes back to input control :)</p>
<pre><code>TmpQuery.ParamByName('MyDateTimeParam').DataType := ftDate; TmpQuery.ParamByName('MyDateTimeParam').Clear; TmpQuery.ParamByName('MyDateTimeParam').Bound := True; </code></pre>
32,570
<p>So basically we have lots of SharePoint usage log files generated by our SharePoint 2007 site and we would like to make sense of them. For that we're thinking of reading the log files and dumping into a database with the appropriate columns and all. Now I was going to make an SSIS package to read all the text files and extract the data when I came across LogParser. Is there a way to use LogParser to dump data into an Sql Server database or the SSIS way is better? Or is there any other better way to use the SharePoint usage logs?</p>
<p>This is the script we use to load IIS log files in a SQL Server database:</p> <pre><code>LogParser "SELECT * INTO &lt;TABLENAME&gt; FROM &lt;LogFileName&gt;" -o:SQL -server:&lt;servername&gt; -database:&lt;databasename&gt; -driver:"SQL Server" -username:sa -password:xxxxx -createTable:ON </code></pre> <p>The <code>&lt;tablename&gt;, &lt;logfilename&gt;, &lt;servername&gt;, &lt;databasename&gt;</code> and sa password need to be changed according to your specs.</p> <p>From my experience LogParser works really well to load data from IIS logs to SQL Server, so a mixed approach is the best:</p> <ul> <li>Load raw data from IIS log to SQL Server using LogParser</li> <li>Use SSIS to extract and manipulate data from the temporary table containing the raw data in the final table you'll use for reporting.</li> </ul>
<p>Sorry I found out that Sharepoint Logs are not the same as IIS logs. They are different. How can we parse them?</p>
21,910
<p>I have a footer that is a 1 x 70px, which is set as the background and tiles horizonally.</p> <p>In cases when the web page does not contain a lot of content on it, it will display the footer above where the footer should be. I want it to fill in with a solid color, so if they scroll down, it won't show the footer, then the white under the footer.</p> <p>Here is the style I have for the footer.</p> <pre><code>.footer{ background:#055830 url('/images/footer_tile.gif') repeat-x top left; color:#fff; font-size:12px; height: 70px; margin-top: 10px; font-family: Arial, Verdana, sans-serif; width:100%; } </code></pre> <p><img src="https://i.stack.imgur.com/pUzIQ.jpg" alt="alt text"></p> <p>I want the footer to look like this: <img src="https://i.stack.imgur.com/s96Ft.jpg" alt="alt text"></p>
<p>Please clarify - do you want solid green at the bottom? If so, just set a green background for body...</p> <pre><code>body { background-color:#060; } </code></pre> <p>That should give you the result in your second screenshot. Change the color to match the bottom of your gradient image.</p> <p>If you want the foot pegged to the bottom, use the absolute positioning mentioned, and set the background to match the top of the gradient image.</p>
<p>You can use </p> <pre><code>position:absolute; bottom: 0; </code></pre> <p>to put the footer at the bottom always...</p>
25,728
<p>Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.</p> <p>Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem.</p> <p>Solution that I know are:</p> <p>a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed.</p> <p>b) Delete the whole project and re-check it out from svn.</p> <p>Does anyone know how I can get around this problem?</p> <p>Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes?</p> <p>Or perhaps there is a recursive modification date reset tool that can be used in this situation?</p>
<p>I would recommend using a virtual machine where you can mess with the clock to your heart's content and it won't affect your development machine. Two free ones are <a href="http://www.microsoft.com/Windows/products/winfamily/virtualpc/default.mspx" rel="nofollow noreferrer">Virtual PC</a> from Microsoft and <a href="http://www.virtualbox.org/" rel="nofollow noreferrer">VirtualBox</a> from Sun.</p>
<p>I don't use windows - but surely there is something like awk or grep that you can use to find the "future" timestamped files, and then "touch" them so they have the right time - even a perl script.</p>
8,608
<p>I need to import a large CSV file into an SQL server. I'm using this :</p> <pre><code>BULK INSERT CSVTest FROM 'c:\csvfile.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO </code></pre> <p>problem is all my fields are surrounded by quotes (" ") so a row actually looks like :</p> <pre><code>"1","","2","","sometimes with comma , inside", "" </code></pre> <p>Can I somehow bulk import them and tell SQL to use the quotes as field delimiters?</p> <p><strong>Edit</strong>: The problem with using '","' as delimiter, as in the examples suggested is that : What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime.</p> <p>From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.</p>
<p>Try <code>FIELDTERMINATOR='","'</code></p> <p>Here is a great link to help with the first and last quote...look how he used the substring the SP</p> <p><a href="http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file" rel="noreferrer">http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file</a></p>
<p>Yup, K Richard is right: <code>FIELDTERMINATOR = '","'</code></p> <p>See <a href="http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file" rel="nofollow noreferrer">http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file</a> for more info.</p>
12,206
<p>OK, I have just been reading and trying for the last hour to import a CSV file from access into MySQL, but I can not get it to do it correctly, no matter what I try.</p> <p>My table is like so:</p> <pre><code>+-----------------+------------- | Field | Type +-----------------+------------- | ARTICLE_NO | varchar(20) | ARTICLE_NAME | varchar(100) | SUBTITLE | varchar(20) | CURRENT_BID | varchar(20) | START_PRICE | varchar(20) | BID_COUNT | varchar(20) | QUANT_TOTAL | varchar(20) | QUANT_SOLD | varchar(20) | STARTS | datetime | ENDS | datetime | ORIGIN_END | datetime | SELLER_ID | varchar(20) | BEST_BIDDER_ID | varchar(20) | FINISHED | varchar(20) | WATCH | varchar(20) | BUYITNOW_PRICE | varchar(20) | PIC_URL | varchar(20) | PRIVATE_AUCTION | varchar(20) | AUCTION_TYPE | varchar(20) | INSERT_DATE | datetime | UPDATE_DATE | datetime | CAT_1_ID | varchar(20) | CAT_2_ID | varchar(20) | ARTICLE_DESC | varchar(20) | DESC_TEXTONLY | varchar(20) | COUNTRYCODE | varchar(20) | LOCATION | varchar(20) | CONDITIONS | varchar(20) | REVISED | varchar(20) | PAYPAL_ACCEPT | tinyint(4) | PRE_TERMINATED | varchar(20) | SHIPPING_TO | varchar(20) | FEE_INSERTION | varchar(20) | FEE_FINAL | varchar(20) | FEE_LISTING | varchar(20) | PIC_XXL | tinyint(4) | PIC_DIASHOW | tinyint(4) | PIC_COUNT | varchar(20) | ITEM_SITE_ID | varchar(20) </code></pre> <p>Which should be fine, and my data is currently semicolon delimited, an example of a row from my csv file is thus:</p> <pre><code>"110268889894";"ORIGINAL 2008 ED HARDY GÜRTEL* MYSTERY LOVE * M *BLACK";"";0,00 €;0,00 €;0;1;0;8.7.2008 17:18:37;5.11.2008 16:23:37;6.10.2008 17:23:37;29;0;0;0;125,00 €;"";0;2;6.10.2008 16:21:51;6.10.2008 14:19:08;80578;0;;0;77;"";0;0;1;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77 "110293328957";"Orig. Ed Hardy Shirt - Tank Top - Gr. XS- OVP/NEU";"";25,05 €;0,00 €;7;1;0;27.9.2008 06:26:27;6.10.2008 18:26:21;6.10.2008 18:26:21;49;0;0;0;0,00 €;"";0;1;6.10.2008 16:21:56;6.10.2008 16:33:20;31058;0;;0;77;"";1;0;0;0;-1;0,00 €;0,00 €;0,00 €;0;0;0;77 </code></pre> <p>I am using a simple PHP page to output the table data, and it is completely wrong. The problem is not with the PHP page as a simple table with just text displays perfectly. I am wondering if I have selected incorrect field types or the columns do not match up, but I see no reason this would be the case. Could something be happening because the data is trying to be displayed as HTML?</p> <p>I have tried to keep this question as specific as possible, and am not asking for people to do it for me as others have suggested, but I honestly can not see where the problem is.</p> <p>edit: When trying to display the data through PHP, at the moment the page is completely black with some table cells having borders and others not, othertimes when trying different delimiters, the fields do not match the columns. The starts field has never displayed correctly.</p> <p>I am loading the file from a CSV file with this command: </p> <pre><code>LOAD DATA LOCAL INFILE 'C:/Dokumente und Einstellungen/hom/Desktop/tblAuction.txt' INTO TABLE Auctions FIELDS TERMINATED BY '\"' LINES TERMINATED BY '\n'; </code></pre> <p>It looks fine in the DB as far as I have been able to tell, apart from the starts field, which is not the main problem at the moment.</p> <p>edit2: I have serialized the result, and this is what was output to the screen:</p> <pre><code>i:0; </code></pre> <p>I have absolutely no idea what that means.</p> <p>edit3: I had tried updating the terminated by a delimiter, and after changing \" to ; the problem still remains of data not being put into the correct columns etc.., I don't understand what I have missed.</p>
<p>Your fields are terminated by ";" not "\"". Change</p> <pre><code> FIELDS TERMINATED BY '\"' </code></pre> <p>to</p> <pre><code> FIELDS TERMINATED BY ';' </code></pre> <p>You could add this as well:</p> <pre><code> OPTIONALLY ENCLOSED BY '"' </code></pre> <p>which I think is what you were trying to do with the TERMINATED BY clause.</p>
<p>it commonly happens that what you're using as the "FIELDS TERMINATED BY" string actually occurs inside one of the fields, check this by writing a little program to .split() each line in the file and count the fields. Hopefully, you control how the input file is generated and can use somehting extremely unlikely, like "~~~~~"</p> <p>Also, (not directly relevent, but you shd know) you still have to do "\N" to enter nulls in the db, and empty strings in input file can turn into zero's in numeric fields</p> <p><a href="http://bugs.mysql.com/bug.php?id=23212" rel="nofollow noreferrer">http://bugs.mysql.com/bug.php?id=23212</a></p>
33,219
<p>I want to connect to a USB Webcam in .NET, specifically using C#. Being new to .NET I don't know what kind of support there is in the standard libraries for doing so. I found one example on the web that copies bitmaps through the clipboard, but that seems very hacky (and probably slow). Is there a better way?</p>
<p>You will need to use <a href="https://learn.microsoft.com/en-gb/windows/win32/wia/-wia-startpage" rel="nofollow noreferrer">Windows Image Acquisition (WIA)</a> to integrate a webcam with your application. There are plenty examples of this readily available. Here is a <a href="https://learn.microsoft.com/en-gb/archive/blogs/markhsch/c-webcam-user-control-source" rel="nofollow noreferrer">C# Webcam User Control</a> with source.</p> <p>Here are some more articles and blog posts from people looking to solve the same problem you are:</p> <ul> <li><a href="https://web.archive.org/web/20100123131023/http://blogs.msdn.com:80/coding4fun/archive/2006/10/31/912546.aspx" rel="nofollow noreferrer">MSDN Coding4Fun: Look at me! Windows Image Acquisition</a></li> <li><a href="https://www.codeproject.com/Articles/2303/WIA-Scripting-and-NET" rel="nofollow noreferrer">CodeProject: WIA Scripting and .NET</a></li> <li><a href="https://www.codeproject.com/Articles/15219/WebCam-Fast-Image-Capture-Service-using-WIA" rel="nofollow noreferrer">CodeProject: WebCam Fast Image Capture Service using WIA</a></li> <li><a href="https://web.archive.org/web/20111216162211/http://clausn.dk/post/2006/02/Webcam-control-from-C-and-WIA.aspx" rel="nofollow noreferrer">clausn.dk: Webcam control from C# and WIA</a></li> </ul>
<p>On my computer, WIA was painstakingly sloooow... so i decided to give the <a href="http://windowssdk.msdn.microsoft.com/en-us/library/ms713477(VS.80).aspx" rel="nofollow noreferrer">Windows Multimedia Video Capture</a> a try.</p> <p>You can find a demo <a href="http://www.timvw.be/wp-content/code/csharp/testavicap32.zip" rel="nofollow noreferrer">here</a>.</p>
13,851
<pre><code>function Submit_click() { if (!bValidateFields()) return; } function bValidateFields() { /// &lt;summary&gt;Validation rules&lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; ... } </code></pre> <p>So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to <a href="http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx" rel="nofollow noreferrer">this</a> it should. Should it?</p>
<p>I recall an issue where having turned off the Navigation Bar in VS stopped a lot of the JS intellisense from working properly. If you have it turned off, try turning the Navigation Bar on again and see if it helps.</p> <p>Edit: You may also have to do Ctrl+Shift+J to force the IDE to update the intellisense.</p> <p>Edit2: As @blub said, if there are any issues with the javascript, the intellisense can break. Visual Studio actually evaluates the javascript to create the intellisense, so if there are syntax errors it can fail and not build the intellisense completely, or at all.</p>
<p>Did you try adding the <code>/// &lt;reference&gt;</code> comment at the top of the external library? I've run into this in the past and it resolved my issue.</p>
26,981