instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>What is the meaning, and where is the Ruby documentation for the syntax of: </p> <pre><code>Array(phrases) </code></pre> <p>which I found browsing the Rails source here:</p> <pre><code># File actionpack/lib/action_view/helpers/text_helper.rb, line 109 ... 119: match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') </code></pre> <p>I thought that Array.new would normally be used to create an array, so something different must be going on here. BTW from the context around this code, the <code>phrases</code> variable can be either a string or an array of strings.</p>
<p>It's most likely the <code>Kernel#Array</code> method, see <a href="http://www.ruby-doc.org/core/classes/Kernel.html#M005989" rel="noreferrer">here</a>. It's slightly different than <code>Array.new</code>; it's more of a cast into an array. (It tries <code>to_ary</code> and <code>to_a</code>.)</p>
<p>Array(x) appears to act exactly the same as x.to_a.</p> <p>@Brian is right - it's a method of Kernel. Pickaxe says:</p> <p><strong>Array( arg ) -> anArray</strong> </p> <p>Returns arg .to_a. </p> <pre><code>Array(1..5) » [1, 2, 3, 4, 5] </code></pre>
46,688
<p>I did not find the TryParse method for the Guid. I’m wondering how others handle converting a guid in string format into a guid type.</p> <pre><code>Guid Id; try { Id = new Guid(Request.QueryString["id"]); } catch { Id = Guid.Empty; } </code></pre>
<pre><code>new Guid(string) </code></pre> <p>You could also look at using a <code>TypeConverter</code>.</p>
<p>If all you want is some very basic error checking, you could just check the length of the string.</p> <pre><code> string guidStr = ""; if( guidStr.Length == Guid.Empty.ToString().Length ) Guid g = new Guid( guidStr ); </code></pre>
45,622
<p>Is there a basic php method that accepts a URL and retrieves the date last modified from the header? </p> <p>It would seem like something php can do, but I'm not sure which object to check.</p> <p>Thanks</p>
<p>Give this a go.. using <a href="http://www.php.net/curl" rel="nofollow noreferrer">cURL</a>.</p> <pre><code>$c = curl_init('http://...'); curl_setopt($c, CURLOPT_HEADER, 1); // Include the header curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // Return the result instead of printing it $result = curl_exec($c); if (curl_errno($c)) die(curl_error($c)); // $result now contains the response, including the headers if (preg_match('/Last-Modified:(.*?)/i', $result, $matches)) var_dump($matches[1]); </code></pre>
<p>Thanks... I tried modifying your version a bit and this seems to work for me:</p> <pre><code>$c = curl_init('http://...'); curl_setopt($c, CURLOPT_HEADER, 1); // Include the header curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_FILETIME, 1); curl_exec($c); $result = curl_getinfo($c); if (curl_errno($c)) die(curl_error($c)); echo date('G:i M jS \'y',(int)$result['filetime']); </code></pre>
39,908
<p>I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are <a href="http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/" rel="noreferrer">here</a> if you're interested in helping out). </p> <p>My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??</p> <p>What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?</p> <p>Thank!</p>
<p>Here's how my school did it:</p> <pre><code>base: algebra trigonometry analytic geometry track 1 track 2 track 3 calc 1 linear algebra statistics calc 2 discrete math 1 calc 3 (multivariable) discrete math 2 differential equations </code></pre> <p>The base courses were a prerequisite for everything, the tracks were independent and taken in order.</p> <p>So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these:</p> <pre><code>algebra, discrete algebra, linear algebra, discrete (if you want to cover matrices first) </code></pre> <p>HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!</p>
<p>Usually, an overview of each field is a good thing to have when looking at any topic, but it's rare to have a genuine dependence the way we'd think of it. Algebra is always needed. I can't think of a time I've needed any trigonometry. (except to expand it with new things from calculus) I'm even quite sure people wouldn't agree on what a dependency graph would look like, or even in which field each topic belongs.</p> <p>I think the right way to approach it is to just collect a wide range of topics from all of branches and read them in whatever order you feel like, recording dependencies between topics as you go. (respecting them, or not, as you please.) This should have the far more important property of <strong>keeping the student interested</strong>.</p> <p>It's also my experience that if something just has you stumped, just mark it and set it aside for later.</p> <p>As for my school, well, it was similar to Harrison's:</p> <ul> <li>cominatorics,</li> <li>linear algebra,</li> <li>calculus,</li> <li>numerical analysis (error analysis in particular.)</li> <li>logic,</li> <li>statistics, (with operations research / queueing therory.)</li> </ul>
4,192
<p>does anybody know any resources that I can refer to?</p>
<p>I believe you are referring to the <a href="http://docs.jquery.com/Effects/fadeOut#speedcallback" rel="nofollow noreferrer">JQuery FadeOut effect</a> (since <a href="http://ttp://blog.stackoverflow.com/2008/09/what-was-stack-overflow-built-with/" rel="nofollow noreferrer">Stackoverflow uses JQuery</a>)</p>
<p>You can easlily find this and lots of other effects in various javascript libraries. I personally like <a href="http://ui.jquery.com/repository/real-world/effects/" rel="nofollow noreferrer">JQuery</a></p>
38,771
<p>I want to be able to specify the file name stem for the log file in a Specman test. I need to hard-code the main *.elog filename so that I don't get variance between tests and confuse the post-processing scripts. Is there a constraint or command line I can pass into Specman?</p>
<p>You can control the *.elog filename with switch -log.</p>
<p>You can control the *.elog filename with switch -log.</p>
19,788
<p>Where can I find a list of all types of bsd style socket errors?</p>
<p>In the documentation? For instance, for connect(), see:</p> <pre><code>% man connect ... ECONNREFUSED No-one listening on the remote address. EISCONN The socket is already connected. ENETUNREACH Network is unreachable. </code></pre>
<p>Of you want to know all possible errno's or some comments on them you could take a look at the header files, on a Linux system there are located in </p> <ul> <li>/usr/include/asm-generic/errno-base.h</li> </ul> <pre> #ifndef _ASM_GENERIC_ERRNO_BASE_H #define _ASM_GENERIC_ERRNO_BASE_H #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ ... </pre> <ul> <li>/usr/include/asm-generic/errno.h</li> </ul> <pre> #ifndef _ASM_GENERIC_ERRNO_H #define _ASM_GENERIC_ERRNO_H #include #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ ... </pre> <p>If you want to know what errno a call, e.g. socket() or connect() can return, when install the development manpages and try man socket or man connect </p>
20,754
<p>This seems to be a common problem but I cannot find a solution.</p> <p>I type in my username and password which are in a login control I have created. I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event.</p> <p>If I press the submit button then everything works fine.</p>
<p>using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML.</p> <p>so you do as Jon said above:</p> <pre><code>&lt;form runat="server" DefaultButton="SubmitButton"&gt; </code></pre> <p>But ensure you use the Button name that will be rendered. You can achieve this my making the Button public in your control, or a method that will return it's ClientId.</p> <p>Let's say your button is called btnSubmit, and your implementation of your control ucLogin.</p> <p>Give your form an id</p> <pre><code>&lt;form runat="server" id="form1"&gt; </code></pre> <p>Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id.</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { form1.DefaultButton = ucLogin.btnSubmit.ClientID; } </code></pre>
<p>Pressing ENTER on a text input executes <strong>Form.onsubmit</strong>, not <strong>Button.onclick</strong>.</p> <p>I suppose this was inspired by the fact that you can have a form without an actual submit button (depending solely on the use of ENTER).</p>
19,528
<p>What is the best solution for converting WAV files to WMA (and vice versa) in C#? I have actually implemented this once already using the Windows Media Encoder SDK, but having to distribute Windows Media Encoder with my application is cumbersome to say the least. The Windows Media Format SDK has large sections of the API marked as deprecated. It looks like there might be some DirectX Media Objects (DMOs) I could use from the Windows SDK, but there would be an awful lot of interop to write.</p> <p>I am wondering if there perhaps is a good managed wrapper for an unmanaged library that can perform the conversions. It would need a license that allows it to be distributed as part of a closed source commercial application.</p>
<p>I haven't tried it personally (so not sure if it's the 'best' solution), but <a href="http://www.codeproject.com/KB/audio-video/WmaCompressor.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/audio-video/WmaCompressor.aspx</a> looks like it should meet your requirements...</p>
<p>You might look at <a href="http://www.mitov.com" rel="nofollow noreferrer">www.mitov.com</a>. There are some libraries there that may help. You'll need to buy a copy to ship in a commercial product, I believe, but I think it's a reasonable price.</p>
8,984
<p>Unit testing with C/C++: What do you teach people who either did not do unit testing before or come from Java/Junit?</p> <p>What is the single most important lesson / thing to remember/ practice from your point of view that saves a lot of time or stress (especially regarding C/C++)?</p>
<ol> <li>Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests).</li> <li>Before fixing a bug, write a unit test to expose it (it should fail). Then fix the bug and rejoice as the test turns green.</li> <li>It's OK to sacrifice a bit of "beauty" of a class for easier testing (like provide public methods that should not really be public, but help your testing/mocking).</li> </ol>
<p>Single most important lesson: A test is better than no test.</p>
27,303
<p>What is the fastest, easiest tool or method to convert text files between character sets?</p> <p>Specifically, I need to convert from UTF-8 to ISO-8859-15 and vice versa.</p> <p>Everything goes: one-liners in your favorite scripting language, command-line tools or other utilities for OS, web sites, etc.</p> <h2>Best solutions so far:</h2> <p>On Linux/UNIX/OS X/cygwin:</p> <ul> <li><p>Gnu <a href="http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html" rel="noreferrer">iconv</a> suggested by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64889">Troels Arvin</a> is best used <strong>as a filter</strong>. It seems to be universally available. Example:</p> <pre><code> $ iconv -f UTF-8 -t ISO-8859-15 in.txt &gt; out.txt </code></pre> <p>As pointed out by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64991">Ben</a>, there is an <a href="http://www.iconv.com/iconv.htm" rel="noreferrer">online converter using iconv</a>.</p> </li> <li><p><a href="https://github.com/rrthomas/recode/" rel="noreferrer">recode</a> (<a href="http://www.informatik.uni-hamburg.de/RZ/software/gnu/utilities/recode_toc.html" rel="noreferrer">manual</a>) suggested by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64888">Cheekysoft</a> will convert <strong>one or several files in-place</strong>. Example:</p> <pre><code> $ recode UTF8..ISO-8859-15 in.txt </code></pre> <p>This one uses shorter aliases:</p> <pre><code> $ recode utf8..l9 in.txt </code></pre> <p>Recode also supports <em>surfaces</em> which can be used to convert between different line ending types and encodings:</p> <p>Convert newlines from LF (Unix) to CR-LF (DOS):</p> <pre><code> $ recode ../CR-LF in.txt </code></pre> <p>Base64 encode file:</p> <pre><code> $ recode ../Base64 in.txt </code></pre> <p>You can also combine them.</p> <p>Convert a Base64 encoded UTF8 file with Unix line endings to Base64 encoded Latin 1 file with Dos line endings:</p> <pre><code> $ recode utf8/Base64..l1/CR-LF/Base64 file.txt </code></pre> </li> </ul> <p>On Windows with <a href="https://learn.microsoft.com/en-us/powershell/" rel="noreferrer">Powershell</a> (<a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937">Jay Bazuzi</a>):</p> <ul> <li><code>PS C:\&gt; gc -en utf8 in.txt | Out-File -en ascii out.txt</code></li> </ul> <p>(No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.)</p> <h2>Edit</h2> <p>Do you mean iso-8859-1 support? Using &quot;String&quot; does this e.g. for vice versa</p> <pre><code>gc -en string in.txt | Out-File -en utf8 out.txt </code></pre> <p>Note: The possible enumeration values are &quot;Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii&quot;.</p> <ul> <li>CsCvt - <a href="http://www.cscvt.de" rel="noreferrer">Kalytta's Character Set Converter</a> is another great command line based conversion tool for Windows.</li> </ul>
<p><a href="http://linux.die.net/man/1/iconv" rel="noreferrer">Stand-alone utility</a> approach</p> <pre class="lang-none prettyprint-override"><code>iconv -f ISO-8859-1 -t UTF-8 in.txt &gt; out.txt </code></pre> <pre class="lang-none prettyprint-override"><code>-f ENCODING the encoding of the input -t ENCODING the encoding of the output </code></pre> <p>You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8.</p>
<p>As described on <a href="https://stackoverflow.com/questions/132318/how-do-i-correct-the-character-encoding-of-a-file">How do I correct the character encoding of a file?</a> <a href="http://www.synalysis.net" rel="nofollow noreferrer">Synalyze It!</a> lets you easily convert on OS X between all encodings supported by the <a href="http://icu-project.org" rel="nofollow noreferrer">ICU library</a>.</p> <p>Additionally you can display some bytes of a file translated to Unicode from all the encodings to see quickly which is the right one for your file.</p>
9,052
<p>I have been developing a compact framework app on an emulator, and some of the forms use DateTimePickers. These work fine in the emulator, but when running on the hardware they cause the form to close when a date is selected. No exception is thrown...the form just closes unexpectedly. Has anyone experienced this or know how to fix it?</p>
<p>On both your device and the emulator, go to:</p> <p>Start | Settings [System] | Regional Settings [Date]</p> <p>and see if both have the same settings for Short date, Date Separator and Long date. This is just a guess, but it's one possible difference between the emulator and the device that is at least related to date pickers. If they're different, try setting the device the same as the emulator and see if you still have the problem.</p>
<p>On both your device and the emulator, go to:</p> <p>Start | Settings [System] | Regional Settings [Date]</p> <p>and see if both have the same settings for Short date, Date Separator and Long date. This is just a guess, but it's one possible difference between the emulator and the device that is at least related to date pickers. If they're different, try setting the device the same as the emulator and see if you still have the problem.</p>
43,537
<p>Is it possible to make a POST request from Ruby with open-uri?</p>
<p>Unfortunately <code>open-uri</code> only supports the <code>GET</code> verb.</p> <p>You can either drop down a level and use <code>net/http</code>, or use <code>rest-open-uri</code>, which was designed to support <code>POST</code> and other verbs. You can do <code>gem install rest-open-uri</code> to install it.</p>
<p>As simple as it gets:</p> <pre><code>require 'open-uri' require 'net/http' response = Net::HTTP.post_form(URI.parse("https://httpbin.org/post"), { a: 1 }) puts response.code puts response.message puts response.body </code></pre> <p>I recommend using <code>response.methods - Object.methods</code> to see all the available methods, e.g. <code>message</code>, <code>header,</code></p> <p><strong>Bonus</strong>: POST / DELETE requests:</p> <pre><code>puts Net::HTTP.new("httpbin.org").post("/post", "a=1").body puts Net::HTTP.new("httpbin.org").delete("/delete").body </code></pre>
30,033
<p>I have a really bent heatbed PCB, the middle is elevated about 3 mm with respect to all edges.</p> <p>I have found this thread <a href="http://midibox.org/forums/topic/17599-warped-pcbs/" rel="noreferrer">Warped PCBs</a>, where a heating method is applied by baking a PCB in the oven, as described here: <a href="http://www.circuitrework.com/guides/3-2.shtml" rel="noreferrer">3.2 Bow and Twist Repair</a>.</p> <p>Can this help straightening out a Prusa heatbed PCB? If so, can I apply the heat by the heatbed itself, or do I need to utilize an oven? Will the pressure from the strongly clamped glass plate be enough or will the glass break at these temperatures (given that the heatbed can reach them).</p>
<p>Baking PCB in an oven is not a good idea, I would say. I know PCBs are resistive to the heat (especially heatbeds) but, still, it sounds odd. But the real question is how baking would help. Let's leave it.</p> <p>If your heatbed is such bent you can do few things depending on your situation/environment.</p> <p>You can:</p> <ol> <li>Add two glass plates (at the bottom and at the top) and clip them all together;</li> <li>Support your HB with flat aluminium or even wood;</li> <li>Add an aluminium frame, or;</li> <li>If you use glass plate, clip the HB to the glass using stronger (wider) clips.</li> </ol> <p>Ad#1 the thermistor can even stay sandwiched between the PCB and the bottom glass plate.</p> <p>Ad#2 If your HB is bent up in the middle, you can use the middle thermistor hole. Drill it a bit with fi8mm drill (but not too much, I would say halfway through) and use a cone head screw to screw it flat on to the aluminium/wood support. Of course you will have to install a thermistor into the new place.</p> <p>The simplest, and less destructive, solution is #1 and I would recommend that.</p>
<p>Easiest way would be to place a glass sheet on top of the bed and run a calibration... Although, that way you may lose a few millimeters of print height.</p>
255
<p>I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.</p> <p>Is there some way to do an XSS attack even if HTML Encode is used?</p>
<p>No.</p> <p>Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.</p> <p>For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will <strong>not stop</strong> injected script from executing.</p> <p>Next, consider the following pseudocode:</p> <pre><code>&lt;input value=&lt;%= HtmlEncode(somevar) %&gt; id=textbox&gt; </code></pre> <p>Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to</p> <pre><code>a onclick=alert(document.cookie) </code></pre> <p>the resulting output is</p> <pre><code>&lt;input value=a onclick=alert(document.cookie) id=textbox&gt; </code></pre> <p>which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.</p> <p>There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).</p> <p>Also don't forget about UTF-7 type attacks - where the attack looks like </p> <pre><code>+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4- </code></pre> <p>Nothing much to encode there...</p> <p>The solution, of course (in addition to proper and restrictive white-list input validation), is to perform <strong>context-sensitive</strong> encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.</p> <p>If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.</p> <p>Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.</p> <p>Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...</p> <p>Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: <a href="http://ha.ckers.org/xss.html" rel="noreferrer">http://ha.ckers.org/xss.html</a></p>
<p>I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser as code) in to entity references which cannot be parsed by the browser and thus, cannot be executed.</p> <pre><code>&amp;lt;script/&amp;gt; </code></pre> <p>There is no way that the above can be executed by the browser.</p> <p>**Unless their is a bug in the browser ofcourse.*</p>
7,727
<p>MS CRM Dynamics 4.0 incorporates the MS WF engine. The built in designer allows the creation of sequential workflows whos activities have native access to CRM entities.</p> <p>Is it possible to:</p> <ul> <li>Create a state machine workflow outside of CRM (i.e. in visual studio) and import it into CRM? </li> <li>Have this workflow access the CRM entities?</li> </ul>
<ul> <li>It is NOT possible to create a state machine workflow for use in MSCRM.</li> <li>It is also not supported to create any workflow outside of MSCRM and import it.</li> <li>As a work around you could write either all the logic you need into a custom workflow activity and import that into MSCRM and have it called from a normal workflow.</li> <li>The other option is build a seperate application which runs a state machine workflow and interacts with MSCRM via the web services. You could (would need to?) combine this with a custom workflow activity to kick off processes.</li> </ul>
<p>I don't know the answer to your specific question, but hopefully this information will point you in the right direction.</p> <p>The "native" format for WF workflows is ".xoml" files. These are basically identical to XAML files, and both are nothing more than generic persistence formats for a .NET object tree. If you can access the saved data that is output by the Dynamics designer, it should be in the same format. If it is, you should be able to open it from the Visual Studio designer.</p> <p>The key here is that CRM undoubtedly defines its own set of custom activities that you'll need to be able to reference from within the alternate designer. With any luck, these will be in assemblies with obvious names and/or in the GAC.</p>
5,427
<p>In a previous SO question, it was mentioned that USB devices can be mounted using the following approach in Windows:</p> <p>MOUNTVOL C:\USB: \\?\Volume{ebc79032-5270-11d8-a724-806d6172696f}\</p> <p>My question is what is that String starting with \\?\Volume called, and what is the best way to retrieve that. I would rather not use .NET if possible since you can't really 'bundle' the .NET runtime without physically installing it on the machine as far as I know.</p> <p>I would also be interested in using JNA if that is possible.</p>
<p>You can't bundle the Java "...runtime without physically installing it on the machine..." either.</p> <p>Enumerating the device after it is mounting should be straightforward. Actually mounting the device should NOT be straightforward since Java (and .NET) are both designed to abstract away the hardware.</p> <p>I recommend that you pick a more appropriate tool for this. Either choose to simply invoke another process to run the mount command (knowing that it won't be portable), or choose a tool that does not abstract away the hardware, or at least less so (perhaps Python?).</p> <p>EDIT: Clarification on JVM install...</p> <p>Excellent point--a JVM installation can be much less invasive than a .NET installation since the latter MUST integrate with the OS while the former merely CAN integrate with the OS. So, yes, including a private JVM install is viable and perhaps desirable.</p> <p>NOTE: The question includes the mount command for the USB device, which tends to emphasize that aspect as a primary requirement.</p>
<p>What kind of USB device are you looking for? The bit you quote is only applicable to USB disk drives, not USB devices in general.</p>
49,597
<p>How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc?</p> <p>What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)?</p> <p>What is WCF <em>not</em> good for that you've seen people try to shoehorn it into?</p> <p>-Adam</p>
<p>Comparing with .asmx: WCF is the next generation of Microsoft's Web service development platform, which addresses many of the issues with older versions, specifically:</p> <ul> <li>better interoperation, so you can interoperate with Web services that aren't from Microsoft or that are published on the Internet</li> <li>much more flexible, so it's easier and faster for developers to get their jobs done</li> <li>easier to configure without changing code, reducing the cost of maintenance significantly</li> </ul> <p>It may be that they raise the question of how it relates to SOA, a "service-oriented architecture". WCF is the Microsoft solution for creating applications that participate in these distributed systems.</p>
<p>In a single sentence, I'd say that WCF is "software that lets you set up and manage communication between systems a lot more efficiently than in the past".</p> <p>I can see them bringing up BizTalk as a competitor, but of course you could say that WCF works with it and is in fact used as base technology for it in the more recent versions.</p> <p>I'm not sure if I can think of any inappropriate shoe-horning of WCF that I have seen, although there are plenty of legacy apps that will probably be "upgraded" to WCF that don't really need to be for any real business reason.</p>
7,281
<p>Summary: </p> <blockquote> <p><strong>Can I program a "thick client" game in C without reinventing wheels</strong>, or should I just bite the bullet and use some library or SDK? I'm a moderate C programmer and am not afraid to work with pointers, data structures, memory locations, etc. if it will give me the control I need to make a great "thick-client" game. However, I'm thinking of eschewing high-level languages &amp; frameworks for the sake of power and control, <em>not</em> ease of use.</p> </blockquote> <p>I'm interesting in tinkering with a 2D fighting/platforming game as a side project sometime. I'm primarily a Linux server-side programmer with experience in Python, Ruby and PHP. I know that there are excellent frameworks in some of these languages, like <a href="http://www.pygame.org/news.html" rel="nofollow noreferrer">PyGame</a>. I am also aware of the success people have had with stuff like Air and .NET... but I have some concerns:</p> <ul> <li><strong>Performance</strong>: Scripting languages are notoriously slow. If I'm making a real-time game, I want it to be as snappy as possible.</li> <li><strong>Huge binaries</strong>: Using frameworks like .NET or scripting languages like Ruby often result in big CLRs or libraries that you wouldn't otherwise need. The game I want to make will be small and simple--I don't want its CLR to be bigger than the game itself!</li> <li><strong>Extra stuff</strong>: Honestly, I just don't like the idea of inheriting some big game library's baggage if I can wrap my head around my own code better.</li> </ul> <p>I'm asking this question because I know I'm very susceptible to Not Invented Here Syndrome. I always want to program it myself, and I'm sure it wastes a lot of time. However, this works out for me remarkably often--for example, instead of using <a href="http://www.rubyonrails.org/" rel="nofollow noreferrer">Rails</a> (a very big web project framework with an ORM and GUI toolkit baked in), I used an array of smaller Ruby tools like <a href="http://rack.rubyforge.org/" rel="nofollow noreferrer">rack</a> and <a href="http://sequel.rubyforge.org/" rel="nofollow noreferrer">sequel</a> that fit together beautifully.</p> <p>So, I turn to you, SO experts. Am I being naive? Here's how I see it:</p> <ul> <li><strong>Use C</strong> <ul> <li><strong>Cons</strong> <ul> <li>Will probably make me hate programming</li> <li>High risk of reinventing wheels</li> <li>High risk of it taking so long that I lose interest</li> </ul></li> <li><strong>Pros</strong> <ul> <li>Tried &amp; true - most A-list games are done in C (is this still true today?)</li> <li>High level of control over memory management, speed, asset management, etc., which I trust myself to learn to handle</li> <li>No cruft</li> </ul></li> </ul></li> <li><strong>Use framework or SDK</strong> <ul> <li><strong>Cons</strong> <ul> <li>Risk of oversized deliverable</li> <li>Dependent on original library authors for all facets of game development--what if there isn't a feature I want? I'll have to program it myself, which isn't bad, but partially defeats the purpose of using a high-level framework in the first place</li> <li>High risk of performance issues</li> </ul></li> <li><strong>Pros</strong> <ul> <li>MUCH faster development time</li> <li>Might be easier to maintain</li> <li>No time wasted reinventing common paradigms</li> </ul></li> </ul></li> </ul> <p>What else can I add to this list? Is it a pure judgment call, or can someone seal the deal for me? Book suggestions welcome.</p>
<p>I believe you are working under a fallacy. </p> <p>There are several frameworks out there specifically for game programming --- written by people with much experience with the complication of game design, almost certainly more tha you do.</p> <p>In other words, you have a "High risk of performance issues" if you DON'T use a framework.</p>
<p>I'm pretty sure most modern games are done in C++, not C. (Every gaming company I ever interviewed with asked C++ questions.)<br> Why not use C++ and existing libraries for physics + collisions, sound, graphics engine etc. You still write the game, but the mundane stuff is taken care of.</p>
29,104
<p>Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported.</p> <p>The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.</p>
<p>I figured it out. It goes something like this:</p> <pre><code>&lt;form method="post" action="&lt;%= Html.AttributeEncode(Url.Action("CastUpVote")) %&gt;"&gt; &lt;input type="submit" value="&lt;%=ViewData.Model.UpVotes%&gt; up votes" /&gt; &lt;/form&gt; </code></pre>
<p><code>&lt;asp:Button&gt;</code> is the ASP.NET equivalent to the HTML.Button. It will by default generate an <code>&lt;input type="button"&gt;</code>. (This is the System.Web.UI.WebControls.Button class)</p>
8,380
<p>Let’s say I have this markup:</p> <pre><code>&lt;div id="content"&gt; &lt;div id="firstP"&gt;&lt;p&gt;First paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="secondP"&gt;&lt;p&gt;Second paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="thirdP"&gt;&lt;p&gt;Third paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="fourthP"&gt;&lt;p&gt;Fourth paragraph&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to add a new <code>&lt;div&gt;</code> with jQuery and focus on this new element. <code>.focus</code> does not do anything.</p> <pre><code>function addParagraph() { var html = "&lt;div id=\"newP\"&gt;&lt;p&gt;New paragraph&lt;/p&gt;&lt;/div&gt;"; $("#content").append(html); $("#newP").focus(); } </code></pre> <p>Any idea why?</p>
<p>I think the main answer is incorrect. DIV and P tags can receive focus providing you specify a tabindex property for them. i.e. </p> <pre><code>&lt;div class="someclass" tabindex="100"&gt; </code></pre> <p>Once the tabindex is specified you can either tab to these elements or shift focus with <em>.focus()</em> .</p> <p>Using a scrollTo plugin seems like a bit of an overkill here.</p>
<p>Only form elements and such can attain focus. If you want the browser to scroll down to that particular paragraph, there is no "default" way of doing so with jQuery, but there is a plugin for it at <a href="http://flesler.blogspot.com/2007/10/jqueryscrollto.html" rel="nofollow noreferrer">jQuery.ScrollTo</a> and a blog explaining how to do it manually at <a href="http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12" rel="nofollow noreferrer">Animated scroll with jQuery</a></p>
43,372
<p><a href="http://en.wikipedia.org/wiki/Tf-idf" rel="noreferrer">TF-IDF (term frequency - inverse document frequency)</a> is a staple of information retrieval. It's not a proper model though, and it seems to break down when new terms are introduced into the corpus. How do people handle it when queries or new documents have new terms, especially if they are high frequency. Under traditional cosine matching, those would have no impact on the total match. </p>
<p>Er, nope, doesn't break down.</p> <p>Say I have two documents, A "weasel goat" and B "cheese gopher". If we actually represented these as vectors, they might look something like:</p> <p>A [1,1,0,0]<br/> B [0,0,1,1]</p> <p>and if we've allocated these vectors in an index file, yeah, we've got a problem when it comes time to add a new term. But the trick of it is, <em>that vector never exists</em>. The key is the <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="nofollow noreferrer">inverted index</a>.</p> <p>As far as new terms not affecting a cosine match, that might be true depending on what you mean. If I search my corpus of (A,B) with the query "marmoset kungfu", neither marmoset nor kungfu exist in the corpus. So the vector representing my query will be orthogonal to all the documents in the collection, and get a bad cosine similarity score. But considering none of the terms match, that seems pretty reasonable.</p>
<p>When you talk about "break down" I think you mean that the new terms have no impact on the similarity measure, because they do not have any representation in the vector space defined by the original vocabulary.</p> <p>One approach to handle this smoothing problem would be to consider fixing the vocabulary to a smaller vocabulary and treat all words rarer than a certain threshold as belonging to the special <code>_UNKNOWN_</code> word.</p> <p>However, I don't think your definition of "break down" is very clear; could you clarify what you mean there? If you could clear that up, perhaps we could discuss ways to work around those problems.</p>
27,527
<p>My model layers are printing much as I expect but the parts when removed from the plate are very soft and flexible and fail to harden any further in sunlight or UV lamplight. A tall or slender part will bend and distort under its own weight while printing. I am using LCD-T resin, I have increased time and reduced thicknesses and am now using 0.04&nbsp;mm layers at 20&nbsp;s and 255 brightness with no improvement. Can anyone suggest what I need to change?</p>
<p>I could finally solve the issue. Calling <code>openscad</code> from command line with parameters does NOT work with the AppImage I used. It works fine with a "standard" installation, though.</p> <p>Thanks for your support.</p>
<p>You can specify variable values from command line using:</p> <pre> openscad ...\ ... \ [ -D var=val [..] ] \ ... \ ... \ filename </pre> <p>See the <a href="https://en.m.wikibooks.org/wiki/OpenSCAD_User_Manual/Using_OpenSCAD_in_a_command_line_environment" rel="nofollow noreferrer">OpenSCAD Manual</a>.</p>
1,228
<p>How many people actually write an SDD document before writing a single line of code?</p> <p>How do you handle large CSCI's? </p> <p>What standard do you use for SDD content?</p> <p>What tailoring have you done?</p>
<p>I certainly have. Historically and on recent projects.<br> Years ago I worked in organisations where templates were everything. Then I worked other places where the templates were looser or non-existent or didn't fit the projects I was working on.<br> Now the content of the software design is pretty much governed by what I need to describe to get the idea across to the audience.<br> "before writing a single line of code" there wouldn't be a a lot of detail. The documents I produce before I start coding are meant to get the idea of what we need to build across to the affected teams and senior management so they introduce high level architecture, functionality, technologies, risks and scope. Those last two are really important. The rest is to show other teams where you need to interface with them and to leave managers with a lingering notion that cool stuff is happening.</p>
<p>Most big software companies have their own practices. For example Motorola has detailed documentation for every aspect of software development process. There are standard templates for each type of documents. Having strict standards allows effectively maintain huge number of documents and integrate it with different tools. Each document obtains tracking number from special document-tracking system. They even have system (last time I seen it was in stage of early development) for automatically requirements tracking - you can say which line of code relate to given requirement\design guideline.</p>
11,733
<p>I know there has to be an obvious solution to this problem and I am missing it, so I would much appreciate someone enlightening me so I don't spin my wheels...</p> <p>I am writing an ASP.Net application that will interact with a service API (Evernote specifically). Evernote requires OAuth for security and before I can actually interact with the objects I need to obtain a token.</p> <p>The workflow goes like this (explaining it to myself as much as anyone else!):</p> <ol> <li>Build a url with my development api key and secret key and some other OAuth stuff, send it to Evernote to request an access token.</li> <li>Send the url as a request to Evernote and pull the new access token out of the response</li> <li>Build another url with the access token to request an authentication token for the user. This url goes to a page the user must interact with to login (if they haven't already) and then authorize my application to access their account. The last param of the url I build is a callback url which will be called from Evernote's servers.</li> <li>If all goes well, Evernote will request the callback url and include the new authentication token as a param. </li> <li>Once my server receives the callback with the embedded token I can use it so that my app can interact with the users' notes on subsequent requests.</li> </ol> <p>The problem is that I'm writing this app on a local box, not an ISP under a public domain. So my callback is to the localhost server. Of course, localhost is relative, so Evernote can't resolve my callback... I can't ever receive an authentication token and debug at the same time. </p> <p>There has to be a way around this problem because this authentication model is not unique to Evernote (by a longshot... Flickr uses it as do a lot of other services). So can someone tell me how to set things up so I can get the authentication token and still be able to debug on my local box?</p> <p>Help is much appreciated!</p>
<p>OAuth is quite tough to implement. It may not be the answer you're looking for, but this is how I managed to get the job done:</p> <ol> <li>Write some code on my local dev machine.</li> <li>Run a bat file (or alternatively hook a post-build event in VS) that executes a msbuild deploy script and deploys the application to a test server. </li> <li>Run the application on the test server. After obtaining the request token and requesting for authorization it redirects to the Evernote website.</li> <li>After successful authorization the Evernote website redirects back to my test server and the authorized request token is exchanged for an access token. </li> <li>Instead of debugging (I don't have VS on the test server) I examine the logs of the application (the logging I used was as simple as writing to a text file).</li> <li>Rinse and repeat</li> </ol> <p>For the purposes of testing I registered a temporary public subdomain (e.g. testing.oauth.mydomain.com) so that Evernote will be able redirect to that url. </p>
<p>According to this (<a href="https://stackoverflow.com/questions/670398/how-do-i-develop-against-oauth-locally">How do I develop against OAuth locally?</a>) the callback is issued by the browser, so it should be able to hit localhost.</p>
45,133
<p>What is the coolest <strong>somewhat practical</strong> metaprogramming hack you've done or seen done in the D programming language? Somewhat practical means excluding, for example, the compile-time raytracer.</p>
<p>In terms of the outright coolest, I'd have to say Kirk McDonald's <a href="http://pyd.dsource.org/" rel="noreferrer" title="PyD">PyD</a> (and other similar bindings) as these have do to a huge amount of work in detecting and handling lots of different types, as well as complex code generation.</p> <p>That said, PyD only wins because <a href="http://www.digitalmars.com/d/archives/digitalmars/D/BLADE_0.2Alpha_Vector_operations_with_mixins_expression_templates_51617.html" rel="noreferrer">BLADE</a> technically uses CTFE, not templates.</p> <p>On a more personal note, D templates have gotten extensive use in a research project of mine. It's a simulation framework where modules can define their own private data types. Exposing a new user type to the framework requires a single line of code which creates an XML parser for the type as well as associated network serialisation/deserialisation code.</p>
<p>I wrote a memoize() function whose header is this (the code is a bit long for pasting here):</p> <p>auto memoize(TFunc)(TFunc func);</p> <p>What it does is, you give it a function's address, and it returns a strongly-typed delegate (same signature and return type as the original function) that caches the return values of the original function, so that calling it twice with the same parameter only calls the underlying function once. For instance, here is a memoized, "recursive" definition of the Fibonacci sequence that executes in linear, rather than exponential, time:</p> <p>uint fib(uint n) { return n > 0 ? n > 1 ? memoize(&amp;fib)(n - 1) + memoize(&amp;fib)(n - 2) : 1 : 0; }</p> <p>You can call it normally, as in: fib(1000);</p> <hr> <p>Edit: The previous code whose link I posted was rather hideous; <a href="http://gist.github.com/741782#file_memoize.d" rel="nofollow">this version is much more elegant</a>.</p>
30,464
<p>I know this is a broad question, but I've inherited several poor performers and need to optimize them badly. I was wondering what are the most common steps involved to optimize. So, what steps do some of you guys take when faced with the same situation?</p> <blockquote> <p>Related Question:<br> <a href="https://stackoverflow.com/questions/39331/what-generic-techniques-can-be-applied-to-optimize-sql-queries">What generic techniques can be applied to optimize SQL queries?</a></p> </blockquote>
<ol> <li>Look at the execution plan in query analyzer</li> <li>See what step costs the most</li> <li>Optimize the step!</li> <li>Return to step 1 [thx to <strong>Vinko</strong>]</li> </ol>
<p>Look at the indexes on the tables that make the query. An indexes may be needed on particular fields that participate in the where clause. Also look at the fields used in the joins in the query (if joins exist). If indexes already exist, look at the type of index. </p> <p>Failing that (because there are negatives to using locking hints) Look at locking hints and explicitly naming the index to use in the join. Using NOLOCKS is more obvious if you're getting a lot of deadlocked transactions.</p> <p>Do what roman and Andy S mentioned first though.</p>
8,612
<p>I'm trying to write a print layout editor in VB6 or VB.Net, and am looking for some reference articles to help get me started. </p> <p>The idea is that the editor will be used to define print "areas" for invoice or statement layouts, by allowing the user to draw the box for customer address, invoice number, lines, totals etc. The program will then figure out how to translate the dimensions and positions of the various boxes into print locations to store in the layout definition file, which is later used by an accounts system to print the various reports. Note that for various reasons (chiefly that the accounts system is non-Windows), placing text into Word or similar products and having them print the document is not an option. I can edit the document layout file by hand of course, but it's not very user-friendly.</p> <p>As you might imagine, searches for "form editor", "layout editor" and the like bring many hundreds of irrelevant results. The frustrating thing is that I have seen a very relevant article, but lost the bookmark.</p> <p>I am hoping someone has some pointers.</p> <hr> <p>Thanks, this sounds more complicated than I imagined. I <em>really</em> wish I could find the original article I lost, as it was pretty clear on how to go about this in vb.net.</p> <p>Because it's a layout for a printed form, I think that cuts down the complexity quite a lot - I only really need to store size and position of each print area, along with font, alignment and colour information, and possibly a filename for a graphic if a logo is required. The layout definition file format is entirely under my control.</p>
<p>First of all, you should have great knowledge of the language/APIs you're using, and in fact you <em>really</em> should specify if you're using Windows.Forms, WPF, GTK#, etc. Make sure you're <strong>very</strong> good on that.</p> <p>Then, you should think of a format for your form editor to store the forms. Usually, form editors use XML. If you also want to follow that trend, you <strong>REALLY</strong> should learn a good XML API for VB.</p> <p>Finally, plan your steps carefully:</p> <ol> <li>Do you want to use the custom text field controls provided by your API, or do you want to draw them manually(if so, then you'll need to learn a drawing API)?</li> <li>Make sure you understand the layout definition file format very well.</li> </ol> <p>Now, it's the time to start a proof-of-concept: create a simple editor that can load/save forms and add buttons to them. This will probably be hardest step to figure out. You may need to deal with events and several other stuff, but eventually it'll work(if not, then you may ask again). Finally, just add the features you need, such as layout definition file output, new controls, control moving/resizing, etc.</p> <p>If you need anything else(including more specific instructions), just ask.</p>
<p>i remember developing exactly this kind of printout form editor in vb6, some 10 years ago iirc. not sure i can still find the sources sadly: indeed i found this question because i need to write another and was hoping to find some code to start from instead of doing it from scratch once again. anyway, the way i done implemented it, more or less, was like this:</p> <ul> <li>one custom control for the page background, displaying a light grid, and reacting to mouse events (eg, show a menu on right click);</li> <li>each field was a windowless custom control, displaying a light grid too, one cell for each (fixed width) char. it also reacted to mouse events so that it could be moved around and resized; when i say windowless i mean "not having an hwnd", a kind of optimization that allowed placing lots of control instances without worrying about the impact on resources; if you are going to use .net you couldn't care less but if you use vb6 it does make a difference;</li> <li>one property grid like the one of vb6 showing properties of the selected field(s). in my case, i could set the style of the text (compressed, expanded, bold) and an expression used at runtime to retrieve the value to be printed;</li> <li>loading a layout file would size the page and instantiate a field control for every field in the file;</li> <li>saving wrote out the page properties (size, name, etc) then enumerate the collection of fields and wrote out their properties; </li> <li>i didn't use xml because the file format was already fixed, as it was used by the engine that did the actual printing; xml would only have made my life easier, no need to write a custom parser for the data file format.</li> <li>the requirement was handling dot matrix printers only but luckily i didn't cut any corners and i could easily adapt it to also handle more precise placement and sizes of the fields. what i mean simply is, i resisted the temptation to use row and column coordinates and used twips instead; it took a little more thinking about the math but no rocket science definitely.</li> </ul> <p>all in all it wasn't that hard to do and it came out very nice, it resembled a bit the form editor of "crystal reports".<br/> i remember spending some time to get the details right, e.g. grid snapping at different character widths, resizing the fields when changing text styles like condensed or expanded without them jumping around because of rounding errors, things like that. don't let this scare you, keep in mind you don't have to take care of everything from the start, just be a little careful not to block the possibility of doing it a later time.</p> <p>nowadays i wouldn't advice vb6 much, unless that's what you know best and need to produce a .exe not depending on the .net framework being installed on the target machines.<br/> if instead you choose to go with .net i think it would be a good chance to learn wpf if you don't know it already, it makes for some impressive graphics even more than windows.forms.</p>
41,543
<p>I need to display the log entries from a database. Of course the log data is huge, so I have to show the results on several pages, and that **without** getting **all** the log data at once, but as the user navigates through the pages.</p> <p>I know about <a href="http://displaytag.sourceforge.net/11/" rel="nofollow noreferrer">DisplayTag</a> and <a href="http://code.google.com/p/tabletags/" rel="nofollow noreferrer">TableTags</a>, but it seems to me that they both fetch all the data before applying pagination.</p> <p>Before I start developing my own JSP tag, does anyone know of a 3rd party solution for this problem?</p> <p>Thanks,<br>Marius</p>
<p>About DisplayTag: it does support <a href="http://displaytag.sourceforge.net/11/tut_externalSortAndPage.html" rel="nofollow noreferrer">Value List</a> design pattern.</p>
<p>Inside your JSP is not really the good place to solve the whole problem. In a typical layered approach, you separate the presentation (JSP here) from the data access (where you do your query).</p> <p>Your displaytag/jsp tag should pass to the data access layer which page it wants (eg I need the next 30 and am on page 5), and your data access layer then takes care of a paginated query.</p>
15,993
<p>From everything I've read, it seemed that adding paging to a ListView control should be dead simple, but it's not working for me. After adding the ListView and DataPager controls to the form and wiring them together, I'm getting very odd behavior. The DataPager correctly limits the ListView's page size, but clicking the paging buttons doesn't affect the ListView at all. The paging buttons seem to think they are doing they're job, as the last button is disabled when you go to the last page, etc., but the ListView never changes. Also, it takes two clicks on the DataPager to get it to do anything, i.e., clicking on Last once does nothing, but clicking it a second time causes the DataPager to react as if the last page is now selected.</p> <p>The only thing I can think of is that I'm binding the DataSource at runtime (to a LINQ object), not using a LinqDataSource control or anything. Has anyone seen this behavior? Am I doing something wrong? Here's the code I'm using:</p> <pre><code>&lt;asp:DataPager ID="HistoryDataPager" runat="server" PagedControlID="HistoryListView" PageSize="10"&gt; &lt;Fields&gt; &lt;asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true" /&gt; &lt;/Fields&gt; &lt;/asp:DataPager&gt; &lt;asp:ListView ID="HistoryListView" runat="server"&gt; ... &lt;/asp:ListView&gt; </code></pre> <p>In the code-behind:</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then HistoryListView.DataSource = From x in myContext.myTables ... DataBind() End If End Sub </code></pre>
<p>We need to databind list view again in OnPreRender event. </p> <pre><code>protected override void OnPreRender(EventArgs e) { ListView1.DataBind(); base.OnPreRender(e); } </code></pre> <p>--Update</p> <p>After working on a few list views with asp.net ajax, I saw a solution that makes more sense than the above one. You would normally data bind Listview on page load method or a button click event handler and when there is post back the data binding would be lost as described above in the problem. So, we need to data bind again on page properties changed event handler for the list view.</p> <pre><code>ListView_PagePropertiesChanged(object sender, EventArgs e) { ListView.DataSource=someDatasource; ListView.DataBind() } </code></pre>
<pre><code>&lt;asp:ListView ID="ListView1" runat="server" DataSourceID="sdsImages"&gt; &lt;ItemTemplate&gt; &lt;div class="photo sample12"&gt; &lt;asp:Image ID="img_Galerie" runat="server" ImageUrl='&lt;%# "~/imageHandler.ashx?ID=" + Eval("ImageID") %&gt;' /&gt; &lt;/div&gt; &lt;/ItemTemplate&gt; &lt;/asp:ListView&gt; &lt;asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="3" QueryStringField="ImageID"&gt; &lt;Fields&gt; &lt;asp:NextPreviousPagerField ShowFirstPageButton="True" ShowNextPageButton="False" /&gt; &lt;asp:NumericPagerField /&gt; &lt;asp:NextPreviousPagerField ShowLastPageButton="True" ShowPreviousPageButton="False" /&gt; &lt;/Fields&gt; &lt;/asp:DataPager&gt; &lt;asp:SqlDataSource ID="sdsImages" runat="server" ConnectionString="&lt;%$ ConnectionStrings:DBCS %&gt;" SelectCommand="SELECT ImageID FROM Images "&gt; </code></pre> <p></p>
29,003
<p>Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?</p>
<p>Click on the lightning bolt icon in the Properties window. Double-click the event you want to implement.</p>
<p>Sure. Use <code>myControl.Event += new EventHandler(SomeHandlerMethodInYourClass)</code> somewhere during initialization, e.g. in the form's constructor.</p>
39,915
<p>I just realized from an article in CACM that Doxygen works with Java (and several other languages) too. But Java has already the Javadoc tool. Can someone explain what are the pros and cons of either approach? Are they mutually exclusive? Is there a Maven plugin for Doxygen?</p>
<p>Doxygen has a number of features that JavaDoc does not offer, e.g. the class diagrams for the hierarchies and the cooperation context, more summary pages, optional source-code browsing (cross-linked with the documentation), additional tag support such as @todo on a separate page and it can generate output in TeX and PDF format.It also allows a lot of visual customization.</p> <p>Since Doxygen supports the standard JavaDoc tags you can run Doxygen on any source code with JavaDoc comments on it. It often can even make sense to run on source code without JavaDoc since the diagrams and source code browsing can help understanding code even without the documentation. And since the JavaDoc tool ignores unknown tags you can even use additional Doxygen tags without breaking JavaDoc generation.</p> <p>Having said all this I must admit that I haven't used Doxygen for a long time. I tend to rely heavily on my IDE nowadays to provide the same visualization and I usually don't read JavaDoc as HTML pages but import the source files into my IDE so it can generate JavaDoc flyouts and I can jump to the definitions. That's even more powerful than what Doxygen has to offer. If you want to have documentation outside the IDE and are happy to run non-Java tooling then Doxygen is worth a try since it doesn't require any change to your Java code.</p>
<p>I like the fact that with Doxygen, you can get class diagrams displayed on the same page as the documentation. Also, I like the fact that it links you directly to the source code, if needed. I am not aware if javadoc has these features though.</p>
27,863
<p>It has to be simple, here's my CSS: </p> <pre><code>.progressImage { position:relative; top:50%; } .progressPanel { height:100%; width:100%; text-align:center; display:none; } &lt;asp:Panel ID="pnlProgress" runat="server" CssClass="progressPanel"&gt; &lt;asp:Image ID="Image1" runat="server" CssClass="progressImage" ImageUrl="~/Images/Icons/loading.gif" /&gt; &lt;/asp:Panel&gt; </code></pre> <p>I toggle panel display depending on user action.</p> <p>Works great in FireFox, but shows up at the top of the page in Safari.</p> <p>p.s. "vertical-align:middle;" doesn't work either. </p> <p>p.p.s. setting "position:relative;" on the panel doesn't work, setting "position:relative;" on the panel and "position:absolute;" on the image breaks it in FF and does nothing in Safari</p> <p>THIS WORKED:</p> <pre><code>.progressPanel { height:100%; width:100%; position:relative; } .progressImage { position:absolute; top:50%; left:50%; } </code></pre>
<p>Set the position of <code>.progressPanel</code> to relative, and the position of <code>.progressImage</code> to absolute. The following works for me in FF, IE, Safari. Set the negative margins to half the width/height of your image for perfect centering. Note that some parent of the progressPanel (body in this case) needs a height so that the progressPanel can fill it.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;style type="text/css"&gt; body { height:700px; } .progressImage { position:absolute; top:50%; left:50%; margin-left:-16px; margin-top:-16px; } .progressPanel { position:relative; height:100%; width:100%; text-align:center; background:red; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="progressPanel"&gt;&lt;img class="progressImage" src="pic.jpg"/&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Position specification (relative or absolute) should be in both elements (parent and child) otherwise the positioning of child element doesn't necessarily work. You should always use relative positioning for an element unless you specify the exact position like left: 100px; top: 100px. Vertical-align refers to the element itself and concerns only the position in text line. Line-height is not the same as div height unless you change it. Line-height must be specified larger than elements inside in order to get vertical-align take effect.</p>
37,138
<p>I'm wondering if there's an integrated solution to have a database with versioned records supported by rails (ala version_fu ar_versioned) and a differ thanks!</p>
<p>Check out <a href="http://wiki.rubyonrails.org/rails/pages/ActsAsVersioned" rel="nofollow noreferrer">acts_as_versioned</a>.</p>
<p>As you noted, that functionality is supported in plugins, and won't be supported by Rails core.</p>
11,855
<p>Is there a way to modify/tell dired to copy files asynchronously? If you mark multiple files in dired and then use 'C' to copy them, emacs locks up until every file is copied. I instead want this copy to be started, and for me to continue editing as it goes on in the background. Is there a way to get this behaviour?</p> <p>EDIT: Actually, C calls 'dired-do-copy' in dired-aux, not in dired itself. Sorry for any confusion.</p>
<p>I think emacs is mostly limited to a single thread - so this may not be directly possible through standard dired commands such as 'C' copy. </p> <p>However, there is a dired command "<a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Shell-Commands-in-Dired.html" rel="nofollow noreferrer">dired-do-shell-command</a>" which calls out to a shell to do the work in the background. If you select the files you want to copy and then use key '!' (this runs dired-do-shell-command) then type 'cp ? [destination]' (possibly can use 'copy' if you are on windows). I haven't tested this - so see help on "dired-do-shell-command" for full details.</p>
<p>See also the Emacs function <code>dired-do-async-shell-command</code>.</p> <p>For an even more generic solution see <a href="https://github.com/jwiegley/emacs-async" rel="nofollow">https://github.com/jwiegley/emacs-async</a> with which you also can evaluate arbitrary Emacs Lisp code through call to a separate Emacs process (which of course incurs a bit of extra latency). More specifically regard file operations see the file dired-async.el in this repo.</p> <p>Also note that there is work on threading in Emacs under the working name Concurrent Emacs but it's not there yet. See <a href="http://www.emacswiki.org/emacs/ConcurrentEmacs" rel="nofollow">http://www.emacswiki.org/emacs/ConcurrentEmacs</a> for details.</p>
49,787
<p>I want to dive more into the unit testing concepts. An open source project which will illustrate the best practices in unit testing is required.</p>
<p>I work on <a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a> (original Java version) and I think it is worth considering as a source of study for a few reasons:</p> <ol> <li>Lots of unit tests. Certainly not the highest coverage but there are plenty to look at.</li> <li>Diverse technology. There are pojos, tag libs, velocity macros, spring, etc.</li> <li>Uneven quality of unit tests. Because we take contributions from outside the quality and throughness of unit tests vary. The core classes are very well tested. Lots of the contributions are untested or poorly tested. Consider the poorly tested ones as "an exercise left for the reader". ;)</li> <li>Maybe the best reason: You can ask questions about the tests on <a href="http://cruisecontrol.sourceforge.net/developers.html" rel="nofollow noreferrer">developer mailing list</a>. In the best case you could even end up writing tests for some of the untested areas and get coaching on your efforts.</li> </ol>
<p>The source code for <a href="http://www.nunit.org" rel="nofollow noreferrer">NUnit</a> (.NET unit testing software) would be worth a look.</p>
39,761
<p>I am going to be using C/C++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p>
<p><a href="http://tangentsoft.net/mysql++/" rel="nofollow noreferrer">MySQL++</a></p>
<p>That depends a bit on what you want to do.</p> <p>First, check out libraries that provide connectivity to more than on DBMS platform. For example, Qt makes it very easy to connect to MySQL, MS SQL Server and a bunch of others, and change the database driver (connection type) at runtime - with just a few lines of code.</p> <p>MySQL-specific libraries are fine, but bear in mind that you are locking yourself down to one DB implementation - if you ever need to change in the future it's gonna be a whole lot of work - even if you design your code such that the DB-specific stuff is behind a facade. Why not use a library that provides connectivity to multiple platforms, and save yourself the trouble?</p>
4,291
<p>I am Need of Formula to Accurately Calculate Bandwith for 1 Gig Nic Card. What i am doing is send Layer 2 Packets @ 1Gbps but my software is showing 6oo Mbps.</p> <p>The whole experiment is Back to Back. No switch No Router.</p> <p>Here is what i did.</p> <pre><code>// LinkSpeed = 1Gb UINT nBandwidth = LinkSpeed/100;//Mbps nBandwidth = nBandwidth/8; //Bytes/sec nBandwidth = nBandwidth/FrameLength; //Frames/Sec. Frame Length = 1518 UINT FramesPerBurst = (nBandwidth*Sleeptime)/1000; //Frames/Burst UINT nBufferSpaceNeededPerFrame = FrameLength-4 + sizeof(dump_bpf_hdr)); UINT nTxBufferSize = FramesPerBurst * nBufferSpaceNeededPerFrame; unsigned char* pTxBuffer = new unsigned char[m_nTxBufferSize]; </code></pre>
<p>In ethernet, you also have to take into account the <a href="http://en.wikipedia.org/wiki/Interframe_gap" rel="nofollow noreferrer">interframe gap</a>, which is at minimum, 96 quantum time, that is, the quantum time being the time to send a bit, which is, 1ns in GigaEthernet (1 second / 1,000,000,000).</p> <p>Also, if you get a collision, there will be <a href="http://en.wikipedia.org/wiki/Truncated_binary_exponential_backoff" rel="nofollow noreferrer">backoff time</a>, which quantum is chosen randomly between 0 and 2^&lt;nb collisions&gt; - 1.</p>
<p>First, you need a "long" at a minimum to store the no. of frames you received. </p> <p>To calculate the bandwidth being used,</p> <p>a = GetIntfCounters()</p> <p>Start a timer (timeout) in seconds</p> <p>b = GetIntfCounters()</p> <p>Pkts/sec = (b - a)/timeout</p> <p>Bits/sec = (Pkts/sec * pktsize)</p> <p>Bytes/sec = (Bits/sec)/8</p> <p>The GetIntfCounters() would depend on the software platform that you are using. Instead of a timer, you can use a sleep for a given interval, and then calculate the pps over that interval. However, the only realistic calculation of bandwidth at which you device is receiving frames will be if you take interface counters into consideration.</p>
44,599
<p>Microsoft's new F# programming language provides the powerful combination of functional programming (first-class lexical closures and tail calls) with an efficient concurrent garbage collector that makes it easy to leverage multicores.</p> <p>OCaml, Haskell, Erlang and all free Lisp and Scheme implementations that I know of do not have concurrent GCs. Scala and Clojure have a concurrent GC but no tail calls.</p> <p>So there appear to be no open source programming languages that combine these features. Is that correct?</p>
<p>Erlang has a shared nothing model where <a href="http://prog21.dadgum.com/16.html" rel="noreferrer">each process has it's own garbage collector</a>. Whether you consider that to be no concurrency or not it's up to you. But it sure scales very well as the number of processes goes up.</p>
<p>Not really an answer to your question, but to my best knowledge, F# uses the standard .NET garbage collector, which is not concurrent; all threads are stopped during GC.</p> <p>Edit : my mistake, there is a concurrent GC in multiprocessor mode.</p>
35,060
<p>While debugging through a .NET 3.5 SP1 project which is contacting a local web service, I'm receiving the exception</p> <p>System.BadImageFormatException: "Bad Class Token"</p> <p>Of course there aren't much more details about what's causing the exception.</p> <p>I can tell that the method where this occurs, which is in the same class as it's caller, the debugger fails to reach. This exception occurs on the call of the method that contacts the web service. I do have other methods communicating with the web service, so the reference is good.</p> <p><strike>My unit tests for the method are also failing with the same exception.</strike> <br /><b>Correction</b>: my unit tests for the method are successful, furthering the confusion.</p> <p>Does anyone know of a way to track down this exception? I've read through the documentation on the exception class, which leads me to believe that one of the assemblies is incorrect in its version, or there's an issue with the build.</p> <p>What other steps would you suggest in troubleshooting this exception?</p>
<p>Running peverify.exe on the assembly may yield useful diagnostics.</p> <p><a href="http://msdn.microsoft.com/en-us/library/62bwd2yd.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/62bwd2yd.aspx</a></p>
<p>Running peverify.exe on the assembly may yield useful diagnostics.</p> <p><a href="http://msdn.microsoft.com/en-us/library/62bwd2yd.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/62bwd2yd.aspx</a></p>
26,336
<p>I have a need to determine what security group(s) a user is a member of from within a SQL Server Reporting Services report. Access to the report will be driven by membership to one of two groups: 'report_name_summary' and 'report_name_detail'. Once the user is executing the report, we want to be able to use their membership (or lack of membership) in the 'report_name_detail' group to determine whether or not a "drill down" should be allowed.</p> <p>I don't know of any way out of the box to access the current user's AD security group membership, but am open to any suggestions for being able to access this info from within the report.</p>
<p>You can add custom code to a report. <a href="http://msdn.microsoft.com/en-us/library/ms155798.aspx" rel="noreferrer">This link</a> has some examples.</p> <p>Theoretically, you should be able to write some code like this, and then use the return value to show/hide what you want. You may have permissions problems with this method, though.</p> <pre><code>Public Function ShouldReportBeHidden() As Boolean Dim Principal As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()) If (Principal.IsInRole("MyADGroup")) Then Return False Else Return True End If End Function </code></pre> <p><strong>Alternatively</strong>, you could add your detail report as a subreport of your summary report. Then you could use the security functionality built in to SSRS to restrict access to your sub report.</p>
<p>In Reporting Services just use :</p> <pre><code>Public Function IsMemberOfGroup() As Boolean If System.Threading.Thread.CurrentPrincipal.IsInRole("MyADGroup") Then Return True Else Return False End If End Function </code></pre> <p>as indicated in <a href="https://stackoverflow.com/questions/3095449/ssrs-windowsidentity-getcurrent-giving-me-nt-authority-network-service">this posting</a></p> <p><em>Note: This works once the report is deployed to server but not in the IDE.</em></p>
33,740
<p>I'm looking to add a numeric up / down control to a .Net StatusStrip. Unfortunately, it isn't listed as an option in the UI designer. Is there a way to do this? </p>
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripcontrolhost.aspx" rel="nofollow noreferrer">ToolStripControlHost</a> class to host a custom ( NumericUpDown for now ) class. You can also derive from this class "NumericUpDownToolStripItem" which initialize the "Control" property with the custom control and can populate next properties from the hosted control ( Min, Max, Value - for example ).</p>
<p>You could try adding 3 ToolStripStatusLabels, set the Image of the first to an "Up Arrow" and the Image of the Third to "Down Arrow". Blank their Text properties.</p> <p>The Middle one can hold the Number, which you increase/decrease in the Click Events.</p> <p>Edit: Left/Right Arrows would probably look better. Left for Down, Right for Up.</p>
14,165
<p>I recently build myself a semi beef up PC (Q9450, 8GB DDR2 1066, 1TB HDD, Dual 8600GT, Vista Ultimate and Dual 22' Monitors) and I'm evaluating whether i should develop on a VPC/VMWare session on top of Vista or not?</p> <p>One benefit I can see is that I can run the same VM on my Vista laptop so my development environment is the same on any of my machines. I also plan on purchasing a MBP before the end of the year as well.</p> <p>Found a couple of articles online that semi-help <a href="http://www.devx.com/vmspecialreport/Article/30410/1954" rel="nofollow noreferrer">Here</a></p> <p>Any other thoughts would be really appreciated?</p>
<p>For webdevelopment I like to have the serverpart separeted out into a VM. My current setup is a Macbook Pro with several Debian VM's inside. I like the isolation aspect of it. I can try new software on the servers and have the ability to revert them back if something is messed up.</p> <p>I do the programming via network-share (samba) in Textmate on the host system.</p>
<p>It depends what you are developing and in what language.</p> <p>VM's tend to take a fairly hard hit on disk access, so compiling may slow down significantly, especially for large C/C++ projects. Not sure if this would be such an issue with .NET/Java.</p> <p>If you are doing anything that is graphics intensive (3D, video, etc) then I would steer clear of a VM too.</p>
20,233
<p>If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings:</p> <pre><code>org.company.project.component org.company.project.component.sub_component </code></pre> <p>you just get:</p> <pre><code>sub_component </code></pre> <p>I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way. </p> <p>Another use-case is to find the diff between the strings:</p> <pre><code>org.company.project.component.diff org.company.project.component.sub_component </code></pre> <p>I actually only want to remove the sections that are identical.</p>
<p>Depends on <em>precisely</em> what you want. If you're looking for a way to compare strings in the general case -- meaning finding common sub-strings between arbitrary inputs -- then you're looking at something closer to the Levenshtein distance and similar algorithms. However, if all you need is prefix/suffix comparison, this should work:</p> <pre><code>public static String sub(String a, String b) { if (b.startsWith(a)) { return b.subString(a.length()); } if (b.endsWith(a)) { return b.subString(0, b.length() - a.length()); } return ""; } </code></pre> <p>...or something roughly to that effect.</p>
<p>This is a solution for the Javascript end of the question:</p> <pre><code>String.prototype.contracat = function(string){ var thing = this.valueOf(); for(var i=0; i&lt;string.length;i++){ thing=thing.replace(string.charAt(i),""); } return thing }; </code></pre>
15,741
<p>Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid. </p> <p>I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win32api directly from IronPython. Is there a way to do this using built-in .net classes? Most of the stuff I have come across recommends using win32api, such as below.</p> <p><a href="https://stackoverflow.com/questions/79111/net-c-getting-child-windows-when-you-only-have-a-process-handle-or-pid">.NET (C#): Getting child windows when you only have a process handle or PID?</a></p> <p>UPDATE: I found a work-around to what I was trying to do. Answer below. </p>
<p>The article below shows how to access the win32api indirectly from IronPython. It uses CSharpCodeProvider CompileAssemblyFromSource method to compile an assembly in memory from the supplied C# source code string. IronPython can then import the assembly.</p> <p><a href="http://www.voidspace.org.uk/ironpython/dynamically_compiling.shtml" rel="nofollow noreferrer">Dynamically compiling C# from IronPython</a></p>
<p>It's like asking if you can swim without going in to the water. If you need information from windows, the only option is to use the win32api. There are lots of examples to find on how to do so.</p> <p>If you don't like this answer, just leave a comment in your question and I will remove this answer, so your question will remain in the unanswered questions list.</p>
15,569
<p>I get exception "There is no default persistence unit in this deployment." can I somehow mark unit as default?(I have only one persistence unit, so Id rather not call it by name)</p>
<p>My advice:</p> <p>Don't make a website from scratch. Use a content management system such as DotNetNuke or Drupal to do it. Find a provider that will host these platforms and learn it. Don't reinvent the wheel.</p>
<p>There's this recommendation that is valid for anyone learning anything new: keep it simple. In the case of web development, I would certainly vote against Silverlight, for a number of reasons. </p> <p>The first one you have already mentioned, it is very Google-unfriendly.</p> <p>The second one is that it is not an ubiquitous plugin: lots of people don't have it yet, and lots of people feel (rightly) scared when they get to a site and see this thing asking them to download and install a plugin. It gets even worst when you're talking about Mac and Linux users, lots of them don't even know what is Silverlight (just try among your friends).</p> <p>Another aspect is that, unless you have some very good design skills, or are planning to hire a designer, a Silverlight site has a big chance of looking ugly as hell. When you go for good old HTML you have <a href="http://www.freecsstemplates.org/" rel="nofollow noreferrer">tons of beautiful, free html and css templates out there</a>, but that's not the case with Silverlight, AFAIK.</p> <p>Finally, if you really want to learn web programming, the best is to start with the basics, HTML, CSS and Javascript. In the case of Javascript you can skip learning all the gritty details, and go for jQuery, it will be a great stepping stone. If you really want to play with Silverlight and XAML I would recommend adding some pzazz to the site <em>after</em> it's up and running, but not upfront. </p> <p>For someone starting on web development, coming from the ASP.NET side, I would strongly recommend ASP.NET MVC, like the guy before me did: it is closer to <em>real</em> web development than webforms, and it promotes (though it doesn't guarantee) a more elegant architecture. I know that your goal #1 is to learn Silverlight, but I would hold on a bit and get the basics covered first.</p> <p>Now, when it comes to the specific Junior Women's Club site you mentioned, I would go for a packaged solution like DNN first; then, once everyone is happy and dandy (and it will take a while, you'll get an infinite number of requests once it's available, from font colors to new features to administrative tasks) then you can start working on your own pace and in peace on a homebrew v2. Another nice thing about DNN is that it allows you to code your own custom modules, so you can do some web development (including Silverlight) in small pieces, instead of getting bogged down on a huge project at once.</p>
48,605
<p>How does Google Chrome command and control multiple cross platform processes and provide a shared window / rendering area?</p> <p>Any insights?</p>
<p>The source code is online <a href="https://chromium.googlesource.com/chromium/chromium/+/trunk/chrome/" rel="nofollow noreferrer">here</a> ...</p>
<p>The source code is online <a href="https://chromium.googlesource.com/chromium/chromium/+/trunk/chrome/" rel="nofollow noreferrer">here</a> ...</p>
6,353
<p>I am looking for a reporting service/tool for visual Studio. My only restraint is my web server is off limits to me as far as installing ANYTHING. So I need something I can just include in my project.</p> <p>My users need to be able to export a report to PDF and without being able to use Crystal I am pretty much lost.</p> <p>Any ideas?</p>
<p><a href="http://www.fyireporting.com/" rel="noreferrer">fyireporting</a> (released under Apache License) is worth a try. </p> <p>The fyiReporting RDL Project is a powerful report and charting system based on Report Definition Language (RDL). Tabular, free form, matrix, charts are fully supported. Report output may be displayed as HTML, PDF, XML, .Net Control, Web Archive, and to a printer. Libraries exist for use in your ASP.NET, Windows .Net, and command line applications. </p>
<p>If you're willing to have no report designer and open source is an absolute requirement, then take a look at <a href="http://itextsharp.com/" rel="nofollow">iTextSharp</a> - version 4.0 is totally open source (5.0 you have to pay for comercial use).</p> <p>There are some additional open source systems listed at <a href="http://www.reportingsoftware.info/" rel="nofollow">Reporting Software Info</a>.</p>
24,808
<p>I have a general exception handler, Application_error in my global.asax where I'm trying to isolate all the uncaught exceptions on all my many pages. I don't want to use Page_error to catch exception because it's inefficient to call that on so many pages. So where in the exception can I find what page actually caused the exception?</p>
<pre><code>HttpContext con = HttpContext.Current; con.Request.Url.ToString() </code></pre>
<p>Remember, the page is not (should not) always be the cause of the exception. It could just as easily be coming from another assembly - and if you don't have your logic in your codebehinds, it likely will be coming from another assembly. Don't get me wrong, it is great to know which page, from the aspect of saying X Page caused Y exception in Z assembly.</p>
44,802
<p>I am preparing a lecture on files for the more junior students in programming class. One of the points I want to elaborate are good practices with files.</p> <p>What are the thing to keep in mind when using files in any programming language?</p>
<ul> <li><p>Files can be considered to contain a set of <em>records</em>, each either of a <em>fixed length</em> or ending with a <em>delimiter</em>.</p></li> <li><p>Files are generally optimized for <em>sequential access</em>, not <em>random-access</em>. It's hard to insert data into the middle of a file, and it's typically faster to process files linearly (like a cassette tape) than randomly (like a CD in "shuffle" mode).</p></li> <li><p>Random-access files usually contain fixed-length records, most of which contain empty space, making them larger than sequential-access files.</p></li> <li><p>Files are temperamental and unpredictable creatures. They can change length, disappear, change access permissions, <em>etc</em>. between accesses, so <em>validate</em> your operations carefully and <em>check return codes</em>.</p></li> <li><p>Files can be used as <em>buffers</em> if you read from the beginning (tail) and write to the end (head).</p></li> <li><p><em>Flush your buffers!</em></p></li> </ul> <p>Since no one's had the poor taste to say it yet: this should give your students a handle on the subject.</p>
<p>Remember to close them when you're done with them.</p>
34,900
<p>I have some special cells in my Excel workbooks which are managed by my Excel Add-in. I want to prevent users from changing content of those cells, but I also want to know, what value users wanted to enter to those cells. On the SheetChange event I can check what users entered to my special cells, but how do I determine the PREVIOUS value in those cells and REVERT user changes?</p> <hr> <p>It is not a solution for me. If I lock cell in Excel, it becomes read-only - user can not even try to enter anything to this cell - Excel popups warning dialog in this case. My problem is that I want to catch what user entered to my cell, do something with this value, and then revert cell content to original value.</p>
<p>How about something like this, which is in VBA, but should be fairly easy to translate to C#</p> <pre><code>Option Explicit ' We are monitoring cell B2... Private initialB2Value As Variant ' holds the value for reinstatement when the user changes it Private Sub Worksheet_Activate() ' record the value before the user makes any changes. ' Could be a constant value, or you could use .Formula to ensure a calculation is not lost initialB2Value = Range("B2").Value End Sub Private Sub Worksheet_Change(ByVal Target As Range) Static alreadyChanging As Boolean ' when we reset the cell, Worksheet_Change will fire again, so we'll use a flag ' to tell us if we should care or not... If alreadyChanging Then ' change is because of this code, no need to process alreadyChanging = False Exit Sub End If If IsEmpty(Intersect(Target, Range("B2"))) Then ' If the change is not happening to the range we are monitoring, ignore it Exit Sub End If ' Do something with the user's input here Debug.Print "User input " &amp; Range("B2").Value &amp; " into B2" ' before we reset the value, flag that we are changing the value in code alreadyChanging = True ' now apply the old value Range("B2").Value = initialB2Value End Sub </code></pre>
<p>I would keep a copy of the cells on a hidden sheet.</p> <p>Then when the user changes a cell, it's easy to find the matching cell on the hidden sheet.</p>
37,710
<p>What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP?</p>
<p>Scraping generally encompasses 3 steps: </p> <ul> <li>first you GET or POST your request to a specified URL </li> <li>next you receive the html that is returned as the response</li> <li>finally you parse out of that html the text you'd like to scrape.</li> </ul> <p>To accomplish steps 1 and 2, below is a simple php class which uses Curl to fetch webpages using either GET or POST. After you get the HTML back, you just use Regular Expressions to accomplish step 3 by parsing out the text you'd like to scrape.</p> <p>For regular expressions, my favorite tutorial site is the following: <a href="http://www.regular-expressions.info/" rel="nofollow noreferrer">Regular Expressions Tutorial</a></p> <p>My Favorite program for working with RegExs is <a href="http://www.regexbuddy.com/" rel="nofollow noreferrer">Regex Buddy</a>. I would advise you to try the demo of that product even if you have no intention of buying it. It is an invaluable tool and will even generate code for your regexs you make in your language of choice (including php).</p> <p>Usage: <pre><code></p> <p>$curl = new Curl(); $html = $curl->get("<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>");</p> <p>// now, do your regex work against $html </pre></code></p> <p>PHP Class:</p> <pre><code> &lt;?php class Curl { public $cookieJar = ""; public function __construct($cookieJarFile = 'cookies.txt') { $this->cookieJar = $cookieJarFile; } function setup() { $header = array(); $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,"; $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; $header[] = "Cache-Control: max-age=0"; $header[] = "Connection: keep-alive"; $header[] = "Keep-Alive: 300"; $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; $header[] = "Accept-Language: en-us,en;q=0.5"; $header[] = "Pragma: "; // browsers keep this blank. curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7'); curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header); curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar); curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar); curl_setopt($this->curl,CURLOPT_AUTOREFERER, true); curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true); } function get($url) { $this->curl = curl_init($url); $this->setup(); return $this->request(); } function getAll($reg,$str) { preg_match_all($reg,$str,$matches); return $matches[1]; } function postForm($url, $fields, $referer='') { $this->curl = curl_init($url); $this->setup(); curl_setopt($this->curl, CURLOPT_URL, $url); curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_REFERER, $referer); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields); return $this->request(); } function getInfo($info) { $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info); return $info; } function request() { return curl_exec($this->curl); } } ?> </code> </pre>
<p>The curl library allows you to download web pages. You should look into regular expressions for doing the scraping.</p>
4,660
<p>I have a specific changeset that I want to "rollback" my Development branch to, but I want to take all of the the changes after that specific changeset and put them in to a new branch. Is this possible in TFS? If so, how could I do such a thing?</p> <p>Thanks, Dave</p>
<p>Well.. The easiest way is to do exactly what you just said. </p> <p>Branch the existing code into a new spot. Then get the changeset you want, checkout the project, and check the changeset back in.</p>
<p>I ended up branching at the changeset I wanted, naming it Development-stable, then renamed Development to Development-experimental and then renamed Development-stable to Development.</p>
19,252
<p>Is it possible to get the expiry <code>DateTime</code> of an <code>HttpRuntime.Cache</code> object?</p> <p>If so, what would be the best approach?</p>
<p>I just went through the System.Web.Caching.Cache in reflector. It seems like everything that involves the expiry date is marked as internal. The only place i found public access to it, was through the Cache.Add and Cache.Insert methods.</p> <p>So it looks like you are out of luck, unless you want to go through reflection, which I wouldn't recommend unless you really really need that date.</p> <p>But if you wish to do it anyway, then here is some code that would do the trick:</p> <pre><code>private DateTime GetCacheUtcExpiryDateTime(string cacheKey) { object cacheEntry = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { cacheKey, 1 }); PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance); DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null); return utcExpiresValue; } </code></pre> <p><a href="https://stackoverflow.com/questions/53199635/cant-access-runtime-cache-using-reflection">Since .NET 4.5</a> the internal public getter of the <code>HttpRuntime.Cache</code> was replaced with a static variant and thus you will need to invoke/get the static variant:</p> <pre><code>object cacheEntry = Cache.GetType().GetMethod("Get").Invoke(null, new object[] { cacheKey, 1 }); </code></pre>
<p>For my solution, I stored the expiry value in the the value of cached object and used the same value as expiry for the cache.</p> <pre><code>var expiry = DateTime.UtcNow.AddMinutes(10); HttpRuntime.Cache.Insert(&quot;key&quot;, new { Value = &quot;Value&quot;, Expiry = expiry }, null, expiry, Cache.NoSlidingExpiration); </code></pre> <p>And when you need to check the expiry you can get the object's Expiry property</p> <pre><code>dynamic cachedData = HttpRuntime.Cache.Get(&quot;key&quot;); DateTime cacheExpiry = cachedData.Expiry; </code></pre>
44,810
<p>Given:</p> <pre><code>interface I { } class B: I { } class C: I { } class A { public void Method(B arg) { } public void Method(C arg) { } public void Method(I arg) { // THIS is the method I want to simplify. if (I is B) { this.Method(arg as B); } else if (I is C) { this.Method(arg as C); } } } </code></pre> <p>I know that there are better ways to design this type of interactions, but because of details which would take too long to explain this is not possible. Since this pattern will be duplicated MANY times, I would like to replace the conditional logic with a generic implementation which I could use just one line. I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.</p> <p>Any help would be appreciated.</p>
<p>I would put the method inside the interface and then let polymorphism decide which method to call</p> <pre><code>interface I { void Method(); } class B : I { public void Method() { /* previously A.Method(B) */} } class C : I { public void Method() { /* previously A.Method(C) */ } } class A { public void Method(I obj) { obj.Method(); } } </code></pre> <p>Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.</p>
<p>It doesn't exist in a convenient form withing C# - <a href="https://stackoverflow.com/questions/156467/switch-pattern-matching-idea">see here</a> for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;</p> <pre><code>return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0); </code></pre> <p>Again - not pretty.</p>
20,858
<p>I am trying to delete several rows from a MySQL 5.0.45 database:</p> <pre><code>delete from bundle_inclusions; </code></pre> <p>The client works for a while and then returns the error:</p> <pre><code>Lock wait timeout exceeded; try restarting transaction </code></pre> <p>It's possible there is some uncommitted transaction out there that has a lock on this table, but I need this process to trump any such locks. How do I break the lock in MySQL?</p>
<p>I agree with Erik; TRUNCATE TABLE is the way to go. However, if you can't use that for some reason (for example, if you don't <em>really</em> want to delete every row in the table), you can try the following options:</p> <ul> <li>Delete the rows in smaller batches (e.g. DELETE FROM bundle_inclusions WHERE id BETWEEN ? and ?)</li> <li>If it's a MyISAM table (actually, this may work with InnoDB too), try issuing a LOCK TABLE before the DELETE. This should guarantee that you have exclusive access.</li> <li>If it's an InnoDB table, then <em>after</em> the timeout occurs, use SHOW INNODB STATUS. This should give you some insight into why the lock acquisition failed.</li> <li>If you have the SUPER privilege you could try SHOW PROCESSLIST ALL to see what other connections (if any) are using the table, and then use KILL to get rid of the one(s) you're competing with.</li> </ul> <p>I'm sure there are many other possibilities; I hope one of these help.</p>
<p>Guessing: truncate table bundle_inclusions</p>
9,026
<p>How can I verify a given xpath string is valid in C#/.NET?</p> <p>I'm not sure just running the XPath and catching exceptions is a valid solution (putting aside the bile in my throat for a moment) - what if tomorrow I run into some other input I haven't tested against?</p>
<blockquote> <p>How can I verify a given XPath string is valid in C#/.NET?</p> </blockquote> <p>You try to build an <code>XPathExpression</code> from it and catch the exception.</p> <pre><code>try { XPathExpression.Compile(xPathString); } catch (XPathException ex) { MessageBox.Show("XPath syntax error: " + ex.Message); } </code></pre>
<p>Use a 'mild' regular expression to filter out complete garbage. If it passes the regex, just execute the query and catch exceptions, like mentioned above...</p>
39,803
<p>Microsoft like implementing their own versions of popular open-source frameworks and assemblies, for example:</p> <ul> <li>Microsoft's MVC Framework vs MonoRail</li> <li>Microsoft's Unity IoC container vs Castle Windsor / Spring.net / Ninject etc</li> <li>Microsoft's VS Unit Test framework vs nUnit (and various others)</li> </ul> <p>Questions:</p> <p>What else has Microsoft 'borrowed'?</p> <p>Which are better in each situation and why?</p> <p>What are people's attitudes towards the official Microsoft stuff vs the ALT.NET versions?</p> <p>What do you think is next to be taken under the Redmond wing?</p> <p><strong>EDIT</strong> Ok, instead of which is 'better', which do you prefer to use as a developer?</p>
<p>Why not just take a stick to a hornet's nest?</p> <p>There's one thing definitely better about MS' versions of these great tools--its much easier to get your MS shop to use a product if it's an official MS product.</p> <p>If you're a shop that develops for Windows systems, you have to take extra steps when incorporating a non-MS product in yours. There are issues with licensing and documentation that, at a minimum, you must meet. Plus, there's always the internal politics that must be overcome. And, in some cases, your clients may be reluctant to use your product if it uses an "open source" component not officially supported by MS.</p> <p>Its not fair, but neither is life. </p> <p>Personally, I like it when MS competes against products like this, as it helps drive new life into the framework.</p>
<p>Only kinda related, but I remember back when they first released windows xp I had a computer that would dual-boot between windows 98 and linux. It had an off-brand sound card where the linux driver was buggy; it would work for a while, and then start stuttering in a very distinct way. When I got xp for the machine (free through the school where I was), it's audio driver for the card had <em>the exact same bug</em>!</p> <p>BTW: anyone taking bets for how long until this gets closed?</p>
25,258
<p>We are trying to bind a Linux machine (debian 4.0) to W2k3 AD. We have configured kerberos properly so that we can get TGTs. And users authenticate properly. However, PAM seems to be the sticky wicket. For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell. The default environment is configured properly and PAM even creates the Homedir properly. As a reference we were loosely following:</p> <p><a href="https://help.ubuntu.com/community/ActiveDirectoryHowto" rel="nofollow noreferrer">https://help.ubuntu.com/community/ActiveDirectoryHowto</a></p>
<p>If you're confident everything but PAM works correctly, I suggest passing the debug option to pam_krb5.so to see if that gives a clue to what's happening.</p> <p>I'd also suggest verifying that nss-ldap is set up correctly using </p> <pre><code>getent passwd avalidusername </code></pre>
<p>I have used Likewise to do something similar on our servers. Here is the process we use to configure it:</p> <p>Install Likewise:</p> <pre><code>$ sudo apt-get update $ sudo apt-get install likewise-open </code></pre> <p>Join the domain (Assuming the domain "domain.local")</p> <pre><code>$ sudo domainjoin-cli join domain.local Administrator $ sudo update-rc.d likewise-open defaults $ sudo /etc/init.d/likewise-open start </code></pre> <p>Assuming you are using sudo AND want AD users to be able to have sudoer powers, you need to edit the sudoers file. This can be done with following command:</p> <pre><code>$ sudo visudo </code></pre> <p>then add the following to the end of the file (this assumes the domain "DOMAIN" and all the users that should have sudo are in a group called "linux_admin" in active directory):</p> <pre><code>%DOMAIN\\linux_admin ALL=(ALL) ALL </code></pre>
21,525
<p>I have three closely related applications that are build from the same source code - let's say APP_A, APP_B, and APP_C. APP_C is a superset of APP_B which in turn is a superset of APP_A.</p> <p>So far I've been using a preprocessor define to specify the application being built, which has worked like this.</p> <pre><code>// File: app_defines.h #define APP_A 0 #define APP_B 1 #define APP_C 2 </code></pre> <p>My IDE build options then specify (for example)</p> <pre><code>#define APPLICATION APP_B </code></pre> <p>... and in source code, I will have things like</p> <pre><code>#include "app_defines.h" #if APPLICATION &gt;= APP_B // extra features for APPB and APP_C #endif </code></pre> <p>However, I shot myself in the foot this morning and wasted far to much time by simply omitting the line to #include "app_defines.h" from one file. Everything compiled fine, but the application crashed with AVs at startup.</p> <p>I'd like to know what a better way of handling this would be. Previously, This would normally one of the few times when I'd consider #define could be used (in C++, anyway), but I still goofed up badly and the compiler didn't protect me. </p>
<p>You don't always have to force inheritance relationships in applications that share a common code base. Really.</p> <p>There's an old UNIX trick where you tailor the behavior of you application based on argv[0], ie, the application name. If I recall correctly (and it's been 20 years since I looked at it), rsh and rlogin are/were the same command. You simply do runtime configuration based on the value of argv[0].</p> <p>If you want to stick with build configuration, this is the pattern that is typically used. Your build system/makefile defines a symbol on the command like, APP_CONFIG to be a non-zero value then you have a common include file with the configuration nuts and bolts.</p> <pre><code>#define APP_A 1 #define APP_B 2 #ifndef APP_CONFIG #error "APP_CONFIG needs to be set #endif #if APP_CONFIG == APP_A #define APP_CONFIG_DEFINED // other defines #endif #if APP_CONFIG == APP_B #define APP_CONFIG_DEFINED // other defines #endif #ifndef APP_CONFIG_DEFINED #error "Undefined configuration" #endif </code></pre> <p>This pattern enforces that the configuration is command line defined and is valid.</p>
<p>You might want to have a look at tools that support the development of product lines and foster explicit variant management in a structured way.</p> <p>One of these tools is pure::variants from <a href="http://www.pure-systems.com/" rel="nofollow noreferrer">pure-systems</a> which is capable of variability management through feature models and of keeping track of the various places a feature is implemented in source code.</p> <p>You can select a specific subset of feature from the feature model, constraints between features are being checked, and the concrete variant of your product line, that is, a specific set of source code files and defines is created.</p>
32,752
<p>I am fetching data in from an SQL table using a DataSet in VB.Net. When there is data in table, it displays the data properly in the grid, but when there is no data in the table, it only shows the UltraGrid's basic view.</p> <p>How can I display the column names of the table as headings of the UltraGrid even when there is no data in Table?</p> <hr> <p>Thanks for the reply, but I think the problem that JD is having is a bit different from mine - in my application the data got fetched properly from SQL Server. My problem is that when there is no data in the table, I want to display the columns of the table as the headings of the grid with 0 rows. This is not happening.</p> <p>It just shows a message box saying that no data is found, and the UltraGrid shows as it does by default in the application.</p>
<p>After giving up on everything else, I deleted the local workspace and created a new one. Now everything works fine.</p>
<p>Have you checked to make sure that the Active Directory change has propagated to TFS? I've seen issues before where users information is changed and TFS doesn't pick up the change and gets confused about your user.</p> <p>Also take a look at the following blog post. It details how to sync up TFS with a user name change in Active Directory</p> <p><a href="http://blogs.msdn.com/teams_wit_tools/archive/2007/03/15/handling-display-name-changes-in-team-foundation-server.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/teams_wit_tools/archive/2007/03/15/handling-display-name-changes-in-team-foundation-server.aspx</a></p>
40,578
<p>I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?</p>
<p>The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):</p> <pre><code> TextBox tb = new TextBox(); Button btn = new Button { Dock = DockStyle.Bottom }; btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); }; Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } }); </code></pre> <p>If this isn't an option, you can look at the KeyDown event etc, but that is more work...</p> <pre><code> TextBox tb = new TextBox(); Button btn = new Button { Dock = DockStyle.Bottom }; btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); }; tb.KeyDown += (sender,args) =&gt; { if (args.KeyCode == Keys.Return) { btn.PerformClick(); } }; Application.Run(new Form { Controls = { tb, btn } }); </code></pre>
<pre><code>private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '\r') { button1_Click(textBox1.Focus(),e); } } </code></pre>
38,298
<p>I have a <code>byte[]</code> array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the <code>BinaryWriter</code> object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)</p> <p>The problem I'm having is that the commonly accepted code for this task:</p> <pre><code> public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } </code></pre> <p>doesn't work for me. The second line of the above method where it calls the <code>Image.FromStream</code> method dies at runtime, saying</p> <pre><code>Parameter Not Valid </code></pre> <p>I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the <code>FromStream</code> method accept this fact.</p> <p>How do I turn a byte array of a TIFF image into an Image object?</p> <p>Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.</p>
<p><strong>Edit:</strong> The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly.</p> <p>I think you need to write to your MemeoryStream first.</p> <p>As if my memory (no pun intended) serves me correctly this:</p> <pre><code>MemoryStream ms = new MemoryStream(byteArrayIn); </code></pre> <p>Creates a memory stream of that size.</p> <p>You then need to write your byte array contents to the memory stream:</p> <pre><code>ms.Write(byteArrayIn, 0, byteArrayIn.Length); </code></pre> <p>See if that fixes it.</p>
<p>All these were clues that helped me figure out my problem which was the same problem as the question asks. So i want to post my solution which i arrived at because of these helpful clues. Thanks for all the clues posted so far!</p> <p>As Time Saunders posted in his answer, that Write method to actually write the bytes to the memory stream is essential. That was my first mistake.</p> <p>Then my data was bad TIFF data too, but in my case, i had an extra character 13 at the beginning of my image data. Once i removed that, it all worked fine for me.</p> <p>When i read about some basic TIFF file format specs, i found that TIFF files must begin with II or MM (two bytes with values of either 73 or 77). II means little-endian byte order ('Intel byte ordering') is used. MM means big-ending ('Motorola byte ordering') is used. The next two bytes are a two byte integer value ( = Int16 in .NET) of 42, binary 101010.</p> <p>Thus a correct TIFF stream of bytes begins with the decimal byte values of: 73, 73, 42, 0 or 77, 77, 0, 42. I encourage anyone with the same problem that we experienced to inspect your TIFF data byte stream and make sure your data is valid TIFF data!</p> <p>Thanks Schnapple and Tim Saunders!!</p>
5,276
<p>While accessing a webservice which is availbale at <a href="http://recpushdata.cyndigo.com/jobs.asmx" rel="nofollow noreferrer">http://recpushdata.cyndigo.com/jobs.asmx</a>, I am getting this Exception. "Remote name could not be resolved"</p> <p>Any Suggesytion..what to do..</p>
<p>The server error you got in the previous comment is good - it means your original problem, being unable to resolve the remote host, is solved. </p> <p>As to your HTTP 500 error, check the event log for that time on the remote host. If you don't have access to it, contact its administrator. </p>
<p>Try using the URL:</p> <p><a href="http://216.10.246.91/jobs.asmx" rel="nofollow noreferrer">http://216.10.246.91/jobs.asmx</a></p> <p>If this works, whereever you are calling the web service from has a problem with DNS. If that does not work report back.</p>
40,070
<p>Is there any BNF grammar for regular expression?</p>
<p>You can see one for <a href="http://www.cs.sfu.ca/~cameron/Teaching/384/99-3/regexp-plg.html" rel="noreferrer">Perl regexp</a> (displayed <a href="https://web.archive.org/web/20090129224504/http://faqts.com/knowledge_base/view.phtml/aid/25718/fid/200" rel="noreferrer">a little more in detail here</a>, as posted by <a href="https://stackoverflow.com/users/4200/edg">edg</a>)</p>
<p><a href="http://web.archive.org/web/20090129224504/http://faqts.com/knowledge_base/view.phtml/aid/25718/fid/200" rel="noreferrer">http://web.archive.org/web/20090129224504/http://faqts.com/knowledge_base/view.phtml/aid/25718/fid/200</a></p>
33,272
<p>I would like to use nail polish to paint and smooth a PLA model. Could nail polish damage a model made out of pure PLA?</p>
<p>NO if you want to smooth your print, gently heat the plastic and with a utensil smooth out the plastic. A hair dryer is a good way of doing this but be careful to only lightly melt the outside of the model.</p>
<p>Nail polish contains acetone. It melts PLA, so yes you <em>could</em> damage it. Google acetone vapor batch to read up on a safer way to do the job.</p>
699
<p>There is a way to keep the scroll on bottom for a multi line textbox?</p> <p>Something like in the vb6 </p> <pre><code>txtfoo.selstart=len(txtfoo.text) </code></pre> <p>I'm trying with txtfoo.selectionstart=txtfoo.text.length without success.</p> <p>Regards.</p>
<p>Ok, I found that the solution was to use </p> <pre><code>txtfoo.AppendText </code></pre> <p>instead of </p> <pre><code> txtfoo.text+="something" </code></pre>
<p>Interesting question. I'm guessing that you are trying to select the text via form load? I can't get it working on form load, but I can on form click. Wierd. :)</p> <pre><code>Public Class Form1 Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click ScrollTextbox() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ScrollTextbox() End Sub Private Sub ScrollTextbox() TextBox1.SelectionStart = TextBox1.TextLength TextBox1.ScrollToCaret() End Sub End Class </code></pre> <p>If it is completely necessary, you could use a timer.</p>
20,419
<p>Have a look at this very simple example WPF program:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;GroupBox&gt; &lt;GroupBox.Header&gt; &lt;CheckBox Content="Click Here"/&gt; &lt;/GroupBox.Header&gt; &lt;/GroupBox&gt; &lt;/Window&gt; </code></pre> <p>So I have a GroupBox whose header is a CheckBox. We've all done something like this - typically you bind the content of the GroupBox in such a way that it's disabled when the CheckBox is unchecked.</p> <p>However, when I run this application and click on the CheckBox, I've found that sometimes my mouse clicks are swallowed and the CheckBox's status doesn't change. If I'm right, it's when I click on the exact row of pixels that the GroupBox's top border sits on.</p> <p>Can someone duplicate this? Why would this occur, and is there a way around it?</p> <p>Edit: Setting the GroupBox's BorderThickness to 0 solves the problem, but obviously it removes the border, so it doesn't look like a GroupBox anymore.</p>
<p>It appears to be a subtle bug in the control template for the GroupBox. I found by editing the default template for the GroupBox and moving the Border named 'Header' to the last item in the control templates Grid element, the issue resolves itself. </p> <p>The reason is that the one of the other Border elements with a TemplateBinding of BorderBrush was further down in the visual tree and was capturing the mouse click, that's why setting the BorderBrush to null allowed the CheckBox to correctly receive the mouse click.</p> <p>Below is resulting style for the GroupBox. It is nearly identical to the default template for the control, except for the Border element named 'Header', which is now the last child of the Grid, rather than the second.</p> <pre><code>&lt;BorderGapMaskConverter x:Key="BorderGapMaskConverter"/&gt; &lt;Style x:Key="GroupBoxStyle1" TargetType="{x:Type GroupBox}"&gt; &lt;Setter Property="BorderBrush" Value="#D5DFE5"/&gt; &lt;Setter Property="BorderThickness" Value="1"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type GroupBox}"&gt; &lt;Grid SnapsToDevicePixels="true"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="6"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="6"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="6"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Border Grid.Column="0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"/&gt; &lt;ContentPresenter Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2"/&gt; &lt;Border Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"&gt; &lt;Border.OpacityMask&gt; &lt;MultiBinding Converter="{StaticResource BorderGapMaskConverter}" ConverterParameter="7"&gt; &lt;Binding Path="ActualWidth" ElementName="Header"/&gt; &lt;Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/&gt; &lt;Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/&gt; &lt;/MultiBinding&gt; &lt;/Border.OpacityMask&gt; &lt;Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3"&gt; &lt;Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/&gt; &lt;/Border&gt; &lt;/Border&gt; &lt;Border x:Name="Header" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" Padding="3,1,3,0"&gt; &lt;ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" ContentSource="Header" RecognizesAccessKey="True"/&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre>
<p>If you change the GroupBox's BorderBrush, it works!</p> <pre><code>&lt;GroupBox BorderBrush="{x:Null}"&gt; </code></pre> <p>I know this defeats the objective but it does prove where the problem lies!</p>
18,324
<p>I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python <code>SimpleHTTPServer.SimpleHTTPRequestHandler</code>?</p> <p>A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. <a href="http://msdl.cs.mcgill.ca/people/julien/04Ajax" rel="noreferrer">here</a>), but so far I could not come up with a truly minimal one.</p> <p>In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).</p>
<p>O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions.</p> <p>the python server file:</p> <pre><code>import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE = 'frontend.html' PORT = 8080 class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """The test example handler.""" def do_POST(self): """Handle a post request by returning the square of the number.""" length = int(self.headers.getheader('content-length')) data_string = self.rfile.read(length) try: result = int(data_string) ** 2 except: result = 'error' self.wfile.write(result) def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" server_address = ("", PORT) server = BaseHTTPServer.HTTPServer(server_address, TestHandler) server.serve_forever() if __name__ == "__main__": open_browser() start_server() </code></pre> <p>...and the HTML file (I call it 'frontend.html', unfortunately the name has to appear in the JavaScript code as well):</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;AJAX test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function xml_http_post(url, data, callback) { var req = false; try { // Firefox, Opera 8.0+, Safari req = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } req.open("POST", url, true); req.onreadystatechange = function() { if (req.readyState == 4) { callback(req); } } req.send(data); } function test_button() { var data = document.test_form.test_text.value; xml_http_post("frontend.html", data, test_handle) } function test_handle(req) { var elem = document.getElementById('test_result') elem.innerHTML = req.responseText } &lt;/script&gt; &lt;form name=test_form&gt; sqr( &lt;input type="text" name="test_text" value="0" size="4"&gt; ) = &lt;span id="test_result"&gt;0&lt;/span&gt; &lt;input type=button onClick="test_button();" value="start" title="start"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Of course it would be much more convenient to use <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery</a> for the XML request, but in the interest of simplicity I'll leave it like that.</p> <p>Finally an alternative implementation using WSGI (unfortunately I didn't see a way to fall back on the standard file-serving handler if the request is not a POST):</p> <pre><code>import threading import webbrowser from wsgiref.simple_server import make_server FILE = 'frontend.html' PORT = 8080 def test_app(environ, start_response): if environ['REQUEST_METHOD'] == 'POST': try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(int(request_body) ** 2) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open(FILE).read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" httpd = make_server("", PORT, test_app) httpd.serve_forever() if __name__ == "__main__": open_browser() start_server() </code></pre>
<p>Thanks for a very intuitive example @nikow I was trying to follow your example, but did get an error:</p> <p>(process:10281): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed</p> <p>I modified your code to meet my needs.</p> <pre><code>webbrowser.open('file:///home/jon/workspace/webpages/frontend_example/%s' % FILE) // skipped the port part httpd = make_server("", 8080, test_app) // hardcoded it here. </code></pre> <p>does my html file has to be put on the webserver ? I have not put it there yet !.</p>
43,701
<p>How can you <a href="http://en.wikipedia.org/wiki/Diff" rel="noreferrer">diff</a> two pipelines without using temporary files in Bash? Say you have two command pipelines:</p> <pre><code>foo | bar baz | quux </code></pre> <p>And you want to find the <code>diff</code> in their outputs. One solution would obviously be to:</p> <pre><code>foo | bar &gt; /tmp/a baz | quux &gt; /tmp/b diff /tmp/a /tmp/b </code></pre> <p>Is it possible to do so without the use of temporary files in Bash? You can get rid of one temporary file by piping in one of the pipelines to diff:</p> <pre><code>foo | bar &gt; /tmp/a baz | quux | diff /tmp/a - </code></pre> <p>But you can't pipe both pipelines into diff simultaneously (not in any obvious manner, at least). Is there some clever trick involving <code>/dev/fd</code> to do this without using temporary files?</p>
<p>A one-line with 2 tmp files (not what you want) would be:</p> <pre><code> foo | bar &gt; file1.txt &amp;&amp; baz | quux &gt; file2.txt &amp;&amp; diff file1.txt file2.txt </code></pre> <p>With <strong>bash</strong>, you might try though:</p> <pre><code> diff &lt;(foo | bar) &lt;(baz | quux) foo | bar | diff - &lt;(baz | quux) # or only use process substitution once </code></pre> <p>The 2nd version will more clearly remind you which input was which, by showing<br> <code>-- /dev/stdin</code> vs. <code>++ /dev/fd/63</code> or something, instead of two numbered fds.</p> <hr> <p>Not even a named pipe will appear in the filesystem, at least on OSes where bash can implement process substitution by using filenames like <code>/dev/fd/63</code> to get a filename that the command can open and read from to actually read from an already-open file descriptor that bash set up before exec'ing the command. (i.e. bash uses <code>pipe(2)</code> before fork, and then <code>dup2</code> to redirect from the output of <code>quux</code> to an input file descriptor for <code>diff</code>, on fd 63.)</p> <p>On a system with no "magical" <code>/dev/fd</code> or <code>/proc/self/fd</code>, bash might use named pipes to implement process substitution, but it would at least manage them itself, unlike temporary files, and your data wouldn't be written to the filesystem.</p> <p>You can check how bash implements process substitution with <code>echo &lt;(true)</code> to print the filename instead of reading from it. It prints <code>/dev/fd/63</code> on a typical Linux system. Or for more details on exactly what system calls bash uses, this command on a Linux system will trace file and file-descriptor system calls</p> <pre><code>strace -f -efile,desc,clone,execve bash -c '/bin/true | diff -u - &lt;(/bin/true)' </code></pre> <hr> <p><strong>Without bash, you could make a named pipe</strong>. Use <code>-</code> to tell <code>diff</code> to read one input from STDIN, and use the named pipe as the other:</p> <pre><code>mkfifo file1_pipe.txt foo|bar &gt; file1_pipe.txt &amp;&amp; baz | quux | diff file1_pipe.txt - &amp;&amp; rm file1_pipe.txt </code></pre> <hr> <p>Note that you can only pipe <em>one output</em> to <em>multiple inputs</em> with the tee command:</p> <pre><code>ls *.txt | tee /dev/tty txtlist.txt </code></pre> <p>The above command displays the output of ls *.txt to the terminal and outputs it to the text file txtlist.txt.</p> <p>But with process substitution, you can use <code>tee</code> to feed the same data into multiple pipelines:</p> <pre><code>cat *.txt | tee &gt;(foo | bar &gt; result1.txt) &gt;(baz | quux &gt; result2.txt) | foobar </code></pre>
<p>Some people arriving at this page might be looking for a line-by-line diff, for which <code>comm</code> or <code>grep -f</code> should be used instead.</p> <p>One thing to point out is that, in all of the answer's examples, the diffs won't actually start until both streams have finished. Test this with e.g.: </p> <pre><code>comm -23 &lt;(seq 100 | sort) &lt;(seq 10 20 &amp;&amp; sleep 5 &amp;&amp; seq 20 30 | sort) </code></pre> <p>If this is an issue, you could try <a href="https://github.com/MarianoGappa/sd" rel="noreferrer">sd</a> (stream diff), which doesn't require sorting (like <code>comm</code> does) nor process substitution like the above examples, is orders or magnitude faster than <code>grep -f</code> and supports infinite streams.</p> <p>The test example I propose would be written like this in <code>sd</code>:</p> <pre><code>seq 100 | sd 'seq 10 20 &amp;&amp; sleep 5 &amp;&amp; seq 20 30' </code></pre> <p>But the difference is that <code>seq 100</code> would be diffed with <code>seq 10</code> right away. Note that, if one of the streams is a <code>tail -f</code>, the diff cannot be done with process substitution.</p> <p>Here's a <a href="http://marianogappa.github.io/software/2016/07/30/diffing-streams-on-the-terminal/" rel="noreferrer">blogpost</a> I wrote about diffing streams on the terminal, which introduces <code>sd</code>.</p>
44,955
<p>There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:</p> <pre><code>bool MyFunction( char* buffer, int* bufferSize ) </code></pre> <p>I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is <strong>best done in PowerShell 1.0</strong>. The fact that the function needing to be called <strong><em>is using pointers</em></strong> could affect the solution (yet I don't really know).</p> <p>So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?</p> <p><strong>Remember for PowerShell 1.0.</strong></p>
<p>To call unmanaged code from Powershell, use the Invoke-Win32 function created by Lee Holmes. You can find the source <a href="http://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx" rel="noreferrer">here</a>. There you can see an example of how to call a function that has pointers, but a more trivial usage would be: </p> <pre><code>PS C:\&gt; Invoke-Win32 "msvcrt.dll" ([Int32]) "puts" ([String]) "Test" Test 0 </code></pre>
<p>There isn't any mechanism in PowerShell 1.0 to directly call Win32 API's. You could of course write a C# or VB.NET helper class to do this for you and call that from PowerShell.</p> <p>Update: Take a look at -</p> <p><a href="http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx</a> <a href="http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx" rel="nofollow noreferrer">http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx</a></p>
17,217
<p>Can I simulate in C#/C++ code <kbd>Control</kbd>+<kbd>Alt</kbd>+<kbd>Delete</kbd> sequence in Vista? When UAC enabled/disabled? How it is done in XP?</p> <p>Can you provide a code sample that works in Vista?</p>
<p>Existing code to simulate the Secure Attention Sequence (SAS), which most people refer to as control alt delete or ctrl-alt-del, no longer works in Windows Vista. It seems that Microsoft offers a library that exports a function called SimulateSAS(). It is not public and one is supposed to request it by sending a mail to saslib@microsoft.com.</p> <p>There is a <a href="http://www.remkoweijnen.nl/blog/2009/03/30/sending-ctrl-alt-del-simulate-sas-in-windows-vista/" rel="noreferrer">similar library</a> available with the following features: </p> <ul> <li>Works both with and without User Account Control (UAC)</li> <li>Supports current, console and any Terminal Server session</li> <li>Does not need a driver</li> <li>The calling application does not need to be signed or have a special manifest</li> <li>Supports multiple programming languages</li> </ul> <p>Please note that this library is not free. Meanwhile you can contact <a href="http://mailto:info@simulatesas.com" rel="noreferrer">info@simulatesas.com</a> if you are interested in it.</p>
<p>PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT | MOD_CONTROL, VK_DELETE));</p> <p>You get PostMessage from the user32 dll</p> <p>edit: <a href="http://www.codeproject.com/KB/system/alt_control_delete.aspx?fid=14112&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2634100&amp;fr=26" rel="nofollow noreferrer">CodeProject article that has code for it</a></p> <p>edit: There is some <a href="http://www.uvnc.com/vista/" rel="nofollow noreferrer">discussion from VNC</a> on why that won't work in Vista and how to set up UAC to allow it.</p>
14,885
<p>I am using the mootools based Rokbox plugin, on one of my sites, and I can't figure out how to close it with javascript.</p> <p>I triggered the click event on the close button, but that did not work.</p> <p>I found the code in the rokbox source that is used to add the click listener</p> <pre><code>this.closeButton.addEvent('click',function(e){new Event(e).stop();self.swtch=false;self.close(e)}); </code></pre> <p>but since it is minified i cannot find what "this" refers to</p>
<p>The <code>this</code> likely refers to the rokbox instance; I don't think you need to worry about it, you're interested in the code that runs on the click event. The salient part looks to be the following:</p> <pre><code>self.swtch=false; self.close(e); </code></pre> <p><code>self</code> most likely refers to the rokbox instance, again, so assuming you instantiate it with something like </p> <pre><code>var rokbox = new RokBox(...); </code></pre> <p>you should be able to just call</p> <pre><code>rokbox.close(); </code></pre> <p>and have it close. I haven't looked at rokbox source, so no guarantees, and not quite sure what the <code>swtch=false</code> does, so you probably will need to experiment a bit.</p>
<p>For the current rokbox and mootools 1.12, the command is</p> <pre><code>window.parent.rokbox.close(null) </code></pre> <p>it took forever to come up with this. By the way, this is to close the rokbox from the page that's loaded in the rokbox, by clicking a regular button instead of the 'x' for instance. Also, to add to what Aeon wrote, the rokbox is automatically created so it's unnecessary to instantiate it.</p>
11,936
<p>I have a string(char*), and i need to find its underlying datatype such as int, float, double, short, long, or just a character array containing alphabets with or with out digits(like varchar in SQL). For ex: </p> <pre><code> char* str1 = "12312" char* str2 = "231.342" char* str3 = "234234243234" char* str4 = "4323434.2432342" char* str5 = "i contain only alphabets" </code></pre> <p><strong>Given these strings, i need to find that the first string is of type int and typecast it to an int, and so on</strong> ex:</p> <pre><code>int no1 = atoi(str1) float no2 = atof(str2) long no3 = atol(str3) double no4 = strtod(str4) char* varchar1 = strdup(str5) </code></pre> <hr> <p>Clarifying a bit more... </p> <p>I have a string and its contents could be alphabets and/or digits and/or special characters. Right now, I am able to parse string and </p> <ol> <li>Identify if it contains only digits,<br> Here i convert the string into short or int or long, based on best fit. ( <strong>How do i know if the string can be converted to an short int or long?</strong>) </li> <li>Only alphabets, leave it as a string. </li> <li>Digits with a single decimal point.<br> Here i need to convert the string into float or double ( <strong>Same question here</strong>)</li> <li>other. leave it as a string</li> </ol>
<p>In C (not in C++), I would use a combination of strtod/strol and max values from &lt;limits.h&gt; and &lt;float.h&gt;:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;limits.h&gt; #include &lt;float.h&gt; /* Now, we know the following values: INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, CHAR_MAX, CHAR_MIN, etc. */ typedef union tagMyUnion { char TChar_ ; short TShort_ ; long TLong_ ; double TDouble_ ; } MyUnion ; typedef enum tagMyEnum { TChar, TShort, TLong, TDouble, TNaN } MyEnum ; void whatIsTheValue(const char * string_, MyEnum * enum_, MyUnion * union_) { char * endptr ; long lValue ; double dValue ; *enum_ = TNaN ; /* integer value */ lValue = strtol(string_, &amp;endptr, 10) ; if(*endptr == 0) /* It is an integer value ! */ { if((lValue &gt;= CHAR_MIN) &amp;&amp; (lValue &lt;= CHAR_MAX)) /* is it a char ? */ { *enum_ = TChar ; union_-&gt;TChar_ = (char) lValue ; } else if((lValue &gt;= SHRT_MIN) &amp;&amp; (lValue &lt;= SHRT_MAX)) /* is it a short ? */ { *enum_ = TShort ; union_-&gt;TShort_ = (short) lValue ; } else if((lValue &gt;= LONG_MIN) &amp;&amp; (lValue &lt;= LONG_MAX)) /* is it a long ? */ { *enum_ = TLong ; union_-&gt;TLong_ = (long) lValue ; } return ; } /* real value */ dValue = strtod(string_, &amp;endptr) ; if(*endptr == 0) /* It is an real value ! */ { if((dValue &gt;= -DBL_MAX) &amp;&amp; (dValue &lt;= DBL_MAX)) /* is it a double ? */ { *enum_ = TDouble ; union_-&gt;TDouble_ = (double) dValue ; } return ; } return ; } void studyValue(const char * string_) { MyEnum enum_ ; MyUnion union_ ; whatIsTheValue(string_, &amp;enum_, &amp;union_) ; switch(enum_) { case TChar : printf("It is a char : %li\n", (long) union_.TChar_) ; break ; case TShort : printf("It is a short : %li\n", (long) union_.TShort_) ; break ; case TLong : printf("It is a long : %li\n", (long) union_.TLong_) ; break ; case TDouble : printf("It is a double : %f\n", (double) union_.TDouble_) ; break ; case TNaN : printf("It is a not a number : %s\n", string_) ; break ; default : printf("I really don't know : %s\n", string_) ; break ; } } int main(int argc, char **argv) { studyValue("25") ; studyValue("-25") ; studyValue("30000") ; studyValue("-30000") ; studyValue("300000") ; studyValue("-300000") ; studyValue("25.5") ; studyValue("-25.5") ; studyValue("25555555.55555555") ; studyValue("-25555555.55555555") ; studyValue("Hello World") ; studyValue("555-55-55") ; return 0; } </code></pre> <p>Which results in the following:</p> <pre><code>[25] is a char : 25 [-25] is a char : -25 [30000] is a short : 30000 [-30000] is a short : -30000 [300000] is a long : 300000 [-300000] is a long : -300000 [25.5] is a double : 25.500000 [-25.5] is a double : -25.500000 [25555555.55555555] is a double : 25555555.555556 [-25555555.55555555] is a double : -25555555.555556 [Hello World] is a not a number [555-55-55] is a not a number </code></pre> <p>Sorry for my rusty C.</p> <p>:-)</p> <p>So, in substance, you after the call of whatIsTheValue, you retrieve the type through the MyEnum enum, and then, according to the value in this enum, retrieve the right value, correctly typed, from the union MyUnion.</p> <p>Note that finding if the number is a double or a float is a bit more complicated because the difference seems to be in the precision, i.e. is your number representable in a double, or in float. A most "decimal real" numbers are not exactly representable into a double, I would not bother.</p> <p>Note, too, that there is a catch, as 25.0 could be both real and an integer number. My comparing "dValue == (double)(long)dValue", I guess you should know if is an integer, again, not taking into account the usual precision problems coming witb binary real numbers used by computers.</p>
<p>First of all, you should decide which representatins you want to recognize. For example, is 0xBAC0 an unsigned short expressed in hex? Same goes for 010 (in octal) and 1E-2 (for 0,01).</p> <p>Once you have decided on the represantation, you can use regular expressions to determine the general forms. For example:</p> <ul> <li><strong><code>-?\d*.\d*([eE]?[+-]?\d*.\d*)?</code></strong> is a floating point number (almost, it accept weird things like <code>.e-.</code> you should define the regex that is most appropriate for you)</li> <li><strong><code>-?\d+</code></strong> is an integer</li> <li><strong><code>0x[0-9A-Fa-f]+</code></strong> is an hex constant</li> </ul> <p>and so on. If you are not using a regex library you will have to write a small parser for those represantion from scratch.</p> <p>Now you can convert it to the largest possible type (e.g. <code>long long</code> for integers, double for floating pointers) and then use the values in <code>limits.h</code> to see if the value would fit in a smaller type.</p> <p>For example if the integer is less than <code>SHRT_MAX</code> you can assume it's a <code>short</code>.</p> <p>You might also have to take arbitrary decisions, for example 54321 can only be an <code>unsigned short</code> but 12345 could be a <code>signed short</code> or an <code>unsigned short</code>.</p>
23,779
<p>I'm updating an old project &amp; my version of xdoclet complains about my Java 1.5 annontations (ArrayList data = ....) when parsing for Hibernate (hibernate3) tags.</p> <p>So my question is this...</p> <p>Is there a fix for Xdoclet 1.2.3, or should I look to move to Xdoclet2?</p> <p>I've already started moving some of the code over, but xdoclet2 doesn't seem to offer the same level of configuration for hibenate, such as excludedtags. I could be wrong on this though.</p> <p>What do you lot think?</p> <p>Jeff Porter</p>
<p>I would definitively lose xdoclet in favor of JPA annotations. You can get about the same functionality from Hibernate using JPA annotations.</p>
<p>To answer the original question: I had a similar (the same?) problem, which was caused by the version of xjavadoc distributed with xdoclet 1.2.3.</p> <p>XJavadoc provided a snapshot release that fixes the compatibility. Replace the jar from the xdoclet-release with the one you can find as an attachment to <a href="http://jira.codehaus.org/browse/MAVENUPLOAD-1399" rel="nofollow noreferrer">this JIRA issue</a> (couldn't find a direct URL), and things should be better...</p>
27,240
<p>I'm trying to consume Sharepoint webservices with ruby. I've basically given up trying to authenticate with NTLM and temporarily changed the Sharepoint server to use basic authentication. I've been successful getting a WSDL using soap4r but still cannot authenticate when attempting to use an actual web service call.</p> <p>Has anyone had any experience getting ruby and Sharepoint to talk?</p>
<p>I'm a total newb. But after a lot of time and with some help from more experience coders, I was able to get ruby working with Sharepoint 2010. The code below requires the 'ntlm/mechanize' gem.</p> <p>I've been able to download the sharepoint xml from lists specified (below) using the List GUID and the List View GUID.</p> <p>Edit (May 23, 2011). I should have pointed out that this code requires the ruby-ntlm gem. Here's a decent link that should help. This definitely works.</p> <p><a href="http://rubydoc.info/gems/ruby-ntlm/0.0.1/file/README.markdown" rel="noreferrer">http://rubydoc.info/gems/ruby-ntlm/0.0.1/file/README.markdown</a></p> <pre><code>agent = Mechanize.new agent.auth('domain\\USERNAME', 'PASSWORD') page = agent.get('http://URL/DIRECTORY/SITE/LIST/_vti_bin/owssvr.dll?Cmd=Display&amp;List={LIST_GUID}&amp;View={VIEW_GUID}&amp;XMLDATA=TRUE') </code></pre>
<p>This may not help but micorosoft just release the toolkit for Sharepoint and WSRP, <a href="http://blogs.msdn.com/sharepoint/archive/2008/12/15/announcing-the-wsrp-toolkit-for-sharepoint.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sharepoint/archive/2008/12/15/announcing-the-wsrp-toolkit-for-sharepoint.aspx</a>, since RoR supports that standard it may provide an easier method of getting the data.</p>
48,671
<p>I am <a href="https://stackoverflow.com/questions/211260/perl-extract-text-then-save&lt;br">searching</a> for HF50(HF$HF) for example in "MyFile.txt" so that the extracted data must save to "save.txt". The data on "save.txt" now extracted again and fill the parameters and output on my table. But when I tried the code, I've got no output and "save.txt" is blank.?</p> <p>Var $HF is not recognized whatever I type. Please help.</p> <pre><code>#! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my ($file,$line,$tester,$HF,$keyword); my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); my $keyWord=param('keyword'); $HF=$keyWord; my $infile='MyFile.txt'; my $outfile='save.txt'; open (my $inhandle, '&lt;',$infile) or die "Can't open $infile:$!"; open (my $outhandle, '&gt;', $outfile) or die "Can't open $outfile:$!"; while (my $line=&lt;$inhandle&gt;){ if ($line=~ m/HF$HF/i) { print {$outhandle}$line; print $line; print "&lt;HTML&gt;"; print "&lt;head&gt;"; print "&lt;body bgcolor='#4682B4'&gt;"; print "&lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt;"; print "&lt;div align='left'&gt;"; print "&lt;FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'&gt;"; print "&lt;b&gt;SEACRH:&lt;/b&gt;"; print "&lt;INPUT TYPE='text' NAME='rec' SIZE='12' MAXLENGHT='40'&gt;"; print "&lt;INPUT TYPE='submit' value='go'&gt;"; print "&lt;/form&gt;"; print "&lt;TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'&gt;"; print "&lt;TR&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER No.&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DATE&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE NAME&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TEST PROGRAM&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;LOADBOARD&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;CATEGORY&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 1&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 2&lt;/td&gt;"; print "&lt;/tr&gt;"; print "&lt;TR&gt;"; $file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;) { my @cells=($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f2&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f3&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f5&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f6&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f8&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f10&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f17&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f18&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f19&lt;/TD&gt;"; print "&lt;/tr&gt;"; } } } close F; print "&lt;/TABLE&gt;"; print "&lt;/body&gt;"; print "&lt;html&gt;"; </code></pre> <p><br></p> <p>=<strong>MyFile.txt data</strong>=<br> 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br> 2,HF60,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br> 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br></p>
<p>Are you running this as a CGI script? In that case, you probably don't have permission to open a file for writing. Did you check the error log to see if your message from <code>die</code> is in there?</p> <p>You might want to check out <a href="http://brian-d-foy.cvs.sourceforge.net/*checkout*/brian-d-foy/CGI_MetaFAQ/troubleshooting_CGI.html" rel="nofollow noreferrer">Troubleshooting Perl CGI scripts</a>. Go through all of the steps without skipping any. When you get stuck, you have most of the imformation you need to help us help you.</p> <p>Good luck, :)</p>
<p>First, Perl's output is by nature buffered. So, unless you use some explicit method, there's no guarantee that the physical file will have anything to read. As somebody mentioned, you'll have to flush the output somehow. My comments are below in the code. (You could also do this by closing the output file and opening it in <em>append</em> mode after you've read from it.)</p> <p>Second, it doesn't seem like you want to do what it looks like you want to do. If everything was flushed perfectly to the file, you're requesting an html header <em>per input line</em>. So as I added lines into the input, it printed out that many search boxes. I don't expect that is what you wanted. </p> <p>Here's a more <em>perl-ified</em> code: </p> <pre><code>use CGI qw(:standard); use IO::File; use strict; use warnings; my ($file,$line,$HF); #,$tester,$HF,$keyword); # don't pollute -&gt; my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10 # ,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); # my $keyWord=param('keyword'); &lt;-- if you're not going to do anything with $keyWord $HF=param('keyword'); # &lt;- assign it to the variable you're going to use my $infile='MyFile.txt'; my $outfile='save.txt'; open (my $inhandle, '&lt;',$infile) or die "Can't open $infile:$!"; open (my $outhandle, '&gt;', $outfile) or die "Can't open $outfile:$!"; # this would flush -&gt; my $outhandle = IO::File-&gt;new( "&gt;$outfile" ); print q{Content-type:text/html &lt;HTML&gt; &lt;head&gt; &lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt; &lt;style type="text/css"&gt; .header { background-color : #0f0; font-size : 12pt } .detail { background-color : #ADD8E6; font-size : 12pt } &lt;/style&gt; &lt;/head&gt; &lt;body bgcolor='#4682B4'&gt; &lt;div align='left'&gt; &lt;FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'&gt; &lt;b&gt;SEACRH:&lt;/b&gt; &lt;input type='text' name='rec' size='12' maxlenght='40'&gt; &lt;input type='submit' value='go'&gt; &lt;/form&gt; &lt;table cellpadding='1' cellspacing='1' border='1' bordercolor=black width='100%'&gt; &lt;tr&gt; &lt;td class="header" width='11%'&gt;TESTER No.&lt;/td&gt; &lt;td class="header" width='10%'&gt;DATE&lt;/td&gt; &lt;td class="header" width='11%'&gt;DEVICE NAME&lt;/td&gt; &lt;td class="header" &gt;TEST PROGRAM&lt;/td&gt; &lt;td class="header" width='10%'&gt;SMSLOT&lt;/td&gt; &lt;td class="header" width='12%'&gt;LOADBOARD&lt;/td&gt; &lt;td class="header" width='10%'&gt;CATEGORY&lt;/td&gt; &lt;td class="header" width='13%'&gt;ROOT CAUSE 1&lt;/td&gt; &lt;td class="header" width='13%'&gt;ROOT CAUSE 2&lt;/td&gt; &lt;/tr&gt; }; my $hf_str = ",HF$HF,"; # OO -&gt; $outhandle-&gt;autoflush(); &lt;- set autoflush while (my $line=&lt;$inhandle&gt;){ next unless index( $line, $hf_str ) &gt; -1; # OO -&gt; $outhandle-&gt;print( $line ); # $outhandle-&gt;flush(); &lt;- if autoflush not set, do it manually print *{$outhandle} $line; print "&lt;tr&gt;" , ( map { qq{&lt;td class="detail"&gt;$_&lt;/td&gt;} } split ',', $line ) , "&lt;/tr&gt;\n" ; } print q{ &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; }; </code></pre>
26,762
<p>I have a list box control:</p> <pre> <code> &lt;asp:ListBox runat="server" id="lbox" autoPostBack="true" /> </code> </pre> <p>The code behind resembles:</p> <pre> <code> private void Page_Load(object sender, System.EventArgs e) { lbox.SelectedIndexChanged+=new EventHandler(lbox_SelectedIndexChanged); if(!Page.IsPostBack) { LoadData(); } } private LoadData() { lbox.DataSource = foo(); lbox.DataBind(); } protected void lboxScorecard_SelectedIndexChanged(object sender, EventArgs e) { int index = (sender as ListBox).selectedIndex; } </code> </pre> <p>My problem is that when my page receives a post back (when a user makes a selection in the listbox), the selection always "jumps" to the first item in the listbox, so that the index variable in my callback function is always 0.</p> <p>Seems like this may be a viewstate problem? How can I fix it so that the selection index remains through the postback?</p> <p>There is no ajax going on, this is .NET 1.0.</p> <p>Thanks.</p> <p><strong>EDIT 1</strong> JohnIdol has gotten me a step closer, If I switch the datasource from my original DataTable to an ArrayList, then everything work properly...what would cause this?</p> <p><strong>Edit 2</strong> It turns out that my DataTable had multiple values that were the same, so that the indexes were treated as the same as all items with the same value...thanks to those who helped!</p>
<p>What's the output of the foo() function call?</p> <p>Populating manually the list box you can set indexes to whatever you want (all 0 for example) - so the same thing can happen setting a given dataSource under certain circumstances (one that specifies indexes I suppose). If all the item indexes are 0 the result is that the SelectedIndexChanged event is not raised (index does not change!) and everything is messed up: on post-back selection will go back to the first item in the list.</p> <p>This would explain it - I cannot think of anything else - it is working fine for me on .NET 2.0 I am using an ArrayList with strings to populate the listBox. </p> <p>The only way I can reproduce your issue is setting all indexes to 0.</p> <p>I'd say add a watch to the ListBox and check the indexes at runtime to make sure they're not all zeroes.</p>
<p>I dont know if it makes a difference or not, but i generally attach my controls to events on the front page rather than in the codebehind. In your example i would have done:</p> <pre><code>&lt;asp:ListBox runat="server" id="lbox" autoPostBack="true" OnSelectedIndexChanged="lboxScorecard_SelectedIndexChanged" /&gt; </code></pre> <p>Other than that, i would verify that the ViewState is enabled. ViewState can be turned of at the control, page, &amp; even site level.</p>
43,938
<p>I have an MPI program which compiles and runs, but I would like to step through it to make sure nothing bizarre is happening. Ideally, I would like a simple way to attach GDB to any particular process, but I'm not really sure whether that's possible or how to do it. An alternative would be having each process write debug output to a separate log file, but this doesn't really give the same freedom as a debugger.</p> <p>Are there better approaches? How do you debug MPI programs?</p>
<p>As someone else said, <a href="https://www.roguewave.com/products-services/totalview" rel="noreferrer">TotalView</a> is the standard for this. But it will cost you an arm and a leg.</p> <p>The OpenMPI site has a great <a href="http://www.open-mpi.org/faq/?category=debugging" rel="noreferrer">FAQ on MPI debugging</a>. Item #6 in the FAQ describes how to attach GDB to MPI processes. Read the whole thing, there are some great tips.</p> <p>If you find that you have far too many processes to keep track of, though, check out <a href="http://www.paradyn.org/STAT/" rel="noreferrer">Stack Trace Analysis Tool (STAT)</a>. We use this at Livermore to collect stack traces from potentially hundreds of thousands of running processes and to represent them intelligently to users. It's not a full-featured debugger (a full-featured debugger would never scale to 208k cores), but it will tell you which groups of processes are doing the same thing. You can then step through a representative from each group in a standard debugger.</p>
<p>Another solution is to run your code within SMPI, the simulated MPI. That's an open source project in which I'm involved. Every MPI rank will be converted into threads of the same UNIX process. You can then easily use gdb to step the MPI ranks.</p> <p>SMPI proposes other advantages to the study of MPI applications: clairevoyance (you can observe every parts of the system), reproducibility (several runs lead to the exact same behavior unless you specify so), absence of heisenbugs (as the simulated platform is kept different from the host one), etc.</p> <p>For more information, see <a href="http://simgrid.gforge.inria.fr/tutorials/simgrid-smpi-101.pdf" rel="nofollow noreferrer">this presentation</a>, or that <a href="https://stackoverflow.com/questions/2299147/running-mpi-code-in-my-laptop">related answer</a>.</p>
42,669
<p>Say you had to develop a web-based application that needs to be able to read the contents of a .NET DLL, and from that, populate the local database with a list of all the namespaces, classes, etc.</p> <p>It has to also do the same thing with Java JAR files.</p> <p>Are there limitations on what language I could use to develop this?</p> <p>I'm leaning toward .NET, but I might consider another language/framework if it's more suitable. I'm basic-to-intermediate-level with PHP.</p>
<p>I think that the "get this information from a DLL" and "get this information from a JAR file" activities would have nothing in common with each other, or with the web application to display the information. Surely there already exist tools to dump this information.</p> <p>You probably ought to write the Web part of this in whatever language you're comfortable in, and execute a pre-existiong tool to do the extraction task...</p>
<p>I would wonder if you would want that? I mean, firstly people write a lot of code that isn't really that good looking and second, some can run obfuscation on there code, what says that you could "get the content" and understand that then?</p> <p>But sure, there are tools out there that can read dll's and get the content you want for sure.</p>
34,063
<p>Here's the situation: I'm developing a simple application with the following structure:</p> <ul> <li>FormMain (startup point)</li> <li>FormNotification</li> <li>CompleFunctions</li> </ul> <p>Right?</p> <p>Well, in <strong>FormMain</strong> I have the following function:</p> <pre><code>private void DoItInNewThread(ParameterizedThreadStart pParameterizedThreadStart, object pParameters, ThreadPriority pThreadPriority) { Thread oThread = new Thread(pParameterizedThreadStart); oThread.CurrentUICulture = Settings.Instance.Language; oThread.IsBackground = true; oThread.Priority = pThreadPriority; oThread.Name = "μRemote: Background operation"; oThread.Start(pParameters); } </code></pre> <p>So, everytime that I need to call a time consuming method located on <strong>ComplexFunctions</strong> I do the following:</p> <pre><code>// This is FormMain.cs string strSomeParameter = "lala"; DoItInNewThread(new ParameterizedThreadStart(ComplexFunctions.DoSomething), strSomeParameter, ThreadPriority.Normal); </code></pre> <p>The other class, FormNotification, its a Form that display some information of the process to the user. This FormNotification could be called from FormMain or ComplexFunctions. Example:</p> <pre><code>// This is ComplexFunctions.cs public void DoSomething(string pSomeParameter) { // Imagine some time consuming task FormNotification formNotif = new FormNotification(); formNotif.Notify(); } </code></pre> <p>FormNotify has a timer, so, after 10 seconds closes the form. I'm not using formNotif.ShowDialog because I don't want to give focus to this Form. You could check <a href="https://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c">this link</a> to see what I'm doing in Notify.</p> <p>Ok, here's the problem: When I call <strong>FormNotify</strong> from <strong>ComplexFunction</strong> which is called from another Thread in <strong>FormMain</strong> ... this <strong>FormNotify</strong> disappears after a few milliseconds. It's the same effect that when you do something like this:</p> <pre><code>using(FormSomething formSomething = new FormSomething) { formSomething.Show(); } </code></pre> <p><strong>How can avoid this?</strong></p> <p>These are possible solutions that I don't want to use:</p> <ul> <li>Using Thread.Sleep(10000) in FormNotify</li> <li>Using FormNotif.ShowDialog()</li> </ul> <p>This is a simplified scenario (FormNotify does some other fancy stuff that just stay for 10 seconds, but they are irrelevant to see the problem).</p> <p>Thanks for your time!!! And please, sorry my english.</p>
<p>Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.</p> <p>There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread.</p> <p>Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify.</p> <p>Fire the event from the worker thread when you want to show the notification. </p> <p>When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily while debugging. Note that illegal cross-thread calls will always raise an exception when an application is started outside the debugger.</p> <p>Note: setting CheckForIllegalCrossThreadCalls to ture should only be done in DEBUGGIN SITUATIONS ONLY. Unpredicatable results will occur and you will wind up trying to chase bugs that you will have a difficuly tome finding.</p>
<p>Use the <strong>SetWindowPos</strong> API call to ensure that your notify form is the topmost window. This post explains how:</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html" rel="nofollow noreferrer">http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html</a></p>
19,411
<p>I've been exploring different strategies for running integration tests within some Nant build scripts. Typically a number of different scripts are chained in one monolithic build that has separate targets: staging (build a staging version, like build), build (just build the stuff), integration (build the stuff and run the integration tests). This works reasonably well, the build target takes about a third of the time to run as the integration target and it's not painfully long so I don't find myself disinclined to run it frequently.</p> <p>The integration target on the other hand takes long enough that I don't want to do it very often - ideally just before I'm ready to do a deploy. Does this seem like a reasonable strategy? IOW, am I doing it right?</p> <p>The plan is to eventually move this project to Continuous Integration. I'm new to the whole Continuous Integration thing but I think I understand the concept of "breaking the build" so I'm wondering what are some good practices to pick up in order to make the most of it? </p> <p>Any good sources of reading on this subject would be appreciated as well. Thanks!</p>
<p>Yes, you are on the right track. What you need to do now is to hook up your nant target to an automated process. I recommend using either Team City or Cruise Control for as your CI tool. Once you have your automated server setup you can run your build and unit tests on each check in (Continuous Integration). Your integration tests could then run at night or over the weekend since they typically take longer to run. If your integration tests are successful, you can then have a job that will deploy to some QA or other server.</p>
<p>See this related thread <a href="https://stackoverflow.com/questions/102902/what-is-a-good-ci-build-process#103759">What is a good CI build process?</a></p> <p>You are on the right track. If you're using a decent CI tool, you should be able to set each setup up as a separate project that triggers the next step in the chain... i.e. sucessfull build triggers tests which trigger deployment which triggers integration etc</p> <p>This way your ealiest "break" stops the line so to speak.</p> <p>We use CruiseControl to build, unit-test, configure and deploy, run integration tests and code coverage, run acceptance tests, and package for release. This is with a system of 8 or so web services, and a dozen or so databases, all with interralated configuration and deployment dependencies with across multiple environments with different configurations (anythin from single boxes to redundent boxes for each component)</p>
26,972
<p>I have a SQL Server 2005 database that I'm trying to access as a limited user account, using Windows authentication. I've got BUILTIN\Users added as a database user (before I did so, I couldn't even open the database). I'm working under the assumption that everybody is supposed to have permissions for the "public" role applied to them, so I didn't do anything with role assignment. Under tblFoo, I can use the SSMS Properties dialog (Permissions page) to add "public", then set explicit permissions. Among these is "Grant" for SELECT. But running</p> <pre><code>SELECT * from tblFoo; </code></pre> <p>as a limited (BUILTIN\Users) account gives me an error "Select permission denied on object 'tblFoo', database 'bar', schema 'dbo'". In the properties dialog, there's an "Effective Permissions button, but it's greyed out.</p> <p>Further, I tried creating a non-priv account called "UserTest", adding that at the server level, then mapping it down to the "bar" database. This let me add UserTest to the "Users or Roles" list, which let me run "Effective Permissions" for the account. No permissions are listed at all -- this doesn't seem right. The account must be in public, and public grants (among other things) Select on tblFoo, so why doesn't the UserTest account show an effective permission? I feel like I'm going a bit crazy here.</p> <p>ASIDE: I am aware that many people don't like using the "public" role to set permissions. This is just my tinkering time; in final design I'm sure we'll have several flexible (custom) database roles. I'm just trying to figure out the behavior I'm seeing, so please no "don't do that!" answers.</p> <p>UPDATE: Apparently I know just enough SQL Server to be a danger to myself and others. In setting permissions (as I said, "among others"), I had DENY CONTROL. When I set this permission, I think I tried to look up what it did, had a vague idea, and decided on DENY. I cannot currently recall why this seemed the thing to do, but it would appear that that was the reason I was getting permission failures. So I'm updating my question: can anyone explain the "CONTROL" permission, as it pertains to tables?</p>
<p>You only need to have SELECT rights. In raw SQL (see the "script" icon/button in your dialogue box), it's <code>GRANT SELECT ON dbo.tblFoo to public</code>. This is the only permission needed to view the data,</p> <p>In this case, the error message explicitly mentions "deny". "DENY" is a right in itself, so it mentions it,</p> <p>If you had no rights, you'd get the message (very approximately) "tblFoo does not exist or you do not have rights" </p> <p>"DENY CONTROL" is mentioned <a href="http://msdn.microsoft.com/en-us/library/ms191291(SQL.90).aspx" rel="nofollow noreferrer">here</a>. In this case, you denied <em>all</em> rights to the public role.</p> <blockquote> <p>The grantee effectively has all defined permissions on the securable</p> </blockquote>
<p>Assuming "UserTest" is a domain user account, connect as a member of the sysadmin role and run</p> <pre><code>EXEC MASTER.dbo.xp_logininfo 'Domain\UserTest', 'all' </code></pre> <p>(substituting your domain name for "Domain")</p> <p>this will display the Windows groups etc. that the account is inheriting security permissions from and the level of access, e.g. you would expect to see something like:</p> <pre><code>account name type privilege mapped login name permission path domain\usertest user user domain\usertest BUILTIN\Users </code></pre> <p>This will help troubleshoot where the account is inheriting permissions from, e.g. which Windows groups it is part of that have permissions to the database. If this all looks OK then I would follow your own advice and not mess with the public role.</p> <ul> <li>Create a database role in your database</li> <li>Assign explicit permissions for that role</li> <li>Create a server login for your user account</li> <li>Open the server login, go to the User Mapping section, click on the database and select the database role you created</li> </ul>
48,333
<p>Given:</p> <pre><code>FieldInfo field = &lt;some valid string field on type T&gt;; ParameterExpression targetExp = Expression.Parameter(typeof(T), "target"); ParameterExpression valueExp = Expression.Parameter(typeof(string), "value"); </code></pre> <p>How do I compile a lambda expression to set the field on the "target" parameter to "value"?</p>
<p><strong>.Net 4.0</strong> : now that there's <code>Expression.Assign</code>, this is easy to do:</p> <pre><code>FieldInfo field = typeof(T).GetField("fieldName"); ParameterExpression targetExp = Expression.Parameter(typeof(T), "target"); ParameterExpression valueExp = Expression.Parameter(typeof(string), "value"); // Expression.Property can be used here as well MemberExpression fieldExp = Expression.Field(targetExp, field); BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp); var setter = Expression.Lambda&lt;Action&lt;T, string&gt;&gt; (assignExp, targetExp, valueExp).Compile(); setter(subject, "new value"); </code></pre> <p><strong>.Net 3.5</strong> : you can't, you'll have to use System.Reflection.Emit instead:</p> <pre><code>class Program { class MyObject { public int MyField; } static Action&lt;T,TValue&gt; MakeSetter&lt;T,TValue&gt;(FieldInfo field) { DynamicMethod m = new DynamicMethod( "setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(Program)); ILGenerator cg = m.GetILGenerator(); // arg0.&lt;field&gt; = arg1 cg.Emit(OpCodes.Ldarg_0); cg.Emit(OpCodes.Ldarg_1); cg.Emit(OpCodes.Stfld, field); cg.Emit(OpCodes.Ret); return (Action&lt;T,TValue&gt;) m.CreateDelegate(typeof(Action&lt;T,TValue&gt;)); } static void Main() { FieldInfo f = typeof(MyObject).GetField("MyField"); Action&lt;MyObject,int&gt; setter = MakeSetter&lt;MyObject,int&gt;(f); var obj = new MyObject(); obj.MyField = 10; setter(obj, 42); Console.WriteLine(obj.MyField); Console.ReadLine(); } } </code></pre>
<p>I once made this class. Perhaps it helps:</p> <pre><code>public class GetterSetter&lt;EntityType,propType&gt; { private readonly Func&lt;EntityType, propType&gt; getter; private readonly Action&lt;EntityType, propType&gt; setter; private readonly string propertyName; private readonly Expression&lt;Func&lt;EntityType, propType&gt;&gt; propertyNameExpression; public EntityType Entity { get; set; } public GetterSetter(EntityType entity, Expression&lt;Func&lt;EntityType, propType&gt;&gt; property_NameExpression) { Entity = entity; propertyName = GetPropertyName(property_NameExpression); propertyNameExpression = property_NameExpression; //Create Getter getter = propertyNameExpression.Compile(); // Create Setter() MethodInfo method = typeof (EntityType).GetProperty(propertyName).GetSetMethod(); setter = (Action&lt;EntityType, propType&gt;) Delegate.CreateDelegate(typeof(Action&lt;EntityType, propType&gt;), method); } public propType Value { get { return getter(Entity); } set { setter(Entity, value); } } protected string GetPropertyName(LambdaExpression _propertyNameExpression) { var lambda = _propertyNameExpression as LambdaExpression; MemberExpression memberExpression; if (lambda.Body is UnaryExpression) { var unaryExpression = lambda.Body as UnaryExpression; memberExpression = unaryExpression.Operand as MemberExpression; } else { memberExpression = lambda.Body as MemberExpression; } var propertyInfo = memberExpression.Member as PropertyInfo; return propertyInfo.Name; } </code></pre> <p>test:</p> <pre><code>var gs = new GetterSetter&lt;OnOffElement,bool&gt;(new OnOffElement(), item =&gt; item.IsOn); gs.Value = true; var result = gs.Value; </code></pre>
41,637
<p>I have two models, Article and Post that both inherit from a base model called ContentBase.</p> <p>You can leave comments on both Articles and Posts, so I am using a Polymorphic Association between Comments and Article or Post.</p> <p>However, since both Article and Post inherit from ContentBase, the commentable_type field ends up being "ContentBase" for both and screws everything up.</p> <p>Is there a way to specify the commentable_type field in the has_many relationship in Article and Post?</p> <p>Edit:</p> <p>By "screws everything up" I mean if there is an Article with ID=1 and Post with ID=1 and I add a Comment with commentable_id=1, commentable_type=ContentBase, that comment will show up for both the Article and Post.</p> <p>Here's the code:</p> <pre><code>class Article &lt; BaseContent has_many :comments, :as =&gt; :commentable end class Post &lt; BaseContent has_many :comments, :as =&gt; :commentable end </code></pre> <p>and here's my Comment model:</p> <pre><code>class Comment &lt; ActiveRecord::Base belongs_to :commentable, :polymorphic =&gt; true end </code></pre>
<p>What's in the ContentBase class? Can you move that code into a module instead of using inheritance?</p> <pre><code>Module BaseContent def self.included(base) base.class_eval do validates_presence_of :somefield validates_length_of :someotherfield def my_method "hello" end end end end </code></pre>
<p>I don't think you want to do that. For polymorphic associations, you want the XXX_type field to be the base model class, not the actual class. I'm not exactly sure of the reason, but I believe it has to do with determining the table name to select from to get the polymorphic data.</p> <p>I think you need to look at Single Table Inheritance, which is what ActiveRecord uses for storing derived classes in the database. It assumes that since Article and Post are subclasses of ContentBase, they will all be in the same table ("content_bases" by default). If that's the case, you'll never have an Article with ID=1 and a Post with ID=1.</p> <p>A few references:</p> <ul> <li><a href="http://www.juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/" rel="nofollow noreferrer">Rails Single Table Inheritance | Juixe Technow</a> </li> <li><a href="http://wiki.rubyonrails.org/rails/pages/singletableinheritance" rel="nofollow noreferrer">Single Table Inheritance in Ruby on Rails</a></li> </ul>
30,663
<p>I have an .Net Froms application that displays web pages through a WebBrowser control.</p> <p>Is there anyway that I can detect if the control shows a '<em>Page not found</em>' or '<em>Cannot display webpage</em>' error? There doesn't seem to be any error event handlers.</p>
<p>The WebBrowser windows forms control is wrapper around Internet Explorer and it doesn't expose all the functionality of the underlying ActiveX control and particularly the NavigateError event. Here's a workaround:</p> <p>First add reference to SHDocVw.dll to your project (COM tab of Add Reference window). Then you can do the following to capture errors:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { SHDocVw.WebBrowser instance = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance; instance.NavigateError += new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(instance_NavigateError); webBrowser1.Navigate("http://www.google.com/foo"); } void instance_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel) { // Do whatever you want with the error } </code></pre>
<p>I found another way to solve this without setting a reference to the SHDocVw dll.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.createsink(VS.80).aspx" rel="noreferrer">web browser CreateSink method</a> on MSDN.</p>
48,123
<p>How do I programmatically force the deletion of files that are locked by the operating system or any other program with C/C++? The functionality should be similar to the software "Unlocker" at <a href="http://ccollomb.free.fr/unlocker" rel="nofollow noreferrer">http://ccollomb.free.fr/unlocker</a>.</p>
<p>Look <a href="http://www.codeguru.com/cpp/w-p/files/fileio/article.php/c1287" rel="noreferrer">this</a> sample.</p>
<p>This really depends on the underlying filesystem. </p> <p>For example, on Linux, ext3 supports file attributes that are not part of the standard unix read/write/execute/user/group/world paradigm.</p> <p><a href="http://linux.about.com/od/commands/l/blcmdl1_chattr.htm" rel="nofollow noreferrer">There is a nice summary of the available attributes here:</a></p> <p>Really drove me crazy the first time I came across, and even as root, and even after rebooting off a bottable CD I still couldn't delete a file off my hard drive... BTW, the possibilities for creative use of this for practical jokes are nearly endless... :)</p>
26,482
<p>This question is pretty much the same as <a href="https://stackoverflow.com/questions/91362/how-to-escape-brackets-in-a-format-string-in-net">this .Net question</a> exept for java.</p> <p>How do you escape the <code>%1$</code> characters in a java <code>String.format</code>?</p> <p>THe reason I need to do this is that I'm building up a string that will later have more info inserted into it. I've thought of having one of the args just be <code>"%1$"</code> but that doesn't seem to be very elegant?</p> <p>sorry if this is obvious my java is a tad rusty.</p>
<p>You can just double up the %</p>
<p>Either you can use the proposal of Draemon, either you can also have a look at <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html" rel="nofollow noreferrer">java.text.MessageFormat class</a> that has more powerfull formatting abilities than String.format()</p>
24,576
<p>I want to make a login system using ASP.NET (MVC).</p> <p>On the internet, I found some bad examples that involved SQL in Click events. Other information pointed to the ASP.NET built-in membership provider.</p> <p>However, I want to roll my own. I don't want to use the built-in membership provider, as it only seems to work on MS SQL, and I don't like the idea of having a few foreign tables in my database.</p> <p>I could probably think of something, but I need a few pointers in the right direction. It does not have to be high-security, but just regular common-sense security.</p> <p>And I have a few direct questions:</p> <ol> <li><p>A lot of systems seem to have the Session ID stored in a user table. I guess this is to tie a session to a user to prevent hijacking. Do check this every time a user enters a page? And what do I do if the session expires?</p></li> <li><p>Hashing, salting, what does it do? I know of MD5 hashing and I have used it before. But not salting.</p></li> <li><p>Best practices for cookies?</p></li> </ol>
<p>I dont know about best practices but I can tell you what I do. Its not hitech security but it does the job.</p> <p>I use forms authentication. I receive the password secured with ssl via a textbox on the login page. I take that password and hash it. (Hashing is like one way encryption, you can get hash code that cant be reversed back to the password). I take that hash and compare it to the users hash in the database. If the hash's match i use asp.nets built in authentication handling, which handles cookies for me.</p> <p>The FormsAuthentication class has methods available to do this fo you, such as SetAuthCookie and RedirectFromLogin. they will set the cookie and mark them as authenticated. The cookie asp.net uses is encrypted. I cant speak for its security level though, but its in fairly common use.</p> <p>In my class i do the password check and use formsauth to handle the rest:</p> <pre><code>if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); } </code></pre>
<p>I would avoid the whole issue and use openid. There is a library available that you can use directly. <a href="http://blog.wekeroad.com/blog/my-mvc-starter-template/" rel="nofollow noreferrer">Here is a link to a blog post about putting this in place</a></p>
18,399
<p>How can I improve the look and feel of my Linux desktop to suit my programming needs?</p> <p>I found Compiz and it makes switching between my workspaces (which is something I do all the time to make the most of my 13.3" screen laptop) easy and look great - so what else don't I know about that make my programming environment more productive/pleasing?</p> <p>@Rob Cooper - thanks for the heads-up, hope this reword addresses the issues</p>
<p>I found that the best programming experience comes from having quick access all your tools. This means getting comfortable with basic command line acrobatics and really learning keyboard shortcuts, flags, and little productivity apps.</p> <p>I find that most of my workflow comes down to just a few apps and commands:</p> <ul> <li>Terminator</li> <li>SVN commands - ci, co, status, log, etc.</li> <li>Command Line FTP</li> <li>Vim</li> <li>Basic Command lines operations (cd, rm, mv, cp, touch, grep, and std i/o redirection comprise 80% of my work day)</li> </ul> <p>Not to say that GUI apps aren't necessary. A few I use:</p> <ul> <li>Diffmerge</li> <li>RapidSVN</li> <li>Filezilla</li> <li>VirtualBox</li> <li>GnomeDo (this really should be first)</li> </ul> <p>When it comes down to it, the real improvement in programming experience comes from just that - programming experience. Just pick a set of tools and stick with them until you know them inside and out.</p>
<p>If you have half decent 3D acceleration on board, CompizFusion adds attractive desktop effects like mapping your workspaces onto a cube using that to switch between them/move windows between them. Looks pretty and improves general usability - great!</p> <p><a href="http://en.wikipedia.org/wiki/Compiz" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Compiz</a></p>
5,730
<p>Let's compile a list of tips.</p> <p>(Understandably there will be some subjectivity involved, but some pointers would be useful to someone overwhelmed by tackling a large project within the Flash framework.)</p>
<p>These are just scattered thoughts on organization for projects being worked on mostly with the Flash IDE.</p> <p>First, I highly recommend using source control, like Subversion, CVS, or Git. </p> <p>Organization of filesystem folder structure is subjective, but I generally have a "src" folder for all my source FLAs and AS class files, and a "deploy" or "bin" folder for compiled files. The src folder would contain class package files, with class packages organized in reverse domain style (e.g. - com.codehinting.projectname.context ). Modify the publish path of your FLA to publish to the deploy folder by tracing back up using the "../" path segment, for as many levels as needed to trace back from the nesting in the src folder.</p> <p>Also, I typically place third-party libraries (that are pretty well "baked") in a separate location and then modify the global classpath in the Flash IDE to point to this location.</p> <p>Two extremely handy plugins for the Flash IDE are Create Basic Layers and Library Generator, which quickly create your skeleton layer and library folder structure - saves time versus manually creating layers and folders.</p>
<p>A complex project will have many dependencies. In my Flash projects, I put all my libraries in a version controlled location as they are. Third party libraries are usually a mishmash of assets, code, demos and docs. </p> <p>I keep a small yaml file that keeps track of the location of each type of resource associated with each library on my system. When I add a new library, its location goes into this file first, then I run my Ruby script to move the files over to a single location. This way there is no jockeying around with third party library paths, and making sure include paths in my projects match in my fla files and Flex builder projects. </p> <p>A single source to bind them all.</p>
6,841
<p>We have an internal .NET case management application that automatically creates a new case from an email. I want to be able to identify other emails that are related to the original email so we can prevent duplicate cases from being created. </p> <p>I have observed that many, but not all, emails have a thread-index header that looks useful. </p> <p>Does anybody know of a straightforward algorithm or package that we could use?</p>
<p>As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.</p> <p>However, you'll get a pretty high hit rate with the following:</p> <ul> <li><p>Every email message should have a unique &quot;Message-ID&quot; field. Find this, and keep a record of it as a part of the case. (See <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>)</p> </li> <li><p>If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.</p> </li> <li><p>Check for the &quot;In-Reply-To&quot; field, if the ID shown matches a known Message-ID then you know the email is related.</p> </li> <li><p>The &quot;References&quot; and &quot;Original-Message-ID&quot; headers have similar meanings.</p> </li> </ul> <p>If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.</p> <p>The internet standards <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>, <a href="https://www.rfc-editor.org/rfc/rfc2076" rel="nofollow noreferrer">RFC-2076</a> and <a href="https://www.rfc-editor.org/rfc/rfc4021" rel="nofollow noreferrer">RFC-4021</a> may be useful further reading.</p> <p>Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, &quot;Close as Duplicate Case&quot; or &quot;Merge with Duplicate Case&quot;, along with tools to make it easier to find duplicates.</p>
<p>As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.</p> <p>However, you'll get a pretty high hit rate with the following:</p> <ul> <li><p>Every email message should have a unique &quot;Message-ID&quot; field. Find this, and keep a record of it as a part of the case. (See <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>)</p> </li> <li><p>If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.</p> </li> <li><p>Check for the &quot;In-Reply-To&quot; field, if the ID shown matches a known Message-ID then you know the email is related.</p> </li> <li><p>The &quot;References&quot; and &quot;Original-Message-ID&quot; headers have similar meanings.</p> </li> </ul> <p>If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.</p> <p>The internet standards <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>, <a href="https://www.rfc-editor.org/rfc/rfc2076" rel="nofollow noreferrer">RFC-2076</a> and <a href="https://www.rfc-editor.org/rfc/rfc4021" rel="nofollow noreferrer">RFC-4021</a> may be useful further reading.</p> <p>Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, &quot;Close as Duplicate Case&quot; or &quot;Merge with Duplicate Case&quot;, along with tools to make it easier to find duplicates.</p>
36,762
<p>I'm using an HTML sanitizing whitelist code found here:<br> <a href="http://refactormycode.com/codes/333-sanitize-html" rel="nofollow noreferrer">http://refactormycode.com/codes/333-sanitize-html</a></p> <p>I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the <code>&lt;img</code> tag check </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre> <p>Aside from the condition above, my code is almost identical to the code in the page I linked to. When I try to test this in C#, it throws an exception saying "<code>Not enough )'s</code>". I've counted the parenthesis several times and I've run the expression through a few online Javascript-based regex testers and none of them seem to tell me of any problems.</p> <p>Am I missing something in my Regex that is causing a parenthesis to escape? What do I need to do to fix this?</p> <p><strong>UPDATE</strong><br> After a lot of trial and error, I remembered that the <code>#</code> sign is a comment in regexes. The key to fixing this is to escape the <code>#</code> character. In case anyone else comes across the same problem, I've included my fix (just escaping the <code>#</code> sign) </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre>
<p>Your IsMatch Method is using the option <code>RegexOptions.IgnorePatternWhitespace</code>, that allows you to put comments inside the regular expressions, so you have to scape the # chatacter, otherwise it will be interpreted as a comment.</p> <pre><code>if (!IsMatch(tagname,@"&lt;font(\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s?&gt;")) { html = html.Remove(tag.Index, tag.Length); } </code></pre>
<p>It works fine for me... what version of the .NET framework are you using, and what is the <em>exact</em> exception?</p> <p>Also - what does you <code>IsMatch</code> method look like? is this just a pass-thru to <code>Regex.IsMatch</code>?</p> <p>[update] The problem is that the OP's example code didn't show they are using the IgnorePatternWhitespace regex option; with this option it doesn't work; without this option (i.e. as presented) the code is fine.</p>
29,718
<p>How can I generate UML diagrams (especially sequence diagrams) from existing Java code?</p>
<h1><a href="http://www.objectaid.com/home" rel="noreferrer">ObjectAid UML Explorer</a></h1> <p>Is what I used. It is easily <strong><a href="https://www.objectaid.com/install-objectaid" rel="noreferrer">installed</a></strong> from the repository:</p> <pre><code>Name: ObjectAid UML Explorer Location: http://www.objectaid.com/update/current </code></pre> <p>And produces quite nice UML diagrams:</p> <p><img src="https://i.stack.imgur.com/QPnZD.png" alt="Screenshot"></p> <h2>Description from the website:</h2> <blockquote> <p>The ObjectAid UML Explorer is different from other UML tools. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor, while being very easy to use. Several unique features make this possible:</p> <ul> <li>Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format.</li> <li>If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code.</li> <li>Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the changes without going out of sync.</li> <li>All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your version control system.</li> <li>Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related information is shown in other views wherever applicable.</li> </ul> </blockquote>
<p>I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.</p> <p>you can install PlantUML plugin in the netbeans by this method:</p> <p>Netbeans Menu -> Tools -> Plugin</p> <p>Now select Available Plugins and then find PlantUML and install it.</p> <p>For more information go to website: www.plantuml.com</p>
7,500
<p>I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity</p> <pre><code>XmlDocument xmldoc = new XmlDocument(); string text = "Hello, I am text &amp;alpha; &amp;nbsp; &amp;ndash; &amp;mdash;" xmldoc.InnerXml = "&lt;p&gt;" + text + "&lt;/p&gt;"; </code></pre> <p>This throws the exception: </p> <blockquote> <p>Reference to undeclared entity 'alpha'. Line 2, position 2.. </p> </blockquote> <p>How would I go about solving this problem?</p>
<p>XML, unlike HTML does not define entities (ie named references to UNICODE characters) so &amp;alpha; &amp;mdash; etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use &amp;lt; and &amp;amp; in XML</p> <p>If you want to create HTML, use an HtmlDocument instead.</p>
<p>You could also set the InnerText to <code>"Hello, I am text α – —"</code>, making the XmlDocument escape them automatically. I think.</p>
35,649
<p>We are developing a WCF based system. In the process we are trying to lock some data from being modified by more than one users. So we decided to have a data structure that will contain the necessary information for the locking logic to execute (by for example storing the ID of the locked objects)</p> <p>The problem we are having is persisting that data between sessions. Is there anyway we can avoid executing expensive database calls? I am not sure how can we do that in WCF since it can only persist data (in memory) during an open session.</p>
<p>Static members of the service implementing class are shared between sessions &amp; calls. </p>
<p>Perhaps a caching framework like <a href="http://blogs.msdn.com/velocity/" rel="nofollow noreferrer">velocity</a> help you out.</p>
34,780
<p>I'm just wondering what the optimal solution is here.</p> <p>Say I have a normalized database. The primary key of the whole system is a varchar. What I'm wondering is should I relate this varchar to an int for normalization or leave it? It's simpler to leave as a varchar, but it might be more optimal </p> <p>For instance I can have</p> <pre><code>People ====================== name varchar(10) DoB DateTime Height int Phone_Number ====================== name varchar(10) number varchar(15) </code></pre> <p>Or I could have</p> <pre><code>People ====================== id int Identity name varchar(10) DoB DateTime Height int Phone_Number ====================== id int number varchar(15) </code></pre> <p>Add several other one-to-many relationships of course. </p> <p>What do you all think? Which is better and why?</p>
<p>Can you really use names as primary keys? Isn't there a high risk of several people with the same name?</p> <p>If you really are so lucky that your name attribute can be used as primary key, then - by all means - use that. Often, though, you will have to make something up, like a customer_id, etc.</p> <p>And finally: "NAME" is a reserved word in at least one DBMS, so consider using something else, e.g. fullname.</p>
<p>If the "name" field really is appropriate as a primary key, then do it. The database will <em>not</em> get more normalized by creating a surrogate key in that case. You will get some duplicate strings for foreign keys, but that is not a normalization issue, since the FK constraint guarantrees integrity on strings just as it would on surrogate keys.</p> <p>However you are not explaining what the "name" is. In practice it is very seldom that a string is appropriate as a primary key. If it is the name of a person, it wont work as a PK, since more than one person can have the same name, people can change names and so on.</p>
17,379
<blockquote> <p>System.InvalidOperationException: DragDrop registration did not succeed. ---> System.Threading.ThreadStateException:</p> </blockquote> <p>What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...</p> <pre><code>splitReport.Panel1.Controls.Add(ChartPanel); </code></pre> <p>Working in VS2008 C#</p>
<p>This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.</p> <p>If you have the <code>[STAThread]</code> attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):</p> <p><code>Thread.CurrentThread.SetApartmentState( ApartmentState.STA )</code></p> <p>(<code>Thread</code> and <code>ApartmentState</code> are members of <code>System.Threading</code>)</p> <p>That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the <code>[STAThread]</code> attribute.</p> <p>If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.</p>
<p>I have encountered this situation recently,<code>[STAThreadAttribute]</code>is in my case,and i solved this problem by using <strong>Invoke</strong> method,it might be helpful for you guys,so I share with a little code snippet:</p> <pre><code>this.Invoke(new InvokeHandler(delegate() { //Your method here! })); </code></pre> <p>And InvokeHandler is a delegate like this:</p> <pre><code>private delegate void InvokeHandler(); </code></pre>
16,445
<p>if you pay like 25% of the license cost as a annual maintenance fee for software, that usually gives you free upgrades (even major releases).</p> <p>this should mean that the software company has to release a major version right? otherwise why would you pay for the annual maintenance fee?</p>
<p>No, it doesn't mean that they should or will release a new major version unless that is in your contract. They might only release minor versions or patches.</p> <p>I do think that ethically they should release new major versions regularly, but I would look at their past release history.</p> <p>A Software Maint fee often also gets you priority support which is a major part of what companies are paying for.</p>
<p>Typically I would expect to get any major releases that happen, but I don't think you can expect anything.</p> <p>For a start what's a major release? If you were to <em>force</em> someone to release a major version then they might just change the numbers in the about box and hit compile on what they have. That doesn't help anyone.</p> <p>More and more we are seeing a trend to 'subscription' licensing anyway in which case the line between the one-off license and the maintenance fee is removed. I think this is a much better model in general, both for the software vendor and the customer.</p>
37,137
<p>As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?</p> <pre><code>import atexit def helloworld(): print("Hello World!") atexit.register(helloworld) raise Exception("Good bye cruel world!") </code></pre> <p>outputs</p> <pre><code>Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; raise Exception("Good bye cruel world!") Exception: Good bye cruel world! Hello World! </code></pre>
<p>I don't really know why you want to do that, but you can install an excepthook that will be called by Python whenever an uncatched exception is raised, and in it clear the array of registered function in the <code>atexit</code> module.</p> <p>Something like that :</p> <pre><code>import sys import atexit def clear_atexit_excepthook(exctype, value, traceback): atexit._exithandlers[:] = [] sys.__excepthook__(exctype, value, traceback) def helloworld(): print "Hello world!" sys.excepthook = clear_atexit_excepthook atexit.register(helloworld) raise Exception("Good bye cruel world!") </code></pre> <p>Beware that it may behave incorrectly if the exception is raised from an <code>atexit</code> registered function (but then the behaviour would have been strange even if this hook was not used).</p>
<p>If you call</p> <pre><code>import os os._exit(0) </code></pre> <p>the exit handlers will not be called, yours or those registered by other modules in the application.</p>
10,656