instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>If I have $var defined in Page1.php and in Page2.php I have</p> <pre> //Page2.php include('Page1.php'); echo $var; </pre> <p>For what reasons will it not print the value of $var to the screen? The files are in the same directory so paths shouldn't be the issue. I've checked the php.ini file and nothing really jumps out at me. Any ideas?</p>
<p>Possible causes:</p> <ul> <li>The current working path isn't always the same as the file's. For example, if Page2.php is being included at a higher level, that higher level will be the path. Either make sure you've loaded Page2.php directly or move Page1.php accordingly.</li> <li>Make sure <code>$var</code> is really what you expect it to be. Echo it in Page1.php to confirm. (this also checks the right file is being included)</li> <li>If the source isn't really this simple, make sure you're not undefining/clearing <code>$var</code> anywhere.</li> </ul>
<p>I've just tested:</p> <p>page1.php:</p> <pre><code>&lt;?php $foo = "bar" ?&gt; </code></pre> <p>page2.php:</p> <pre><code>&lt;?php include('page1.php'); echo $foo; ?&gt; </code></pre> <p>This works.</p> <p>You might want to check your file paths. Also var_dump() is handy to check the variable output.</p>
21,653
<p>I have a solution with about 20 projects (that use Devexpress controls) in and when I do a normal solution build (ctrl-shift-B) it says everything is completed sucessfully when in actualy fact it has done nothing. To get it to build i have to right click on the solution and use the batch build option.</p> <p>I've tried deleting the solution and regetting from TFS and i've even gone as far as reinstalling VS!</p> <p>Anyone got any clues as to what is going wrong?</p> <p>Sorry should have added that also tried to build from the main menus aswell.</p>
<p>I've had similar issues. It's a long shot, but right-click your solution and go to Properties -> Configuration Properties. Check to make sure all of your projects have the "Build" option checked.</p>
<p>Perhaps Ctrl+Shift+B has been assigned to one of the "check-to-see-if-it-is-needed-before-building" type of functions?</p> <p>Check in the keyboard setting:</p> <ul> <li>Right-click the toolbar</li> <li>Select Customize in the popup menu</li> <li>Click the Keyboard button in the lower right corner of the dialog</li> <li>In the new dialog, in the "Press shortcut keys", a bit to the right and below the center, hit Ctrl+Shift+B</li> <li>Verify that it is bound to <em>Build.BuildSolution</em></li> </ul> <p>at least that is what it is bound to for me. I notice there is an action named Build.RebuildSolution as well, you should experiment.</p>
43,876
<p>I made a Java Applet with some Standard GUI Components on it. I used the <a href="http://www.miglayout.com/" rel="nofollow noreferrer">MigLayout</a> Manager.</p> <p>If I move the mouse slowly over the various GUI Components everything appears to be fine, but if I move the mouse fast, it flickers.</p> <p>What could make that nasty ugly redraw? (Core 2 Duo 6300, 2GB Ram, Windows XP)</p>
<p>One thought would be to check your code (and/or the MigLayout code) for unnecessary <code>repaint()</code> operations.</p> <p>Custom UIs and layouts can cause weird problems sometimes...</p>
<p>you could use double buffering in java applet to improve screen refreshing speed. ask more if details needed..</p>
17,798
<p>The application is planned to be built using ASP.NET, .NET Remoting &amp; MS SQL Server. High availability is required at presentation layer, application layer and database.</p> <p>Does IIS 7.0 provide any advantages over IIS 6.0 in regard to the High availability aspect?</p>
<p>Take a look at the <a href="http://highscalability.com/" rel="nofollow noreferrer">High Scalability Blog</a></p>
<p>Make sure your design scales in a horizontal manner.</p> <p>That is, have your system hiding behind a load balance layer with the servers that are actually providing the service behind the load balance layer.</p> <p>When you need to increase capacity, you build a new server or servers and plug it in alongside the existing servers. Then you configure the load balance layer to also consider the new server(s) when passing out the work.</p>
31,059
<p>Does anyone else find that the documentation of a lot of payment processors have poor or incomplete documentation as to how to use their API? Or it's just plain confusing?</p> <p>Recently I have setup both <a href="http://www.paypal.com" rel="nofollow noreferrer">PayPal</a> and <a href="http://www.beanstream.com" rel="nofollow noreferrer">Beanstream</a> and found that both are either confusing or don't include full documentation.</p> <p>For example, in the BeanStream documentation, they say they will return a "message_id", which is great, but no where do they tell you what the different id's mean. It also comes with some text, so you can start creating a list, but there is no way to check to ensure you get either a valid one or the one that means it was successful.</p> <p>Has anyone had this experience?</p> <p><strong>Edit:</strong> I will agree that when you email them they are helpful, but unfortunately most of them are only open normal business hours for general tech support (other than emergency) which isn't always useful as that isn't when it seems like I do my integration.</p>
<p>well, this isn't really specific to payment processor documentation, in that, all things being equal, well documented APIs will help encourage development. for what it's worth, i've worked with paypal, authorize.net, ups, and usps APIs, and didn't find them overtly confusing (not implying that they were a particular joy to get through).</p> <p>that being said, i wish more documentation was like PHP's. despite it being such a scattered language, the documentation is really quite good.</p>
<p>I've only worked with PayPal, but the simple version (where you just set up an HTML form on your web page and submit it with the PayPal button) is super-easy to work with. And if you're looking for near real-time payment feedback, I always found it easier to just write a program to check my PayPal email account periodically, and parse payment details from the body of the email itself.</p>
34,722
<p>We have got loads of options for <code>php + MySQL + Apache</code> combo... Which is the best pack among these ?</p> <p>Lets confine our ideas to <code>WAMP vs XAMPP</code>, is there a better option to go for?</p> <p>I created an online programming contest web app called <code>CodeFire</code> on <code>XAMPP</code>, later I had to switch to <code>WAMP</code>, where none of the <code>php</code> scripts worked properly... what standard should I follow?</p>
<p>I like XAMPP, personally. I have an install running on a thumbdrive that I carry around that's pretty much my development environment for LAMP web dev on any machine I happen to be at (I'm mostly on Windows client machines).</p> <p>Small, fully-functional, and stable - works really well for my needs.</p>
<p>I use xampp, because it offers easy upgradeability and portability. You can easily upgrade the version wihtout a hassle.</p> <p>I use xampp's 7zip installer version which is a very nice when it comes to be upgrading your php and phpmyadmin quite frequently in order to fix the bugs that are introduced in previous versions and have new functionality.</p>
13,100
<p>I am trying to hide the button based on the user's role using the following code: </p> <pre><code> &lt;asp:Button ID="btndisplayrole" Text="Admin Button" Visible='&lt;%= WebApplication1.SiteHelper.IsUserInRole("Admin") %&gt;' runat="server" OnClick="DisplayRoleClick" /&gt; </code></pre> <p>But when I run the above code I get the following error message: </p> <p>Cannot create an object of type 'System.Boolean' from its string representation '&lt;%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible' </p>
<p>Kind of an interesting issue.. But as the error message states, the string <code>&lt;%= WebApplication1.SiteHelper.IsUserInRole("Admin") %&gt;</code> cannot be converted to a boolean.</p> <p>Unfortunately i cannot explain why the expression isn't evaluated, but instead is treated like a string.</p> <p>The reason why your <code>&lt;%# %&gt;</code> expression works as expected, is because it is treated much differently. When the Page is compiled into a class, then the compiler creates an event handler similar to this:</p> <pre><code>public void __DataBindingButton2(object sender, EventArgs e) { Button button = (Button) sender; Page bindingContainer = (Page) button.BindingContainer; button.Visible = HttpContext.Current.User.IsInRole("admin"); } </code></pre> <p>and hooks this method up to the Control.Databinding event on your control. As you can see, the <code>&lt;%# %&gt;</code> is this time properly treated as server code, and not just a random string.</p> <p>So i guess the solution is either to use databinding, or go to the codebehind as AndreasKnudsen suggests.</p>
<pre><code>Visible='&lt;%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %&gt;' </code></pre> <p>OR</p> <pre><code>Visible=&lt;%= WebApplication1.SiteHelper.IsUserInRole("Admin") %&gt; </code></pre>
48,290
<p>What is the purpose of the colon before a block in Python?</p> <p>Example:</p> <pre><code>if n == 0: print "The end" </code></pre>
<p>The colon is there to declare the start of an indented block.</p> <p>Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the <a href="http://www.python.org/dev/peps/pep-0020/" rel="noreferrer">Python koan</a> “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so <em>any</em> statement that <em>should</em> be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)</p> <p>It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.</p> <hr> <p>This question turns out to be a <a href="http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements" rel="noreferrer">Python FAQ</a>, and I found one of its answers by Guido <a href="http://markmail.org/message/ve7mwqxhci4pm6lw" rel="noreferrer">here</a>:</p> <blockquote> <p><strong>Why are colons required for the if/while/def/class statements?</strong></p> <p>The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:</p> <pre><code>if a == b print a </code></pre> <p>versus </p> <pre><code>if a == b: print a </code></pre> <p>Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.</p> <p>Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.</p> </blockquote>
<p>The colon is a complete annoyance. If you need to indent after an 'if' or a 'for', then just look for the 'if' or the 'for'.</p> <p>Cmon', all this rationalization. The 'spin' language for the propeller chip easily overcomes this issue.</p> <p>PLEASE, let's make the colon optional, and get on with some logical programming.</p>
26,496
<p>I have seen many apps that take instrument classes and take <code>-javaagent</code> as a param when loading also put a <code>-noverify</code> to the command line.</p> <p>The Java doc says that <code>-noverify</code> turns off class verification.</p> <p>However why would anyone want to turn off verification even if they are instrumenting classes?</p>
<p>Start-up time, I'd say. Verification that classes are correct takes some time when the class is loaded. Since classes might be loaded in a lazy fashion (not on app start, but when being used for the first time), this might cause unexpected and undesired runtime delays.</p> <p>Actually the class does not need to be checked in general. The compiler will not emit any invalid bytecode or class construct. The reason for verification is that the class may be build on one system, get hosted online and is transmitted to you through the unprotected internet. On this path, a malicious attacker might modify the bytecode and create something the compiler might never create; something that can crash the JVM or possibly circumvents security restrictions. Thus the class is verified before it is used. If this is a local application, there is usually no need to check the bytecode again.</p>
<p>Start up time used to be a bit of an issue. However, verifiers are now faster, as are processors. Code compiled with JDK6 javac will by default include extra information to make the verifier step faster. Apache Harmony just uses a much faster verification algorithm.</p> <p>Some very old versions of javac produced incorrect bytecode. Indeed the Sun PlugIn still includes fix-up code to make some broken class files verify.</p>
38,547
<p>How can I see which file extensions are related to which kind of syntax highlighting? Unfortunately, <code>Tools -&gt; Options -&gt; Text Editor -&gt; File Extensions</code> lists only those entered manually, no default ones. And I didn't manage to find it on my own via Google or other means. </p> <p>My particular problem is, I want to have .inc highlighted exactly as .asp but I'm not sure which editor is used for .asp. I did try the following (none worked):</p> <ul> <li>Web Form Editor </li> <li>VBscript Editor </li> <li>HTML Editor</li> <li>Script Editor</li> </ul> <p>(They did work in a sense that they colored my code in one way or another, but it wasn't the same highlight as I get for <code>.asp</code> files).</p>
<p>maybe <a href="http://cc.codegear.com/Item/25538" rel="nofollow noreferrer">Andreas Hausladen's DFMCheck</a> helps?</p> <p>Uli.</p>
<p>Just to be sure, but have you used 'inherited' in the inherited dfm?</p> <pre><code>inherited Form1: TForm1 Caption = 'Form1' PixelsPerInch = 96 TextHeight = 13 end </code></pre> <p>If you have 'object' and not 'inherited' you get a lot of problems.</p>
37,746
<p>I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.</p> <p>I have looked at <a href="http://www.fullphat.net/index.php" rel="noreferrer">Snarl</a>, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.</p> <p>Which one do you recommend?</p> <p>Python support is a huge plus.</p>
<p>You can do it by depending on a GUI library.</p> <p>For example, with PyQt,it is possible :</p> <ul> <li><p><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qsystemtrayicon.html" rel="nofollow noreferrer">PyQt QSystemTrayIcon Documentation</a></p></li> <li><p><a href="http://qt-project.org/doc/qt-4.8/qsystemtrayicon.html" rel="nofollow noreferrer">QSystemTrayIcon Class Reference</a></p></li> <li><p><a href="http://qt-project.org/doc/qt-4.8/desktop-systray.html" rel="nofollow noreferrer">Example of QSystemTrayIcon</a> (in C++, easy to adapt to python)</p></li> </ul>
<p>You don't need anyhting. Just use toasters windows with Win32 api</p>
44,803
<p>What's the best way, using C# or other .NET language, to determine if a file path string is on the local machine or a remote server?</p> <p>It's possible to determine if a path string is UNC using the following:</p> <pre><code>new Uri(path).IsUnc </code></pre> <p>That works great for paths that start with C:\ or other drive letter, but what about paths like:</p> <pre><code>\\machinename\sharename\directory \\10.12.34.56\sharename\directory </code></pre> <p>...where both refer to the local machine - these are UNC paths but are still local.</p>
<p>Don't know if there's a more efficient way of doing this, but it seems to work for me:</p> <pre><code> IPAddress[] host; IPAddress[] local; bool isLocal = false; host = Dns.GetHostAddresses(uri.Host); local = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress hostAddress in host) { if (IPAddress.IsLoopback(hostAddress)) { isLocal = true; break; } else { foreach (IPAddress localAddress in local) { if (hostAddress.Equals(localAddress)) { isLocal = true; break; } } if (isLocal) { break; } } } </code></pre>
<p>I don't know of a single method to check that. However, you can compare the Uri's <code>Host</code> property to either the local host name or IP address.</p> <p>You can get the local machine name using:</p> <pre><code>string hostName = System.Net.Dns.GetHostName() </code></pre> <p>You can then get an array of IP addresses by passing that string to:</p> <pre><code>System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(hostName); </code></pre> <p>Switch on the Uri's <code>HostNameType</code> property, probably <code>UriHostNameType.Dns</code> or <code>UriHostNameType.IPv4</code>, to match either the name or IP address.</p>
46,182
<p>I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop:</p> <pre><code>function populateDropDown(dropdownId, list, enable, showCount) { var dropdown = $get(dropdownId); dropdown.options.length = 1; for (var i = 0; i &lt; list.length; i++) { var opt = document.createElement("option"); if (showCount) { opt.text = list[i].Name + ' (' + list[i].ChildCount + ')'; } else { opt.text = list[i].Name; } opt.value = list[i].Name; dropdown.options.add(opt); } dropdown.disabled = !enable; } </code></pre> <p>However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback?</p> <p><strong>Edit:</strong> Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?</p>
<p>Although I'm not really sure how it does it the CascadingDropDown in the AJAX Control Toolkit does support this.</p> <p>This is the line that appears to do it:</p> <pre><code>AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]); </code></pre> <p>But the simplest idea would be to put the selected value into a hidden input field for the postback event.</p>
<p>You need to use Request.Form for this - you can't encrypt ViewState on the fly from the client - it would defeat the whole point of it :).</p> <p>Edit: Responding to your Edit :) the Page Lifecycle is the thing that allows you to use the ViewState persistence in the first place. The control tree is handled there and, well, there's just no getting around it.</p> <p>Request.Form is a perfectly viable way to do this - it will tell you the value of the selection. If you want to know all of the values, you could do some type of serialization to a hidden control.</p> <p>Ugly, yes, But that's why god (some call him ScottGu) invented ASP.NET MVC :).</p>
18,882
<p>What is the simplest way of copying symbolic links on the Mac?</p> <p>A python or perl solution would be preferred, but any solution would be a help.</p> <p>I am copying frameworks for an installation package, and need the links to be maintained</p>
<p>As David mentioned, OS X is missing the handy -a option that gnu cp has.</p> <p>However, if you use -R to do a recursive copy, then it will copy symlinks by default, so</p> <pre><code>cp -R source destination </code></pre> <p>ought to work.</p>
<p>As you tagged python, i asume you mean something like copytree(src, dst[, symlinks]). Real symlinks (created by ln -s) will be copied as on any unix system. But if you create an alias with the finder, you wont get a symlink, but an alias. The MacOS offers two types of links: unix type symlinks and aliases (see <a href="http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/Articles/Aliases.html" rel="nofollow noreferrer">http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/Articles/Aliases.html</a>). These aliases are not treated as links by many tools - neither copytree as i know.</p>
27,259
<p>I'm a very novice OCaml programmer so please forgive me if this is a stupid/obvious question. There's <em>a lot</em> to absorb and I may have missed this in the documentation.</p> <p>I have a base of code that's starting to look like this:</p> <pre><code>let update_x p x = add_delta p; p.x &lt;- x; refresh p let update_y p y = add_delta p; p.y &lt;- y; refresh p let update_z p z = add_delta p; p.z &lt;- z; refresh p </code></pre> <p>The duplication is starting to bug me because I <em>want</em> to write something like this:</p> <pre><code>let update_scalar p scalar value = add_delta p; magic_reflection (p, scalar) &lt;- value; refresh p </code></pre> <p>This way when I update x I can simply call:</p> <pre><code>update_scalar p 'x' value </code></pre> <p>This calls out "macros!" to me but I don't believe OCaml has a macro system. What else can I do?</p>
<p>You can't do quite what you want, but you can greatly reduce the boilerplate with a higher-order function:</p> <pre><code>let update_gen set p x = add_delta p; set p x; refresh p let update_x = update_gen (fun p v -&gt; p.x &lt;- v) let update_y = update_gen (fun p v -&gt; p.y &lt;- v) let update_z = update_gen (fun p v -&gt; p.z &lt;- v) </code></pre> <p>OCaml does have a macro system (camlp4) and it does allow you to implement this kind of thing, with some work.</p>
<p>As noted above ocaml has macro system. And for this task only small fraction of it is needed :</p> <pre><code>open Printf type t = { mutable x : float; mutable y : float; mutable z : float; mutable t : int; } let add_delta p = p.t &lt;- p.t + 1 let refresh p = printf "%d) %.2f %.2f %.2f\n" p.t p.x p.y p.z DEFINE UPD(x) = fun p v -&gt; add_delta p; p.x &lt;- v; refresh p let update_x = UPD(x) let update_y = UPD(y) let update_z = UPD(z) let () = let p = { x = 0.; y = 0.; z = 0.; t = 0; } in update_x p 0.1; update_y p 0.3; update_z p 2.0 </code></pre> <p>Compile with:</p> <pre><code>ocamlfind ocamlc -package camlp4.macro -syntax camlp4o q.ml -o q </code></pre> <p>See the generated code with :</p> <pre><code>camlp4o Camlp4MacroParser.cmo q.ml </code></pre>
26,527
<p>I am trying to develop a multimedia site and I am leaning heavily toward Silverlight however Flash is always a main player. I am a Speed and performance type developer. Which Technology will load fastest in the given scenarios? 56k, DSL and Cable?</p>
<p>It all depends on what you're doing: animation, video, calculation, etc? There are <a href="http://www.tobinharris.com/2008/8/30/performance-of-silverlight-vs-flash-vs-javascript-vs-tracemonkey" rel="nofollow noreferrer">some tests that show Silverlight being faster for raw computation</a>, while Flash's graphics engine is farther along (GPU utilization, 3D, etc.).</p> <p>If you're talking about load time, there are definitely things you can do in Silverlight to make your XAP file smaller than most images - the Hard Rock Memorabilia team got their XAP down under 70K, and that site browsed GB of photo data. I'm sure you can do the same in Flash.</p> <p>While your question is focused on performance, as others have mentioned you do have to take into account the 4.5MB install for Silverlight, since it's not widely installed yet.</p>
<p>Actually, you have to assume that Flash is probably already installed on the user's browser, and SilverLight probably not. So the cost of installing silverlight (though a small download) has to be taken in to consideration as well.</p> <p>Silverlight, however, does have some pretty neat out of the box multimedia support.</p>
9,140
<p>I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using <code>jQuery.getJSON()</code>.</p> <p>Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until <code>jQuery.getJSON()</code> executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until <code>jQuery.getJSON()</code> ran).</p> <p>The only way I can think of out of this problem is to somehow specify the name of my function to <code>jQuery.getJSON()</code> instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.</p>
<p>The use of <code>jQuery.getScript</code> turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the default in <code>jQuery.getScript</code>, as in all the other calls in jQuery's Ajax library, is to append a further additional argument <code>_=12344567</code> (where 1234567 is really a time stamp). jQuery does this to prevent the browser from caching the response. However, this additional breaks my signing of the request just like the auto-named callback function. </p> <p>With some help on #jquery, I learned that the only way to get jQuery not to mess at all with your params is to make the request using the base <code>jQuery.Ajax</code> method with the following arguments:</p> <pre><code>jQuery.ajax({ url: fbookUrl, dataType: "script", type: "GET", cache: true, callback: null, data: null }); </code></pre> <p>(where <code>fbookUrl</code> is the Facebook API url I'm trying to request with its full params including the signature and the <code>callback=myFunction</code>). The <code>dataType: "script"</code> arg specifies that the resulting JSONP should be stuffed into a script tag on the page for execution, <code>cache: true</code> tells jQuery to allow the browser to cache the response, i.e. to skip the addition of the time stamp parameter.</p>
<p>This is a better solution with a fixed callback:</p> <pre><code>window.fixed_callback = function(data){ alert(data.title); }; $(function() { $.getScript("http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&amp;tagmode=any&amp;format=json&amp;jsoncallback=fixed_callback", function(data) { alert('done'); } ); }); </code></pre> <p>The problem with this callback is you can only handle one kind of request at a time as the function is globally registered. The callback function would probably have to turn into a dispatcher for the different kinds of data that it could retrieve and call the appropriate function.</p>
24,857
<p>I have a bunch of generic interfaces and classes</p> <pre><code>public interface IElement { // omited } class Element implements IElement { // omited } public interface IElementList&lt;E extends IElement&gt; extends Iterable { public Iterator&lt;E&gt; iterator(); } class ElementList implements IElementList&lt;Element&gt; { public Iterator&lt;Element&gt; iterator() { // omited } } public interface IElementListGroup&lt;E extends IElementList&lt;? extends IElement&gt;&gt; { public E getChosenElementList(); } class ElementListGroup implements IElementListGroup&lt;ElementList&gt; { public ElementList getChosenElementList() { // omited } } </code></pre> <p>And then a simple code</p> <pre><code>ElementListGroup group; for(Element e : group.getChosenElementList()) { // omited } </code></pre> <p>And the line with for keyword throwe a "cannot convert from element type Object to Element" compiler error.</p> <p>Thanks in advance.</p>
<p><code>IElementList</code> needs to implement <code>Iterable&lt;E&gt;</code>. Otherwise, the interface specifies <code>Iterator iterator()</code>, not <code>Iterator&lt;E&gt; iterator()</code>. This makes the compiler think that you're iterating over <code>Object</code>s.</p> <p>I made this change, and it compiled fine (after adding some null returns).</p>
<p>Your function returns an ElementList not an Element, and ElementList is not an iterable over Element</p>
40,602
<p>When I add an assembly reference to a project in Visual Studio 8 the Aliases property, of that reference, is set to "global". What is this property good for and why is it set to global?</p> <p>MSDN tells me that this is a list of aliases for the assembly but not why I might want to use this property or why most are aliased as "global".</p> <p><a href="http://msdn.microsoft.com/en-us/library/vslangproj80.reference3.aliases.aspx" rel="noreferrer">MSDN reference</a></p>
<p>This is for "extern aliases". Suppose you want to use two different types, both of which are called <code>Foo.Bar</code> (i.e. <code>Bar</code> in a namespace of <code>Foo</code>). The two types will be in different assemblies (by definition) - you use the property in VS to associate an alias with each reference, then you can do:</p> <pre><code>extern alias FirstAlias; extern alias SecondAlias; using FirstBar = FirstAlias::Foo.Bar; using SecondBar = SecondAlias::Foo.Bar; </code></pre> <p>and then use <code>FirstBar</code> and <code>SecondBar</code> in your code.</p> <p>So basically it's an extra level of naming - and you shouldn't use it unless you really, really have to. It will confuse a lot of people. Try to avoid getting into that situation in the first place - but be aware of this solution for those times where you just can't avoid it.</p>
<p>Search for "<a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias" rel="nofollow noreferrer">extern alias</a>"; it is a very rarely used feature that is only needed to disambiguate between two dlls that contribute the same types (for example, two different versions of the same assembly, or two assemblies that have a class which shares a fully-qualified-name).</p> <p>"global" is the default. For example, if you have a class called <code>Foo.System</code>, you can unambiguously refer to the main <code>System</code> namespace via <code>global::System</code>.</p>
36,439
<p>I have a serious problem and I can't find a way to solve it because I have no idea why is it happening. For some reason the things I print get really messy, like a mountain range growing on the print. It looks like overflow but it can't be because I'm already using 0.82 flow modifier and if I go any lower the printout will fall apart as the extrusions won't touch at all. I've double checked my extruder steps and my filament and also my nozzle width, all are set up correctly. The whole thing looks like the printer is over-extruding just in some parts of the print. <a href="https://i.stack.imgur.com/CgpKL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CgpKL.jpg" alt="enter image description here"></a></p>
<p>It definitely looks like over extruding. But similar effect can appear with proper extruding (or not too much exceeded) but with too high temperature.</p> <p>If it appears only on some parts of the first layer then it can be:</p> <ul> <li>bed leveling issue (or eventually bed is bent)</li> <li>caret mechanism issue (dispositioned/bent)</li> </ul> <p>You can also check different speeds just to be sure.</p>
<p>This is happening on the first or second layer, correct? It looks like your nozzle is trammed too close to the build plate. If there is less gap between the nozzle and bed than the slicer expects, it will over-extrude the first layer. That tends to produce "bacon" patterns of ripples on the bottom of the print as the plastic gets unevenly squeezed out to the side of the strand. </p>
334
<p>How do I loop into all the resources in the resourcemanager?</p> <p>Ie: foreach (string resource in ResourceManager) //Do something with the recource.</p> <p>Thanks</p>
<p>Use ResourceManager.<a href="http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset.aspx" rel="noreferrer">GetResourceSet</a>() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach).</p> <hr> <p>To answer Nico's question: you can count the elements of an <code>IEnumerable</code> by casting it to the generic <code>IEnumerable&lt;object&gt;</code> and use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx" rel="noreferrer"><code>Enumerable.Count&lt;T&gt;()</code></a> extension method, which is new in C# 3.5:</p> <pre><code>using System.Linq; ... var resourceSet = resourceManager.GetResourceSet(..); var count = resSet.Cast&lt;object&gt;().Count(); </code></pre>
<p>I wonder why would you like to loop through all of the resources.</p> <p>Anyway, <code>ResourceManager</code> needs to be instantiated giving it a <code>Type</code> or the base name where to lookup for resources. Then you will be able to retrieve a <code>ResourceSet</code> but for a given <code>CultureInfo</code>, ergo if you want to obtain all the resources for a given `ResourceManager</p>
16,944
<p>I need to monitor my Windows Server event logs so that I know if there is a problem with any of my ASP.Net websites (IIS errors, windows login errors etc) - errors that would end up in the event log rather than being handled by my application's error logging.</p> <p>Has anyone had any experience of <a href="http://www.gfi.com/eventsmanager/" rel="nofollow noreferrer">GFI Events Manager</a> or <a href="http://www.eventsentry.com/" rel="nofollow noreferrer">Event Sentry</a>? Is there anything better on the market?</p>
<p>I currently use EventSentry and I have to say I am very happy with it. I get an email when my backups don't run, the reports are helpful and my experience with the support staff has been great. In my case, EventSentry was much cheaper than GFI and offered the value I needed.</p>
<p>I haven't used this tool, but Microsoft' System Center Operations Manager (used to be called Microsoft Operations Manager) should do all of that. </p> <p><a href="http://www.microsoft.com/systemcenter/opsmgr/default.mspx?sess=296d9b4b1d52c17152baa2806e58dd78" rel="nofollow noreferrer">System Center Operations Manager</a></p>
39,748
<p>I'm trying to get some WPF concepts down, so I've put together a simple example of what I'm trying to do. I would like to set a custom property of a user control, and have it be used by an element within the control.</p> <p>I've been researching and experimenting, but I'm not fully understanding everything here. Any help would be appreciated.</p> <p>The user control for this example is a simple square with a circle inside of it:</p> <pre><code>&lt;UserControl x:Class="CircleInSquare" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="100" Height="100" &gt; &lt;Grid Background="#000000"&gt; &lt;Ellipse Name="Circle" Margin="10" Fill="?????????" &gt; &lt;/Ellipse&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>The VB Code Behind it:</p> <pre><code>Partial Public Class CircleInSquare Private _CircleColor As Color Public Property CircleColor() As Color Get Return _CircleColor End Get Set(ByVal value As Color) _CircleColor = value End Set End Property End Class </code></pre> <p>When I use this user control, how can I apply a CircleColor to the control, and have it be shown as the Ellipse's fill color? Even better... can I give it a default color that shows up in the VS2008 Designer?</p> <p>So... if I place one of these into my window XAML like this:</p> <pre><code>&lt;app:CircleInSquare CircleColor="Blue" /&gt; </code></pre> <p>I would like the circle to display as Blue (or any other color I choose for that instance)</p>
<p>Sorry to repost, but After re-reading you post, I think that you might be better off with templating. I've attached some samples in VB</p> <p>Window.xaml</p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:WpfApplicationVB1" Title="Window1" Height="300" Width="300"&gt; &lt;Grid&gt; &lt;app:CircleInSquare Height="50" Width="50" CircleColor="Blue" SquareColor="Red" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>CircleInSquare.xaml.vb</p> <pre><code>Partial Public Class CircleInSquare Public Property CircleColor() As Brush Get Return GetValue(CircleColorProperty) End Get Set(ByVal value As Brush) SetValue(CircleColorProperty, value) End Set End Property Public Shared ReadOnly CircleColorProperty As DependencyProperty = _ DependencyProperty.Register("CircleColor", _ GetType(Brush), GetType(CircleInSquare), _ New FrameworkPropertyMetadata(Brushes.Black)) Public Property SquareColor() As Brush Get Return GetValue(SquareColorProperty) End Get Set(ByVal value As Brush) SetValue(SquareColorProperty, value) End Set End Property Public Shared ReadOnly SquareColorProperty As DependencyProperty = _ DependencyProperty.Register("SquareColor", _ GetType(Brush), GetType(CircleInSquare), _ New FrameworkPropertyMetadata(Brushes.Gray)) End Class </code></pre> <p>CircleInSquare.xaml</p> <pre><code>&lt;UserControl x:Class="CircleInSquare" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:app="clr-namespace:WpfApplicationVB1" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;UserControl.Template&gt; &lt;ControlTemplate&gt; &lt;Border x:Name="PART_Square" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}" Background="{TemplateBinding app:CircleInSquare.SquareColor}"&gt; &lt;Ellipse x:Name="PART_Ellipse" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}" Fill="{TemplateBinding app:CircleInSquare.CircleColor}" /&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;/UserControl.Template&gt; &lt;/UserControl&gt; </code></pre>
<p>You need to create a DependencyProperty in your CircleInSquare class. Do some googling on that. The concept of using the property for your circle class like below is called AttachedProperties, and you will probably need to handle the CircleColorChanged event to do what you need.</p> <pre><code>&lt;Ellipse app:CircleInSquare.CircleColor="Blue" /&gt; </code></pre>
46,743
<p>I wish to test a function that will generate <code>lorem ipsum</code> text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow:</p> <pre><code>Result = "&lt;p&gt;Some text&lt;/p&gt;"; Expected = array( '&lt;p' , 'regex', '/p' ); assertTags(resutl, expected) </code></pre> <p>I am using SimpleTest with CakePHP, but I think it should be a general question.</p>
<pre><code>$expected = array( '&lt;p', 'preg:/[A-Za-z\.\s\,]+/', '/p' ); </code></pre>
<p>Extend the SimpleExpectation class and then use your new Expectation class in the assert statement</p> <p>see: <a href="http://www.lastcraft.com/expectation_documentation.php#extending" rel="nofollow noreferrer">http://www.lastcraft.com/expectation_documentation.php#extending</a></p> <p>the example given is for validating an IP address but should be applicable to your problem:</p> <pre><code>class ValidIp extends SimpleExpectation { function test($ip) { return (ip2long($ip) != -1); } function testMessage($ip) { return "Address [$ip] should be a valid IP address"; } } </code></pre> <p>then in your test</p> <pre><code>$this-&gt;assert(new ValidIp(),$server-&gt;getIp()); </code></pre>
16,026
<p>I am considering using Maven for a Java open source project I manage.</p> <p>In the past, however, Maven has not always had the best reputation. What are your impressions of Maven, at this time? </p>
<p>For an open-source project, Maven has some advantages, especially for your contributors (eg mvn eclipse:eclipse).</p> <p>If you do go with Maven, the one rule you must follow religiously is: don't fight the tool. Layout your project exactly how Maven recommends, follow all its conventions and best practices. Every little fight you get into with Maven is a day you won't be spending writing code for your project.</p> <p>Also consider up front where you want to deploy your artifacts (are you going to host your own repository?).</p> <p>And don't be afraid to go with something other than Maven (eg Ant). The success of your project will be the project itself, not its build tool (so long as you choose a best-of-breed build tool, which both Ant and Maven are).</p>
<p>@MetroidFan2002: Maven 1 is deprecated and it's arguably more stable than Maven 2 (although less features). Writing Jelly script is definitely a bad idea.</p> <p>yc</p>
39,043
<p>Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.</p>
<p>Use <a href="http://lxml.de/" rel="nofollow noreferrer">lxml</a> which is the best xml/html library for python.</p> <pre><code>import lxml.html t = lxml.html.fromstring("...") t.text_content() </code></pre> <p>And if you just want to sanitize the html look at the lxml.html.clean <a href="http://lxml.de/lxmlhtml.html#cleaning-up-html" rel="nofollow noreferrer">module</a></p>
<p>Regular expressions are not scary, but writing your own regexes to strip HTML is a sure path to madness (and it won't work, either). Follow the path of wisdom, and use one of the many good HTML-parsing libraries.</p> <p>Lucas' example is also broken because "sub" is not a method of a Python string. You'd have to "import re", then call re.sub(pattern, repl, string). But that's neither here nor there, as the correct answer to your question does not involve writing any regexes.</p>
5,819
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.w3.org/Protocols/rfc822/#z28" rel="noreferrer">RFC 822 date-time</a> formatted string representation <strong>and</strong> parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the <a href="http://www.rssboard.org/rss-specification" rel="noreferrer">RSS Syndication Format</a>.</p>
<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-822 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC). I agree that this is not very elegant code, but it does the job.</p> <pre><code>/// &lt;summary&gt; /// Provides methods for converting &lt;see cref="DateTime"/&gt; structures /// to and from the equivalent &lt;a href="http://www.w3.org/Protocols/rfc822/#z28"&gt;RFC 822&lt;/a&gt; /// string representation. /// &lt;/summary&gt; public class Rfc822DateTime { //============================================================ // Private members //============================================================ #region Private Members /// &lt;summary&gt; /// Private member to hold array of formats that RFC 822 date-time representations conform to. /// &lt;/summary&gt; private static string[] formats = new string[0]; /// &lt;summary&gt; /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format. /// &lt;/summary&gt; private const string format = "ddd, dd MMM yyyy HH:mm:ss K"; #endregion //============================================================ // Public Properties //============================================================ #region Rfc822DateTimeFormat /// &lt;summary&gt; /// Gets the custom format specifier that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 822 format. /// &lt;/summary&gt; /// &lt;value&gt;A &lt;i&gt;DateTime format string&lt;/i&gt; that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 822 format.&lt;/value&gt; /// &lt;remarks&gt; /// &lt;para&gt; /// This method returns a string representation of a &lt;see cref="DateTime"/&gt; that utilizes the time zone /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes. /// The &lt;see cref="Rfc822DateTimeFormat"/&gt; is a valid date-time format string for use /// in the &lt;see cref="DateTime.ToString(String, IFormatProvider)"/&gt; method. /// &lt;/para&gt; /// &lt;para&gt; /// The &lt;a href="http://www.w3.org/Protocols/rfc822/#z28"&gt;RFC 822&lt;/a&gt; Date and Time specification /// specifies that the year will be represented as a two-digit value, but the /// &lt;a href="http://www.rssboard.org/rss-profile#data-types-datetime"&gt;RSS Profile&lt;/a&gt; recommends that /// all date-time values should use a four-digit year. The &lt;see cref="Rfc822DateTime"/&gt; class /// follows the RSS Profile recommendation when converting a &lt;see cref="DateTime"/&gt; to the equivalent /// RFC 822 string representation. /// &lt;/para&gt; /// &lt;/remarks&gt; public static string Rfc822DateTimeFormat { get { return format; } } #endregion #region Rfc822DateTimePatterns /// &lt;summary&gt; /// Gets an array of the expected formats for RFC 822 date-time string representations. /// &lt;/summary&gt; /// &lt;value&gt; /// An array of the expected formats for RFC 822 date-time string representations /// that may used in the &lt;see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/&gt; method. /// &lt;/value&gt; /// &lt;remarks&gt; /// The array of the expected formats that is returned assumes that the RFC 822 time zone /// is represented as or converted to a local differential representation. /// &lt;/remarks&gt; /// &lt;seealso cref="ConvertZoneToLocalDifferential(String)"/&gt; public static string[] Rfc822DateTimePatterns { get { if (formats.Length &gt; 0) { return formats; } else { formats = new string[35]; // two-digit day, four-digit year patterns formats[0] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz"; formats[1] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz"; formats[2] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz"; formats[3] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz"; formats[4] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz"; formats[5] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz"; formats[6] = "ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz"; formats[7] = "ddd',' dd MMM yyyy HH':'mm':'ss zzzz"; // two-digit day, two-digit year patterns formats[8] = "ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz"; formats[9] = "ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz"; formats[10] = "ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz"; formats[11] = "ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz"; formats[12] = "ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz"; formats[13] = "ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz"; formats[14] = "ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz"; formats[15] = "ddd',' dd MMM yy HH':'mm':'ss zzzz"; // one-digit day, four-digit year patterns formats[16] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz"; formats[17] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz"; formats[18] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz"; formats[19] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz"; formats[20] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz"; formats[21] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz"; formats[22] = "ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz"; formats[23] = "ddd',' d MMM yyyy HH':'mm':'ss zzzz"; // two-digit day, two-digit year patterns formats[24] = "ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz"; formats[25] = "ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz"; formats[26] = "ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz"; formats[27] = "ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz"; formats[28] = "ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz"; formats[29] = "ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz"; formats[30] = "ddd',' d MMM yy HH':'mm':'ss'.'f zzzz"; formats[31] = "ddd',' d MMM yy HH':'mm':'ss zzzz"; // Fall back patterns formats[32] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern; formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern; return formats; } } } #endregion //============================================================ // Public Methods //============================================================ #region Parse(string s) /// &lt;summary&gt; /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent. /// &lt;/summary&gt; /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt; /// &lt;returns&gt; /// A &lt;see cref="DateTime"/&gt; equivalent to the date and time contained in &lt;paramref name="s"/&gt;, /// expressed as &lt;i&gt;Coordinated Universal Time (UTC)&lt;/i&gt;. /// &lt;/returns&gt; /// &lt;remarks&gt; /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object. /// &lt;/remarks&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is an empty string.&lt;/exception&gt; /// &lt;exception cref="FormatException"&gt;&lt;paramref name="s"/&gt; does not contain a valid RFC 822 string representation of a date and time.&lt;/exception&gt; public static DateTime Parse(string s) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ if (String.IsNullOrEmpty(s)) { throw new ArgumentNullException("s"); } DateTime result; if (Rfc822DateTime.TryParse(s, out result)) { return result; } else { throw new FormatException(String.Format(null, "{0} is not a valid RFC 822 string representation of a date and time.", s)); } } #endregion #region ConvertZoneToLocalDifferential(string s) /// &lt;summary&gt; /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset). /// &lt;/summary&gt; /// &lt;param name="s"&gt;A string containing an RFC 822 date and time to convert.&lt;/param&gt; /// &lt;returns&gt;A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in &lt;paramref name="s"/&gt;.&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is an empty string.&lt;/exception&gt; public static string ConvertZoneToLocalDifferential(string s) { string zoneRepresentedAsLocalDifferential = String.Empty; //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ if (String.IsNullOrEmpty(s)) { throw new ArgumentNullException("s"); } if(s.EndsWith(" UT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" UT") + 1) ), "+00:00"); } else if (s.EndsWith(" GMT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" GMT") + 1 ) ), "+00:00"); } else if (s.EndsWith(" EST", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" EST") + 1)), "-05:00"); } else if (s.EndsWith(" EDT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" EDT") + 1)), "-04:00"); } else if (s.EndsWith(" CST", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" CST") + 1)), "-06:00"); } else if (s.EndsWith(" CDT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" CDT") + 1)), "-05:00"); } else if (s.EndsWith(" MST", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" MST") + 1)), "-07:00"); } else if (s.EndsWith(" MDT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" MDT") + 1)), "-06:00"); } else if (s.EndsWith(" PST", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" PST") + 1)), "-08:00"); } else if (s.EndsWith(" PDT", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" PDT") + 1)), "-07:00"); } else if (s.EndsWith(" Z", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" Z") + 1)), "+00:00"); } else if (s.EndsWith(" A", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" A") + 1)), "-01:00"); } else if (s.EndsWith(" M", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" M") + 1)), "-12:00"); } else if (s.EndsWith(" N", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" N") + 1)), "+01:00"); } else if (s.EndsWith(" Y", StringComparison.OrdinalIgnoreCase)) { zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(" Y") + 1)), "+12:00"); } else { zoneRepresentedAsLocalDifferential = s; } return zoneRepresentedAsLocalDifferential; } #endregion #region ToString(DateTime utcDateTime) /// &lt;summary&gt; /// Converts the value of the specified &lt;see cref="DateTime"/&gt; object to its equivalent string representation. /// &lt;/summary&gt; /// &lt;param name="utcDateTime"&gt;The Coordinated Universal Time (UTC) &lt;see cref="DateTime"/&gt; to convert.&lt;/param&gt; /// &lt;returns&gt;A RFC 822 string representation of the value of the &lt;paramref name="utcDateTime"/&gt;.&lt;/returns&gt; /// &lt;exception cref="ArgumentException"&gt;The specified &lt;paramref name="utcDateTime"/&gt; object does not represent a &lt;see cref="DateTimeKind.Utc"&gt;Coordinated Universal Time (UTC)&lt;/see&gt; value.&lt;/exception&gt; public static string ToString(DateTime utcDateTime) { if (utcDateTime.Kind != DateTimeKind.Utc) { throw new ArgumentException("utcDateTime"); } return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo); } #endregion #region TryParse(string s, out DateTime result) /// &lt;summary&gt; /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent. /// &lt;/summary&gt; /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt; /// &lt;param name="result"&gt; /// When this method returns, contains the &lt;see cref="DateTime"/&gt; value equivalent to the date and time /// contained in &lt;paramref name="s"/&gt;, expressed as &lt;i&gt;Coordinated Universal Time (UTC)&lt;/i&gt;, /// if the conversion succeeded, or &lt;see cref="DateTime.MinValue"&gt;MinValue&lt;/see&gt; if the conversion failed. /// The conversion fails if the s parameter is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic), /// or does not contain a valid string representation of a date and time. /// This parameter is passed uninitialized. /// &lt;/param&gt; /// &lt;returns&gt;&lt;b&gt;true&lt;/b&gt; if the &lt;paramref name="s"/&gt; parameter was converted successfully; otherwise, &lt;b&gt;false&lt;/b&gt;.&lt;/returns&gt; /// &lt;remarks&gt; /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object. /// &lt;/remarks&gt; public static bool TryParse(string s, out DateTime result) { //------------------------------------------------------------ // Attempt to convert string representation //------------------------------------------------------------ bool wasConverted = false; result = DateTime.MinValue; if (!String.IsNullOrEmpty(s)) { DateTime parseResult; if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult)) { result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc); wasConverted = true; } } return wasConverted; } #endregion } </code></pre>
<p>Based on the answer of Kirk Liemohn, I used this method with success:</p> <pre><code>private DateTimeOffset? ParseDate(string date) { const string FORMAT = &quot;ddd, d MMM yyyy HH:mm:ss zzz&quot;; const string FORMAT2 = &quot;ddd, dd MMM yyyy HH:mm:ss zzz&quot;; const string FORMAT3 = &quot;dd MMM yyyy HH:mm:ss zzz&quot;; const string FORMAT4 = &quot;d MMM yyyy HH:mm:ss zzz&quot;; DateTimeOffset d; if (DateTimeOffset.TryParseExact(date, new string[] { FORMAT, FORMAT2, FORMAT3, FORMAT4 }, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out d)) return d; return null; } </code></pre> <p>Example:</p> <pre><code>DateTimeOffset? date = ParseDate(&quot;Thu, 5 Apr 2012 23:47:37 +0200&quot;); Console.WriteLine(date.ToString()); // =&gt; 05/04/2012 23:47:37 +02:00 </code></pre> <p>It does not respect full spec of RFC but it works for my use cases.</p> <p>Specifically, it does not work with timezone express like : &quot;GMT&quot;, &quot;CST&quot;, etc. (see <a href="https://www.rfc-editor.org/rfc/rfc822#section-5.1" rel="nofollow noreferrer">&quot;zone&quot; in RFC822 Section 5.1</a>). See the <a href="https://stackoverflow.com/a/37550344/249742">better answer of Oleksandr Pshenychnyy</a>.</p>
36,137
<p>I am developing a scientific application used to perform physical simulations. The algorithms used are O(n3), so for a large set of data it takes a very long time to process. The application runs a simulation in around 17 minutes, and I have to run around 25,000 simulations. That is around one year of processing time.</p> <p>The good news is that the simulations are completely independent from each other, so I can easily change the program to distribute the work among multiple computers.</p> <p>There are multiple solutions I can see to implement this:</p> <ul> <li>Get a multi-core computer and distribute the work among all the cores. Not enough for what I need to do.</li> <li>Write an application that connects to multiple "processing" servers and distribute the load among them. </li> <li>Get a cluster of cheap linux computers, and have the program treat everything as a single entity.</li> </ul> <p>Option number 2 is relatively easy to implement, so I don't look so much for suggestions for how to implement this (Can be done just by writing a program that waits on a given port for the parameters, processes the values and returns the result as a serialized file). That would be a good example of <a href="http://en.wikipedia.org/wiki/Grid_computing" rel="nofollow noreferrer" title="Grid Computing">Grid Computing</a>.</p> <p>However, I wonder at the possibilities of the last option, a traditional cluster. How difficult is to run a Java program in a linux grid? Will all the separate computers be treated as a single computer with multiple cores, making it thus easy to adapt the program? Is there any good pointers to resources that would allow me to get started? Or I am making this over-complicated and I am better off with option number 2?</p> <p>EDIT: As extra info, I am interested on how to implement something like described in this article from Wired Magazine: <a href="http://www.wired.com/techbiz/it/news/2007/10/ps3_supercomputer" rel="nofollow noreferrer">Scientific replaced a supercomputer with a Playstation 3 linux cluster</a>. Definitively number two sounds like the way to go... but the coolness factor.</p> <p>EDIT 2: The calculation is very CPU-Bound. Basically there is a lot of operations on large matrixes, such as inverse and multiplication. I tried to look for better algorithms for these operations but so far I've found that the operations I need are 0(n3) (In libraries that are normally available). The data set is large (for such operations), but it is created on the client based on the input parameters.</p> <hr> <p>I see now that I had a misunderstanding on how a computer cluster under linux worked. I had the assumption that it would work in such a way that it would just appear that you had all the processors in all computers available, just as if you had a computer with multiple cores, but that doesn't seem to be the case. It seems that all these supercomputers work by having nodes that execute tasks distributed by some central entity, and that there is several different libraries and software packages that allow to perform this distribution easily.</p> <p>So the question really becomes, as there is no such thing as number 3, into: What is the best way to create a clustered java application?</p>
<p>I would very highly recommend the Java Parallel Processing Framework especially since your computations are already independant. I did a good bit of work with this undergraduate and it works very well. The work of doing the implementation is already done for you so I think this is a good way to achieve the goal in "number 2."</p> <p><a href="http://www.jppf.org/" rel="noreferrer">http://www.jppf.org/</a></p>
<p>You already suggested it, but disqualified it: Multi cores. You could go for multi core, if you had enough cores. One hot topic atm is GPGPU computing. Esp. NVIDIAs CUDA is a very priomising approach if you have many independent task which have to do the same computation. A GTX 280 delivers you 280 cores, which can compute up to 1120 - 15360 threads simultanously . A pair of them could solve your problem. If its really implementable depends on your algorithm (data flow vs. control flow), because all scalar processors operate in a SIMD fashion. </p> <p>Drawback: it would be C/C++, not java</p>
43,246
<p>In Oracle, I have set the <code>log_archive_dest1='D:\app\administrator\orcl\archive'</code> parameter and shutdown the database. When I tried to start up the db, I got the following error:</p> <pre><code>SQL&gt; startup mount; ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated ORA-09291: sksachk: invalid device specified for archive destination OSD-04018: Unable to access the specified directory or device. O/S-Error: (OS 3) The system cannot find the path specified. </code></pre> <p>Does anyone have any ideas of how I might fix this?</p>
<p>You probably need a trailing \ on the dir name</p> <p>ie D:\app\administrator\orcl\archive\</p>
<p>I've never used Oracle but some things you might try are</p> <ul> <li>Make sure the permissions on the file path you're using allow the database to read / write to it?</li> <li>Make sure all the folders in the path already exist</li> <li>On Windows you might find the '\' characters confuse the database. Do you specify other paths in the same way for Oracle? An alternative may be to use '/' instead of '\'. Different programs that originated in the Unix world handle Windows paths in different ways</li> </ul>
17,866
<p>I have two C DLLs that I need to access in the same executable. I have header files and .LIB files for both libraries. Unfortunately a subset of the functions that I need to access have the exact same names. The best solution I have been able to come up with so far is to use LoadLibrary to load one of the DLLs and explicitly call its methods using GetProcAddress. Is there a way for me to implicitly load both libraries and somehow give the compiler a hint that in one case I want to call OpenApi in DLL A and in the other case I want to call OpenApi in DLL B?</p> <p>I'm developing my executable in C++ using Visual Studio 2008 and the corresponding C runtime library (msvcr90.dll).</p> <p>[Edit]</p> <p>Commenter Ilya asks below what I don't like about the GetProcAddress solution. I don't like it for two reasons:</p> <ol> <li>It makes the code more complex. One line of code to call a function is replaced with three lines of code, one to define the function signature, one to call GetProcAddress, and one to actually call the function. </li> <li>It's more prone to run-time errors. If I misspell the function name or mess up the signature I don't see the error until run-time. Say I decide to integrate a new version of the dll and one of the method names has changed, it will compile just fine and won't have a problem until the actual call to GetProcAddress, which could possibly even be missed in a test pass.</li> </ol>
<p>It used to be you could 'rename' an imported symbol using a linker .def file. You probably still can, but it's been so long since .def files have been widely used, it's difficult to locate documentation.</p> <p>The current MSDN documentation lists the IMPORTS directive as a 'reserved keyword'. I'm not sure if this means they removed the functionality, or if they just don't want to support it anymore.</p> <p>Here's on page that describes the IMPORTS directive:</p> <p><a href="http://www.digitalmars.com/ctg/ctgDefFiles.html#imports" rel="nofollow noreferrer">http://www.digitalmars.com/ctg/ctgDefFiles.html#imports</a></p> <p>Other kludgy alternatives are:</p> <ol> <li><p>create wrapper functions for the conflicting APIs. Those functions can do the <code>LoadLibrary()/GetProcAddress()</code> dance. All other non-conflicting functions can be implicitly linked as normal. Actually, this solution is probably the least kludgy of the 3 in this answer.</p></li> <li><p>create 2 wrapper DLLs such that each links only to one or the other library with the conflicting names. Use differing names in the wrapper DLLs that simply thunk over to the real librarys. Note the wrapper libraries do not need to wrap all the API's - they just need to wrap the conflicting ones.</p></li> </ol>
<p>You may be able to build new import library files that rename the functions in question and then implicitly link with both DLL modules using these new import libraries. Here is a Microsoft Knowledge Base article that describes the process: <a href="http://support.microsoft.com/kb/131313" rel="nofollow noreferrer">How To Create 32-bit Import Libraries Without .OBJs or Source</a>.</p>
36,293
<p>How can I replace multiple spaces in a string with only one space in C#?</p> <p>Example:</p> <pre><code>1 2 3 4 5 </code></pre> <p>would be:</p> <pre><code>1 2 3 4 5 </code></pre>
<pre><code>string sentence = "This is a sentence with multiple spaces"; RegexOptions options = RegexOptions.None; Regex regex = new Regex("[ ]{2,}", options); sentence = regex.Replace(sentence, " "); </code></pre>
<p>I looked over proposed solutions, could not find the one that would handle mix of white space characters acceptable for my case, for example:</p> <ul> <li><code>Regex.Replace(input, @&quot;\s+&quot;, &quot; &quot;)</code> - it will eat your line breaks, if they are mixed with spaces, for example <code>\n \n</code> sequence will be replaced with <code> </code></li> <li><code>Regex.Replace(source, @&quot;(\s)\s+&quot;, &quot;$1&quot;)</code> - it will depend on whitespace first character, meaning that it again might eat your line breaks</li> <li><code>Regex.Replace(source, @&quot;[ ]{2,}&quot;, &quot; &quot;)</code> - it won't work correctly when there's mix of whitespace characters - for example <code>&quot;\t \t &quot;</code></li> </ul> <p>Probably not perfect, but quick solution for me was:</p> <pre><code>Regex.Replace(input, @&quot;\s+&quot;, (match) =&gt; match.Value.IndexOf('\n') &gt; -1 ? &quot;\n&quot; : &quot; &quot;, RegexOptions.Multiline) </code></pre> <p>Idea is - line break wins over the spaces and tabs.</p> <p>This won't handle windows line breaks correctly, but it would be easy to adjust to work with that too, don't know regex that well - may be it is possible to fit into single pattern.</p>
25,321
<p>I need to build a terminal-like application that needs to be used under my usual Ubuntu install but also under Windows. I've been looking for a terminal component that accepts commands and is able to show some kind of command history together with output.</p> <p>There is a component called VTE that is used in gnome-terminal, but I have not been able to compile it under Windows because it depends on some Unix-specific functions (as it seems). Do you know of any other terminal-like GTK components that can be built under Windows or some way to build VTE?</p>
<p>Maybe you want to look at the old GNOME widget called zvt, it might have been ported to Win32.</p>
<p>Gnuplot wxt provides a terminal which is compiled with GTK on X and uses the win32 API on windows. It uses the WxWindows interface to compile into both environments.</p>
44,452
<p>I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line. </p> <p>This is on</p> <ul> <li>Eclipse 3.3</li> <li>JDK 1.5</li> <li>Windows XP Professional</li> </ul> <p>Any clues?</p> <p>Error given on the command line is:</p> <pre><code>Icons.java:16: code too large public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, ^ </code></pre> <p>The code line in question is:</p> <pre><code>public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, 0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64, -8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72, -72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56, -24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56, -64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72, -72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40, -56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104, -40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80, -32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88, 104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64, -112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80, -88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96, -112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72, -32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120, 96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120, -16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88, -104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88, -24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120, -8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104, 112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72, -128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72, -128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104, -48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120, -40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40, -48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56, -24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24, -56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120, -48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112, -120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120, -104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56, -128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72, -40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96, 72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104, 80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88, 120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120, 96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120, 72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72, -88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112, 112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120, 120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112, -24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120, -72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96, -120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104, -72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128, -96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112, 96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56, -88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72, -96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40, -48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64, -32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104, -88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96, -96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0, 50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125, 8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79, -94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19, 48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64, 12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40, 64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47, 17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16, -71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28, -61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72, 34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18, 44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4, 6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32, 109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31, 91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40, -103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105, 40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113, 13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61, -94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81, 23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37, -40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54, -36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108, -27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6, 34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82, -62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117, 112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104, -56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18, 84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24, 114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123, 53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78, -47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76, 21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80, 65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1, -60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32, 102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51, 120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124, 116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79, 12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40, -1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3, 32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47, -33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52, 80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83, 7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42, 12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10, -88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107, -108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121, -125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128, -4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33, -121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69, -110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106, 32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90, 81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60, -15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31, 84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45, 63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4, -82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66, 40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80, 64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48, -48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20, 59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122, 25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1, 52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35, 1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114, -11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12, -84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55, 23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68, 9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1, 18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32, -2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40, 65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70, -16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14, -30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31, -16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88, 102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67, 100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80, 7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64, 65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2, 122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128, -121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120, 34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89, 32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17, 108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16, -116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84, 80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71, -8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47, 18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53, 90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117, 106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128, 47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80, 76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126, 11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2, 55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71, -15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51, -124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5, -112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9, 51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39, 67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 }; </code></pre>
<p>Taking from <a href="http://forums.sun.com/thread.jspa?threadID=747860&amp;messageID=4278559" rel="nofollow noreferrer">this forum on Sun's support site</a>, no method can be more than 64 KB long:</p> <p>When you have code (pseudo) like the following...</p> <pre><code>class MyClass { private String[] s = { "a", "b", "c"} public MyClass() { } </code></pre> <p>The compiler ends up producing code that basically looks like the following.</p> <pre><code>class MyClass { private String[] s; private void FunnyName$Method() { s[0] = "a"; s[1] = "b"; s[2] = "c"; } public MyClass() { FunnyName$Method(); } </code></pre> <p>And as noted java limits all methods to 64k, even the ones the compiler creates.</p> <p>It may be that Eclipse is doing something sneaky to get around this, but I assure you this is still possible in Eclipse because I have seen the same error message. A better solution is to just read from a static file, like this:</p> <pre><code>public class Icons { public static final byte[] compileIcon; static { compileIcon = readFileToBytes("compileIcon.gif"); } //... (I assume there are several other icons) private static byte[] readFileToBytes(String filename) { try { File file = new File(filename); byte[] bytes = new byte[(int)file.length()]; FileInputStream fin = new FileInputStream(file); fin.read(bytes); fin.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } </code></pre>
<p>Hard to say from what's provided, but guesses are</p> <ol> <li>Different JVM in Eclipse than command line.</li> <li>Bad classpath settings in command line.</li> </ol> <p>What are the compile errors?</p> <p>Can you isolate the problem in a dummy class for demonstration?</p>
14,101
<p>I can't retrieve cookie maxage it always returns -1</p> <p>Creating cookie:</p> <pre><code>Cookie securityCookie = new Cookie("sec", "somevalue"); securityCookie.setMaxAge(EXPIRATION_TIME); </code></pre> <p>Retrieve cookie:</p> <pre><code>Cookie[] cookies = request.getCookies(); if (cookies != null) { for(int i=0; i&lt;cookies.length; i++) { Cookie cookie = cookies[i]; if ("sec".equals(cookie.getName())){ int age = cookie.getMaxAge(); } } } </code></pre> <p>i am always getting age = -1</p> <p>also when i check in firefox cookie expiration i see strange date.</p> <p>Thx</p>
<p>When a browser sends a cookie back to the origin server, it doesn't include any age. So it is logical that your "retrieve" code above does not receive a max age: it is not included in the request.</p> <p>When the cookie is received from the server, the browser uses the max age parameter to determine how long the cookie should be kept; the age is never communicated back to the server, an expired cookie is simply discarded. When processing a request, if you want to renew the age of the cookie, reinclude the cookie in the response.</p> <p>Also see the section "Sending Cookies to the Origin Server" in the <a href="http://www.w3.org/Protocols/rfc2109/rfc2109" rel="noreferrer">RFC</a>.</p>
<p>The value may be modified by the browser.</p> <p>You create a cookie and want to set a max age. The cookie is sent to the browser. The browser may reject the cookie or ignore a max age too long for its policy. This modified cookie is sent back to your application.</p> <p>Check your browser settings.</p>
21,410
<p>I'm working on a stored procedure in SQL Server 2000 with a temp table defined like this:</p> <pre>CREATE TABLE #MapTable (Category varchar(40), Code char(5))</pre> <p>After creating the table I want to insert some standard records (which will then be supplemented dynamically in the procedure). Each category (about 10) will have several codes (typically 3-5), and I'd like to express the insert operation for each category in one statement. </p> <p>Any idea how to do that? </p> <p>The best idea I've had so far is to keep a real table in the db as a template, but I'd really like to avoid that if possible. The database where this will live is a snapshot of a mainframe system, such that the entire database is blown away every night and re-created in a batch process- stored procedures are re-loaded from source control at the end of the process.</p> <p>The issue I'm trying to solve isn't so much keeping it to one statement as it is trying to avoid re-typing the category name over and over.</p>
<p>DJ's is a fine solution but could be simplified (see below).</p> <p>Why does it need to be a single statement?</p> <p>What's wrong with:</p> <pre><code>insert into #MapTable (category,code) values ('Foo','AAAAA') insert into #MapTable (category,code) values ('Foo','BBBBB') insert into #MapTable (category,code) values ('Foo','CCCCC') insert into #MapTable (category,code) values ('Bar','AAAAA') </code></pre> <p>For me this is much easier to read and maintain.</p> <hr> <p>Simplified DJ solution:</p> <pre><code>CREATE TABLE #MapTable (Category varchar(40), Code char(5)) INSERT INTO #MapTable (Category, Code) SELECT 'Foo', 'AAAAA' UNION SELECT 'Foo', 'BBBBB' UNION SELECT 'Foo', 'CCCCC' SELECT * FROM #MapTable </code></pre> <p>There's nothing really wrong with DJ's, it just felt overly complex to me.</p> <hr> <p>From the OP:</p> <blockquote> <p>The issue I'm trying to solve isn't so much keeping it to one statement as it is trying to avoid re-typing the category name over and over.</p> </blockquote> <p>I feel your pain -- I try to find shortcuts like this too and realize that by the time I solve the problem, I could have typed it long hand.</p> <p>If I have a lot of repetitive data to input, I'll sometimes use Excel to generate the insert codes for me. Put the Category in one column and the Code in another; use all of the helpful copying techniques to do the hard work</p> <p>then </p> <pre><code>="insert into #MapTable (category,code) values ('"&amp;A1&amp;"','"&amp;B1&amp;"')" </code></pre> <p>in a third row and I've generated my inserts</p> <p>Of course, all of this is assuming that the Categories and Codes can't be pulled from a system table.</p>
<p>This might work for you:</p> <pre><code>CREATE TABLE #MapTable (Category varchar(40), Code char(5)) INSERT INTO #MapTable SELECT X.Category, X.Code FROM (SELECT 'Foo' as Category, 'AAAAA' as Code UNION SELECT 'Foo' as Category, 'BBBBB' as Code UNION SELECT 'Foo' as Category, 'CCCCC' as Code) AS X SELECT * FROM #MapTable </code></pre>
30,256
<p>I am using Qt Dialogs in one of my application. I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.</p>
<p>By default the <em>Qt::WindowContextHelpButtonHint</em> flag is added to dialogs. You can control this with the <em>WindowFlags</em> parameter to the dialog constructor. </p> <p>For instance you can specify only the <em>TitleHint</em> and <em>SystemMenu</em> flags by doing:</p> <pre><code>QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint); d-&gt;exec(); </code></pre> <p>If you add the <em>Qt::WindowContextHelpButtonHint</em> flag you will get the help button back.</p> <p>In PyQt you can do:</p> <pre><code>from PyQt4 import QtGui, QtCore app = QtGui.QApplication([]) d = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) d.exec_() </code></pre> <p>More details on window flags can be found on the <a href="https://doc.qt.io/qt-5.7/qt.html#WindowType-enum" rel="noreferrer">WindowType enum</a> in the Qt documentation.</p>
<p>I couldn't find a slot but you can override the virtual <code>winEvent</code> function.</p> <pre><code>#if defined(Q_WS_WIN) bool MyWizard::winEvent(MSG * msg, long * result) { switch (msg-&gt;message) { case WM_NCLBUTTONDOWN: if (msg-&gt;wParam == HTHELP) { } break; default: break; } return QWizard::winEvent(msg, result); } #endif </code></pre>
10,734
<p>I have the following code:</p> <pre><code>string prefix = "OLD:"; Func&lt;string, string&gt; prependAction = (x =&gt; prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.</p> <p>Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:</p> <pre><code>Func&lt;string, string&gt; prependAction = (x =&gt; "OLD:" + x); </code></pre> <p>The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. </p> <p>The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:</p> <pre><code>string prefix = "NEW:"; var prepender = new Prepender {Prefix = prefix}; Func&lt;string, string&gt; prependAction = prepender.Prepend; prefix = "OLD:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>With helper class:</p> <pre><code>[Serializable] public class Prepender { public string Prefix { get; set; } public string Prepend(string str) { return Prefix + str; } } </code></pre> <p>This seems like a lot of extra work to get the compiler to be "dumb".</p>
<p>I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization". There is an explanation of it <a href="http://social.msdn.microsoft.com/Forums/en-US/67f63b9a-ea44-4428-aea0-5dcdb61e918b/binding-lambdas-when-they-are-closures" rel="nofollow noreferrer">here</a>.</p>
<p>What about this</p> <pre><code>string prefix = "OLD:"; string _prefix=prefix; Func&lt;string, string&gt; prependAction = (x =&gt; _prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); </code></pre>
13,578
<p>When you link to an unmanaged library (say 'A.dll') which in turn links to another library ('B.dll'), and B.dll is missing, you will get a run-time error message about failing to load 'B.dll'.</p> <p>But when you P/Invoke into 'A.dll' from managed code, you'll get a general exception of this form:</p> <p>Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'A.dll': The specified module could not be found.</p> <p>How can I get an error message that pinpoints the specific unmanaged dll file that failed to load, when p/invoking from managed code ?</p>
<p>I don't think there's any specific API you can use to pinpoint why <code>LoadLibrary</code> (the underlying Win32 API) failed for 'A.dll'. I recommend the use of a tool like <a href="http://www.dependencywalker.com/" rel="nofollow noreferrer">Dependency Walker</a> to troubleshoot DLL loading errors.</p>
<p>I'm not sure how you can get this in the form of an exception. When I run into this problem I usually try and open the DLL with depends.exe. It's pretty good and reporting missing dependencies that exist if the DLL is simply loaded from it's current location.</p>
33,805
<p>I have a column that contains dates, when I click the column header the column is sorted numerically and not by date. How would I sort this by date? The date is in the format dd/mm/yy.</p> <p>Example (sorted oldest first):</p> <p>10/12/08 &lt;--December 10/09/08 &lt;--September 12/12/08 &lt;--December</p> <p>Many thanks</p>
<p>Is the source a datatable? If so, you'll probably need to specify that the column in question is of type DateTime:</p> <pre><code>myDataTable.Columns["ColumnName"].DataType = System.Type.GetType("System.Date"); </code></pre> <p>Hope that helps!</p>
<p>When the datagrid is not bound to a datasource and the dataGrid is filled row by row, the following approach works for me:</p> <pre><code>//Init dataGridView_records.Columns[0].DefaultCellStyle.Format = "dd/MM/yy HH:mm:ss"; </code></pre> <p>then fill the datagrid as follows:</p> <pre><code>DateTime date = DateTime.ParseExact((String)drs["data"], "dd/MM/yy HH:mm:ss", CultureInfo.InvariantCulture); object[] gdr = new object[1] { date };//add the other columns data here dataGridView_records.Rows.Add(gdr); </code></pre>
48,183
<p>I am trying to establish the best practice for handling the creation of child objects when the parent object is incomplete or doesn't yet exist in a web application. I want to handle this in a stateless way so in memory objects are out.</p> <p>For example, say we have a bug tracking application.</p> <p>A Bug has a title and a description (both required) and any number of attachments. So the "Bug" is the parent object with a list of "Attachment" children.</p> <p>So you present a page with a title input, a description input, and a file input to add an attachment. People then add the attachments but we haven't created the Parent Bug as yet.</p> <p>How do you handle persisting the added attachments ? </p> <p>Obviously we have to keep track of the attachments added, but at this point we haven't persisted the parent "Bug" object to attach the "Attachment" to.</p>
<p>Create the incomplete bug and define a process for handling incompleteness. (Wait X minutes/hours/days, then delete it/email someone/accept it as it is.) Even without a title or description, knowing that a problem occurred and the information in the attachment is potentially useful. The attachment may include a full description, but the user just put it somewhere other than you'd attended. Or it may only contain scattered data points which are meaningless on their own - but could corroborate another user's report.</p>
<p>In this case I would consider storing the attachments in some type of temporary storage, be it Session State, a temp directory on the file system, or perhaps a database. Once the bug has been saved, I would then copy the attachments to their actual place.</p> <p>Careful with session though, if you let them upload large attachments you could push memory issues depending on your environment. </p> <p>One approach I saw before was as soon as the user opens the new bug form, a new bug is generated in your database. Depending on your app this may or may not be a good thing. If your collecting data from a user for example, this is useful as you get some intelligence even if they fail to enter the data, and leave your site. You still know they started the process, and whatever else you collected like user agent etc..</p>
42,757
<p>In Cura, when you enable "Print support structure", is there a way to see what it will look like?</p>
<p>Select the View Modes Button in the upper right hand corner, and select Layers.</p> <p><a href="https://i.stack.imgur.com/grPQi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/grPQi.png" alt="Cura"></a></p>
<p>Cura generates support based on the outlines of the layers which will be printed, rather based on the triangles of the 3D model. It is therefore not possible to show the generated support in the solid view.</p> <p>You can view the support in the layer view however. In Cura 2 that's on the left bottom of the screen.</p> <p><a href="https://i.imgur.com/2rkCslJ.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/2rkCslJ.png" alt="Cura"></a></p> <p>Support is classified as a helper part in the legend of the layer view.</p>
205
<p>On our site, we get a large amount of photos uploaded from various sources. </p> <p>In order to keep the file sizes down, we strip all <a href="http://en.wikipedia.org/wiki/Exif" rel="noreferrer">exif data</a> from the source using <a href="http://www.imagemagick.org/www/mogrify.html" rel="noreferrer">mogrify</a>:</p> <pre><code>mogrify -strip image.jpg </code></pre> <p>What we'd like to be able to do is to insert some basic exif data (Copyright Initrode, etc) back onto this new "clean" image, but I can't seem to find anything in the docs that would achieve this.</p> <p>Has anybody any experience of doing this? </p> <p>If it can't be done through imagemagick, a PHP-based solution would be the next best thing!</p> <p>Thanks.</p>
<p>You can save a large amount of space, especially if you have a large number of images..</p> <p>Add the following to text.txt (format of the IPTC tags taken from <a href="http://www.narf.ssji.net/~shtrom/wiki/tips/imagemanipulation" rel="noreferrer">here</a>):</p> <pre><code>2#110#Credit="My Company" 2#05#Object Name="THE_OBJECT_NAME" 2#55#Date Created="2011-02-03 12:45" 2#80#By-line="BY-LINE?" 2#110#Credit="The CREDIT" 2#115#Source="SOURCE" 2#116#Copyright Notice="THE COPYRIGHT" 2#118#Contact="THE CONTACT" 2#120#Caption="AKA Title" </code></pre> <p>Strip all existing exif data from the image</p> <pre><code>mogrify -strip image.jpg </code></pre> <p>Add the credit to your image</p> <pre><code>mogrify -profile 8BIMTEXT:text.txt image.jpg </code></pre>
<p>I doubt you will gain lot of space by removing Exif information...</p> <p>Anyway, I can be wrong, but Exif metadata belongs more to store technical (and contextual) information. For stuff like copyright, you should use IPTC instead.</p> <p>That's something you can do, apparently, with ImageMagick: <a href="http://www.experts-exchange.com/Software/Photos_Graphics/Web_Graphics/Q_21093317.html" rel="nofollow noreferrer" title="Write IPTC Data to Jpeg with ImageMagick">Write IPTC Data to Jpeg with ImageMagick</a>.</p>
28,404
<p>I've got the following code to end a process, but I still receive an error code 2 (Access Denied).</p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:\\" &amp; strComputer &amp; "\root\cimv2") Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'") For each objProcess in colProcessList wscript.echo objProcess.processid intrc = objProcess.Terminate() if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " &amp; intrc End if </code></pre>
<p>It's quite legitimate to get "access denied" for ending a program. If it's a service (which I'm guessing mssearch.exe is), then it is probably running as the "SYSTEM" user, which has higher privileges than even the Administrator account.</p> <p>You can't log on as the SYSTEM account, but you could probably write a service to manage other services...</p>
<p>As a non-privileged user, you can only end processes you own. In a multiuser environment this can bite you in the ankle, because WMI would return equally named processes from other users as well, unless you write a more specific WQL query.</p> <p>If your process is a service, and your script runs under a privileged account, you may still need to take "the regular route" to stop it, for example using <code>WScript.Shell</code> to call <code>net stop</code> or <code>sc.exe</code>, or, more elegantly, using the <code>Win32_Service</code> class:</p> <pre><code>Set Services = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Service WHERE Name = '" &amp; ServiceName &amp; "'") For Each Service In Services Service.StopService() WSCript.Sleep 2000 ' wait for the service to terminate ' Next </code></pre>
27,788
<p>I'm writing a little tile-based game, for which I'd like to support light sources. But my algorithm-fu is too weak, hence I come to you for help.</p> <p>The situation is like this: There is a tile-based map (held as a 2D array), containing a single light source and several items standing around. I want to calculate which tiles are lit up by the light source, and which are in shadow.</p> <p>A visual aid of what it would look like, approximately. The L is the light source, the Xs are items blocking the light, the 0s are lit tiles, and the -s are tiles in shadow.</p> <pre><code>0 0 0 0 0 0 - - 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 L 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X 0 0 0 0 0 - - - - - 0 0 0 - - - - - - - </code></pre> <p>A fractional system would be even better, of course, where a tile can be in half-shadow due to being partially obscured. The algorithm wouldn't have to be perfect - just not obviously wrong and reasonably fast.</p> <p>(Of course, there would be multiple light sources, but that's just a loop.)</p> <p>Any takers?</p>
<p>The roguelike development community has a bit of an obsession with line-of-sight, field-of-view algorithms.</p> <p>Here's a link to a roguelike wiki article on the subject: <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision" rel="noreferrer">http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision</a></p> <p>For my roguelike game, I implemented a shadow casting algorithm (<a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Shadow_casting" rel="noreferrer">http://roguebasin.roguelikedevelopment.org/index.php?title=Shadow_casting</a>) in Python. It was a bit complicated to put together, but ran reasonably efficiently (even in pure Python) and generated nice results.</p> <p>The "Permissive Field of View" seems to be gaining popularity as well: <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View" rel="noreferrer">http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View</a></p>
<p>If you don't want to spend the time to reinvent/re-implement this, there are plenty of game engines out there. <a href="http://www.ogre3d.org/" rel="nofollow noreferrer">Ogre3D</a> is an open source game engine that fully supports lighting, as well as sound and game controls.</p>
21,051
<p>I've got a php page which handles requets for file downloads. I need to be able to detect when a file has been downloaded successfully. How can this be done? Perhaps there's some means of detecting this client-side then sending a confirmation down to the server.</p> <p>Thanks.</p> <p>Edit: By handle, I mean that the page is doing something like this:</p> <pre><code>$file = '/var/www/html/file-to-download.xyz'; header('Content-Type: application/octet-stream'); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename=' . basename($file)); readfile($file); </code></pre>
<p>Handle the download in a seperate php script (better do a little more than just <code>readfile($file);</code>, you can also provide the ability to resume downloads like in this <a href="https://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file">question</a>). Then in this script, when you <em>read</em> the last block and send it, you know that all the file was sent. This is not the same as knowing that all was received, but it should be enough for most scenarios.</p>
<p>What Treb said, but I should add that you can check if the client is still listening during download with <a href="http://nl3.php.net/connection_status" rel="nofollow noreferrer">connection_status()</a>.</p> <p>Don't forget to <code>flush()</code> after you've written data to the client, it helps in detecting if the connection is still up.</p>
23,646
<p>I am new to Ajax.Net.</p> <p>I want to know how to access data send from Ajax POST method. (ie)AjaxObject.send("Some Data")</p> <p>How to access that "Some Data" in form?</p> <p>I can access same when i used GET method and passed data in Querystring. like Request.Querystring("name") in ASP.</p>
<p>You need to define a Webservice (asmx) on the server. You can find good documentation on <a href="http://www.asp.net" rel="nofollow noreferrer">http://www.asp.net</a></p> <p>Specifically around webservices: <a href="http://www.asp.net/AJAX/Documentation/Live/tutorials/ASPNETAJAXWebServicesTutorials.aspx" rel="nofollow noreferrer">http://www.asp.net/AJAX/Documentation/Live/tutorials/ASPNETAJAXWebServicesTutorials.aspx</a> </p>
<p>On the server-side, you access POSTed ajax data the same way you access any POSTed form data:</p> <pre><code>Request.Form("name") </code></pre>
42,187
<p>I'm trying to set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up. </p> <p>By debugging I can see that the stream contains the image data. So what's wrong?</p> <pre><code>Assembly asm = Assembly.GetExecutingAssembly(); Stream iconStream = asm.GetManifestResourceStream("SomeImage.png"); PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); ImageSource iconSource = iconDecoder.Frames[0]; _icon.Source = iconSource; </code></pre> <p>The icon is defined something like this: <code>&lt;Image x:Name="_icon" Width="16" Height="16" /&gt;</code></p>
<p>After having the same problem as you and doing some reading, I discovered the solution - <a href="http://msdn.microsoft.com/en-us/library/aa970069.aspx" rel="noreferrer">Pack URIs</a>.</p> <p>I did the following in code:</p> <pre><code>Image finalImage = new Image(); finalImage.Width = 80; ... BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"); logo.EndInit(); ... finalImage.Source = logo; </code></pre> <p>Or shorter, by using another BitmapImage constructor:</p> <pre><code>finalImage.Source = new BitmapImage( new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png")); </code></pre> <p>The URI is broken out into parts:</p> <ul> <li>Authority: <code>application:///</code></li> <li><p>Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: <code>AssemblyShortName[;Version][;PublicKey];component/Path</code></p> <ul> <li>AssemblyShortName: the short name for the referenced assembly.</li> <li>;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.</li> <li>;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.</li> <li>;component: specifies that the assembly being referred to is referenced from the local assembly.</li> <li>/Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.</li> </ul></li> </ul> <p>The three slashes after <code>application:</code> have to be replaced with commas:</p> <blockquote> <p>Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details.</p> </blockquote> <p>And of course, make sure you set the build action on your image to <code>Resource</code>.</p>
<p>Force chose UriKind will be correct:</p> <pre><code>Image.Source = new BitmapImage(new Uri(&quot;Resources/processed.png&quot;, UriKind.Relative)); </code></pre> <p>UriKind options:</p> <pre><code>UriKind.Relative // relative path UriKind.Absolute // exactly path </code></pre>
45,554
<p>I want to add a comma in the thousands place for a number.</p> <p>Would <code>String.Format()</code> be the correct path to take? What format would I use?</p>
<pre><code>String.Format("{0:n}", 1234); // Output: 1,234.00 String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876 </code></pre>
<p>The method I used to not worry anymore about cultures and potential formatting issues is that I formatted it as currency and took out the currency symbol afterwards.</p> <p><code>if (decimal.TryParse(tblCell, out result))</code></p> <pre><code>{ formattedValue = result.ToString("C").Substring(1); } </code></pre>
13,129
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p> <p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p> <p>i.e.</p> <pre><code> >>> class Foo(object): def __eq__(self, other): return True >>> f = Foo() >>> f == None True >>> f is None False </code></pre>
<pre><code>a is b # returns true if they a and b are true alias a == b # returns true if they are true alias or they have values that are deemed equivalence a = [1,3,4] b = a[:] #creating copy of list a is b # if gives false False a == b # gives true True </code></pre>
4,616
<p>I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it?</p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/5817" rel="nofollow noreferrer">As a Firefox plugin</a> (aimed mainly at gears, but should work)</p> <p><a href="http://www.sqlitemanager.org" rel="nofollow noreferrer">As a (sucky) web based app</a></p> <p>And <a href="http://www.sqlite.org/cvstrac/wiki?p=ManagementTools" rel="nofollow noreferrer">a big list of management tools</a></p>
<p>I also discovered some SQLite software for Visual Studio at <a href="http://sqlite.phxsoftware.com/" rel="nofollow noreferrer">http://sqlite.phxsoftware.com/</a> which allows you to use the Visual Studio Server Explorer to create connections to SQLite databases.</p>
7,984
<p>When you open a page in the browser, an instance of the page is created on the server. But, when you use AJAX, does anyone know if the entire page object is created at the server on postbacks?</p>
<p>When you are using ASP.NET Ajax, a AJAX request will still process all code-behind code, however, the only rendering updates will be those to items inside your update panel.</p>
<p>It also depends on whether by using the term AJAX, you are referring to real AJAX or the AJAX .NET toolkit, which mostly is a set of javascript functions, in which 90% or so of them aren't really ajax. In most of those later controls, the entire page is called, and the output is only parsed for the particular information or sections needed. In the case that there is a asynchronous javascript calling the page and parsing it, the asp.net page won't be able to tell the difference between this call and a regular browser view (unless you program it to know the difference), so in this case, the Page Object will be created as well. The only time it will not process the entire page, is when a web method or script method is called. </p>
26,881
<p>I'm starting a project which requires reading outlook msg files in c#. I have the specs for compound documents but am having trouble reading them in c#. Any pointers would be greatly appreciated.</p> <p>Thanks.</p>
<p>Here is my shot. This is an initial translation of this <a href="http://www.codeguru.com/cpp/cpp/cpp_mfc/files/article.php/c13487__1/" rel="noreferrer">article</a>.</p> <pre><code>namespace cs_console_app { using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; [ComImport] [Guid("0000000d-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumSTATSTG { // The user needs to allocate an STATSTG array whose size is celt. [PreserveSig] uint Next( uint celt, [MarshalAs(UnmanagedType.LPArray), Out] System.Runtime.InteropServices.ComTypes.STATSTG[] rgelt, out uint pceltFetched ); void Skip(uint celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSTATSTG Clone(); } [ComImport] [Guid("0000000b-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IStorage { void CreateStream( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void OpenStream( /* [string][in] */ string pwcsName, /* [unique][in] */ IntPtr reserved1, /* [in] */ uint grfMode, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void CreateStorage( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStorage ppstg); void OpenStorage( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ IStorage pstgPriority, /* [in] */ uint grfMode, /* [unique][in] */ IntPtr snbExclude, /* [in] */ uint reserved, /* [out] */ out IStorage ppstg); void CopyTo( /* [in] */ uint ciidExclude, /* [size_is][unique][in] */ Guid rgiidExclude, // should this be an array? /* [unique][in] */ IntPtr snbExclude, /* [unique][in] */ IStorage pstgDest); void MoveElementTo( /* [string][in] */ string pwcsName, /* [unique][in] */ IStorage pstgDest, /* [string][in] */ string pwcsNewName, /* [in] */ uint grfFlags); void Commit( /* [in] */ uint grfCommitFlags); void Revert(); void EnumElements( /* [in] */ uint reserved1, /* [size_is][unique][in] */ IntPtr reserved2, /* [in] */ uint reserved3, /* [out] */ out IEnumSTATSTG ppenum); void DestroyElement( /* [string][in] */ string pwcsName); void RenameElement( /* [string][in] */ string pwcsOldName, /* [string][in] */ string pwcsNewName); void SetElementTimes( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pctime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME patime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pmtime); void SetClass( /* [in] */ Guid clsid); void SetStateBits( /* [in] */ uint grfStateBits, /* [in] */ uint grfMask); void Stat( /* [out] */ out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, /* [in] */ uint grfStatFlag); } [Flags] public enum STGM : int { DIRECT = 0x00000000, TRANSACTED = 0x00010000, SIMPLE = 0x08000000, READ = 0x00000000, WRITE = 0x00000001, READWRITE = 0x00000002, SHARE_DENY_NONE = 0x00000040, SHARE_DENY_READ = 0x00000030, SHARE_DENY_WRITE = 0x00000020, SHARE_EXCLUSIVE = 0x00000010, PRIORITY = 0x00040000, DELETEONRELEASE = 0x04000000, NOSCRATCH = 0x00100000, CREATE = 0x00001000, CONVERT = 0x00020000, FAILIFTHERE = 0x00000000, NOSNAPSHOT = 0x00200000, DIRECT_SWMR = 0x00400000, } public enum STATFLAG : uint { STATFLAG_DEFAULT = 0, STATFLAG_NONAME = 1, STATFLAG_NOOPEN = 2 } public enum STGTY : int { STGTY_STORAGE = 1, STGTY_STREAM = 2, STGTY_LOCKBYTES = 3, STGTY_PROPERTY = 4 } class Program { [DllImport("ole32.dll")] private static extern int StgIsStorageFile( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName); [DllImport("ole32.dll")] static extern int StgOpenStorage( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName, IStorage pstgPriority, STGM grfMode, IntPtr snbExclude, uint reserved, out IStorage ppstgOpen); static void Main(string[] args) { string filename = @"f:\temp\treta2.msg"; if (StgIsStorageFile(filename) == 0) { IStorage storage = null; if (StgOpenStorage( filename, null, STGM.DIRECT | STGM.READ | STGM.SHARE_EXCLUSIVE, IntPtr.Zero, 0, out storage) == 0) { System.Runtime.InteropServices.ComTypes.STATSTG statstg; storage.Stat(out statstg, (uint) STATFLAG.STATFLAG_DEFAULT); IEnumSTATSTG pIEnumStatStg = null; storage.EnumElements(0, IntPtr.Zero, 0, out pIEnumStatStg); System.Runtime.InteropServices.ComTypes.STATSTG[] regelt = { statstg }; uint fetched = 0; uint res = pIEnumStatStg.Next(1, regelt, out fetched); if (res == 0) { while (res != 1) { string strNode = statstg.pwcsName; bool bNodeFound = false; Console.WriteLine(strNode); if (strNode == "__substg1.0_0E04001E" || strNode == "__substg1.0_0E1D001E" || strNode == "__substg1.0_1000001E" || strNode == "__substg1.0_1013001E") { bNodeFound = true; } if (bNodeFound) { switch (statstg.type) { case (int) STGTY.STGTY_STORAGE: { IStorage pIChildStorage; storage.OpenStorage(statstg.pwcsName, null, (uint) (STGM.READ | STGM.SHARE_EXCLUSIVE), IntPtr.Zero, 0, out pIChildStorage); } break; case (int) STGTY.STGTY_STREAM: { IStream pIStream; storage.OpenStream(statstg.pwcsName, IntPtr.Zero, (uint)(STGM.READ | STGM.SHARE_EXCLUSIVE), 0, out pIStream); byte[] data = new byte[255]; pIStream.Read(data, 255, IntPtr.Zero); } break; } } if ((res = pIEnumStatStg.Next(1, regelt, out fetched)) != 1) { statstg = regelt[0]; } } } } } Console.ReadLine(); } } } </code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.aspx" rel="nofollow noreferrer">Outlook Interop</a>. While I have never used the outlook interop, you <strong>SHOULD</strong> be able to open the email messages with it.</p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.aspx" rel="nofollow noreferrer">MailItem Interface</a> should be the interface that you need to access it.</p> <p>Also, make sure that you release the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject(VS.80).aspx" rel="nofollow noreferrer">com references</a> after you are done with them</p>
21,603
<p>In an impersonation scenario related to Sharepoint I need to execute some code in a separate process (the process will run in the context of a certain user). I do not want to launch a separate application, basically I want to do a "run as" on just a method.</p>
<p>I haven't tried this myself but <a href="http://michiel.vanotegem.nl/Permalink,guid,36633846-2eca-40fe-9957-2859d8a244dc.aspx" rel="nofollow noreferrer">this seems</a> to do the trick.</p> <p>If you are fine with the impersonated method blocking until it finishes it should work. So your code would be something like:</p> <pre><code>... WrapperImpersonationContext context = new WrapperImpersonationContext(domain, username, password); context.Enter(); Results res = MyImpersonatedMethod(data); context.Leave(); ... </code></pre> <p>Hope this helps.</p>
<p>"Execute code in a separate process" = "launch a separate application" though.</p> <p>I mean, you could launch a single process and then make requests to it to run the particular method... but it's not clear whether that's what you want.</p>
39,296
<p>What is the most efficient algorithm for grouping identical items together in an array, given the following:</p> <ol> <li>Almost all items are duplicated several times.</li> <li>The items are not necessarily integers or anything else that's similarly simple. The range of the keys is not even well-defined, let alone small. In fact, the keys can be arbitrary structs. This rules out the most simple forms of counting sort.</li> <li>We care about both asymptotic and non-asymptotic properties, and n may be small sometimes. However, when n is small, performance is still important because this function may be called several million times in a loop on millions of small datasets. This rules out any expensive hash function or using a complex data structure that needs to perform lots of memory allocations.</li> <li>The data may be sorted in arbitrary order as long as all identical items are grouped together.</li> </ol> <p>If this is confusing, here's an example, assuming such a function is named groupIdentical:</p> <pre><code>uint[] foo = [1,2,3,2,1,5,4,5]; uint[] bar = groupIdentical(foo); // One possibile correct value for bar: // bar == [2,2,1,1,3,4,5,5]. // Another possible correct answer: // bar == [1,1,2,2,5,5,4,3]. </code></pre> <p>However, as a reminder, we cannot assume that the data is composed as integers.</p> <p>Edit: Thank you for the answers. My main problem with hashing was that hash tables perform memory allocations to frequently. What I ended up doing was writing my own hash table that uses a region allocator that I had around to get around this problem. Works well.</p>
<p>I think you could just hash the objects, since real order doesn't matter, only grouping. Identical objects will end up grouped in the same bucket. This is assuming that every type you're interested in has its own hash function, or you can define your own and overload it (taking each type as a parameter to a different hashCode function definition).</p> <p>To avoid collisions across data types (so strings don't end up in the same bucket as doubles, for one example), you'd need to encode the data type into the hash. So, for example, if you have a 32-bit hash, maybe the first 5 bits could encode the data type, so you can have 32 different types in the same hash map.</p> <p>EDIT: Let me just add that the reason that I'm suggesting a custom hash map is because I don't know of one that exposes enough of its internal implementation for you to get the values out of each bucket. There might be such an implementation that I don't know of. There are a lot of things I don't know. :)</p>
<p>If you know the range of the possible values, and it's small, you could do: (pseudo-ish code)</p> <pre><code>uint[] bucket = new int[10]; foreach(uint val in foo) { ++bucket[val]; } uint bar_i = 0; uint[] bar = new int[foo.length]; foreach(int val = 0; val &lt; 10; val++) { uint occurrences = bucket[val]; for(int i=0; i &lt; occurrences; i++) { bar[bar_i++] = val; } } </code></pre>
46,143
<p>I have a main asp.net app, which is written in asp.net 1.1. Runnning underneath the application are several 2.0 apps. To completely logout a user can I just logout of the 1.1 app with FormsAuthentication.SignOut or is it more complicated than that?</p>
<p>What you are looking to do is called Single Sign On and Single Sign Off. There are differences based on how you have the applications set up. I will try to clarify where those differences come into play.</p> <p>To implement single sign on and single sign off you need to make the cookie name, protection, and path attributes the same between all the applications.</p> <pre><code>&lt;authentication mode="Forms"&gt; &lt;forms name=".cookiename" loginUrl="~/Login.aspx" timeout="30" path="/" /&gt; &lt;/authentication&gt; </code></pre> <p>Next you need to add the machine keys and they need to be the same between all your applications.</p> <pre><code>&lt;machineKey validationKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902" encryptionKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC" validation="SHA1" /&gt; </code></pre> <p>Are you using second or third level domains for the applications? If so you will need to do a little bit more by adding the domain to the cookie:</p> <pre><code>protected void Login(string userName, string password) { System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False); cookie.Domain = "domain1.com"; cookie.Expires = DateTime.Now.AddDays(30); Response.AppendCookie(cookie); } </code></pre> <p>Now to do single sign off, calling FormsAuthentication.SignOut may not be enough. The next best thing is to set the cookie expiration to a past date. This will ensure that the cookie will not be used again for authentication.</p> <pre><code>protected void Logout(string userName) { System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False); cookie.Domain = "domain1.com"; cookie.Expires = DateTime.Now.AddDays(-1); Response.AppendCookie(cookie); } </code></pre> <p>I am taking into consideration you are using the same database for all the applications. If the applications use a separate database for registration and authentication, then we will need to do some more. Just let me know if this is the case. Otherwise this should work for you.</p>
<p>It could be easier if you are having a central session store for all your applications. You can then set the session to null in one place.</p>
7,929
<p>I have a <a href="https://www.monoprice.uk/products/monoprice-maker-ultimate-3d-printer-uk" rel="nofollow noreferrer">Monoprice Maker Ultimate 3D Printer</a> and have tried to replace the nozzle.</p> <p>The nozzles I bought turned out to be too small.</p> <p><img src="https://i.imgur.com/iYnMTVf.jpg" alt="Imgur"></p> <p>What are the important specifications of a nozzle?</p> <ul> <li>Thread size</li> <li>Thread length</li> <li>That plastic tube thing?</li> </ul> <p>Monoprice is very bad at publishing the specs, can I work it out with a caliper?</p>
<h2>What part fits?</h2> <p>A replacement nozzle needs to fit 3 parameters:</p> <ul> <li>Thread diameter and pitch need to match up, to allow mounting</li> <li>Thread length should be close to the original to allow secure fastening</li> <li>The style needs to fit: there are quite some styles of nozzle - most are not lined, yours is PTFE lined to the nozzle (see also <a href="https://3dprinting.stackexchange.com/questions/7497/can-the-filament-tube-be-outside-of-the-nozzle/7498#7498">Can the filament tube be outside of the nozzle?</a>)</li> </ul> <p>Monoprice nozzles are <strong>not</strong> compatible with what is known as Ultimaker Mk8 or E3D style (which you bought). They are Ultimaker Mk10 style.</p> <h2>What's a good nozzle?</h2> <p>Now, what separates a good replacement nozzle from a bad one?</p> <ul> <li>good machining to leave no burs and a smooth interior.</li> <li>a good inner geometry that allows easy flow</li> <li>outlet hole is to size</li> </ul> <h2>Finding premade replacement parts</h2> <p>As a first measure to not get the wrong replacement parts, make sure to add the manufacturer of your printer to the search and then check the thread diameter if given. In your case, you might have to add Monoprice or Toymaker, as those use this style of nozzle.</p> <h2>Reverse engineering a Nozzle</h2> <p>Now, which measurements do you need to reverse engineer it?</p> <ul> <li>nozzle front pitch angle</li> <li>hex head flat-to-flat &amp; hight</li> <li>recess diameter &amp; hight</li> <li>screw shaft relief diameter &amp; hight</li> <li>thread outer diameter &amp; length</li> <li>inner bore diameter at entry (and in case of a lined one: after the step) &amp; corresponding depth of drilling</li> <li>amount of chamfering</li> </ul> <p>With these, it's possible to do do a CNC model or a sketch of the outside and produce pretty much blanks or shells on a lathe that just need their last little bit of drilling... and here comes the tricky part: till now, all could be accessed from the outside. We are missing one profile though: the last piece of the inner bore geometry.</p> <p>This one can't easily be measured, but if one can push some plastic in, let it cool and then pull it out, one might get a molding of it, which might allow to reverse engineer a fitting drill for the last piece.</p>
<h2>What part fits?</h2> <p>A replacement nozzle needs to fit 3 parameters:</p> <ul> <li>Thread diameter and pitch need to match up, to allow mounting</li> <li>Thread length should be close to the original to allow secure fastening</li> <li>The style needs to fit: there are quite some styles of nozzle - most are not lined, yours is PTFE lined to the nozzle (see also <a href="https://3dprinting.stackexchange.com/questions/7497/can-the-filament-tube-be-outside-of-the-nozzle/7498#7498">Can the filament tube be outside of the nozzle?</a>)</li> </ul> <p>Monoprice nozzles are <strong>not</strong> compatible with what is known as Ultimaker Mk8 or E3D style (which you bought). They are Ultimaker Mk10 style.</p> <h2>What's a good nozzle?</h2> <p>Now, what separates a good replacement nozzle from a bad one?</p> <ul> <li>good machining to leave no burs and a smooth interior.</li> <li>a good inner geometry that allows easy flow</li> <li>outlet hole is to size</li> </ul> <h2>Finding premade replacement parts</h2> <p>As a first measure to not get the wrong replacement parts, make sure to add the manufacturer of your printer to the search and then check the thread diameter if given. In your case, you might have to add Monoprice or Toymaker, as those use this style of nozzle.</p> <h2>Reverse engineering a Nozzle</h2> <p>Now, which measurements do you need to reverse engineer it?</p> <ul> <li>nozzle front pitch angle</li> <li>hex head flat-to-flat &amp; hight</li> <li>recess diameter &amp; hight</li> <li>screw shaft relief diameter &amp; hight</li> <li>thread outer diameter &amp; length</li> <li>inner bore diameter at entry (and in case of a lined one: after the step) &amp; corresponding depth of drilling</li> <li>amount of chamfering</li> </ul> <p>With these, it's possible to do do a CNC model or a sketch of the outside and produce pretty much blanks or shells on a lathe that just need their last little bit of drilling... and here comes the tricky part: till now, all could be accessed from the outside. We are missing one profile though: the last piece of the inner bore geometry.</p> <p>This one can't easily be measured, but if one can push some plastic in, let it cool and then pull it out, one might get a molding of it, which might allow to reverse engineer a fitting drill for the last piece.</p>
1,196
<p>Does anyone know of a good open source plugin for database querying and exploring within Eclipse? </p> <p>The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.</p> <p>Any suggestions?</p>
<p>It's this way in SQL (as a logic language) because null means unknown/undefined.</p> <p>However, in programming languages (like say, C++ or C#), a null pointer/reference is a specific value with a specific meaning -- nothing.</p> <p>Two nothings are equivilent, but two unknowns are not. The confusion comes from the fact that the same name (null) is used for both concepts.</p>
<p>In SQL you would have to do something like:</p> <pre><code>WHERE column is NULL </code></pre> <p>rather than</p> <pre><code>WHERE column = NULL </code></pre>
10,092
<p>I've been using <a href="http://www.jcraft.com/jsch/" rel="nofollow noreferrer">JSch</a> for a couple of weeks now. It seems to <em>work</em> okay, but its API is a little bit cumbersome. I'm also a little off put by its total lack of documentation (not even javadoc style comments). Has anyone used a good Java SSH2 library that they'd recommend. I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol.</p>
<p>Here's one way, using the <a href="http://www.php.net/list" rel="nofollow noreferrer">list</a> language construct</p> <pre><code>function returnsAnArray () { return array ('test'); } list($foo)=returnsAnArray(); </code></pre> <p>You could grab a sequence of elements from an offset by combining this with <a href="http://www.php.net/array_slice" rel="nofollow noreferrer">array_slice</a></p> <pre><code>list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3); </code></pre>
<p>I ask myself why one would like to avoid creating a temporary variable for a returned array. Why don't you just return one value instead of an whole array? Maybe you'll have to overthink your program logic.</p> <p>Or is it a performance/memory issue? Consider using <a href="http://de2.php.net/manual/en/language.references.php" rel="nofollow noreferrer">references</a> instead of always creating a new array object and returning it.</p>
20,794
<p>For years, maybe 10, I've been fascinated with cryptography. I read a book about XOR bit-based encryption, and have been hooked ever since thing.</p> <p>I guess it's more fair to say that I'm fascinated by those who can break various encryption methods, but I digress.</p> <p>To the point -- what methods do you use when writing cryptography? Is obfuscation good in cryptography? </p> <p>I use two key-based XOR encryption, various hashing techniques (SHA1) on the keys, and simple things such as reversing strings here and there, etc.</p> <p>I'm interested to see what others think of and try when writing a not-so-out-of-the-box encryption method. Also -- any info on how the pros go about "breaking" various cryptography techniques would be interesting as well.</p> <p><strong>To clarify -- I have no desire to use this in any production code, or any code of mine for that matter. I'm interesting in learning how it works through toying around, not reinventing the wheel. :)</strong></p> <p>Ian</p>
<p>To contradict what everyone else has said so far, <strong>go for it!</strong> Yeah, your code might have buffer overflow vulnerabilities in it, and may be slow, buggy, etc, but you're doing this for <strong>FUN</strong>! I completely understand the recreational enjoyment found in playing with crypto.</p> <p>That being said, cryptography isn't based on obfuscation at all (or at least shouldn't be). Good crypto will continue to work, even once <a href="http://en.wikipedia.org/wiki/Alice_and_Bob#List_of_characters" rel="nofollow noreferrer">Eve</a> has slogged through your obfuscated code and completely understands what is going on. IE: Many newspapers have <a href="http://en.wikipedia.org/wiki/Caesar_cipher" rel="nofollow noreferrer">substitution code</a> puzzles that readers try and break over breakfast. If they started doing things like reversing the whole string, yes, it'd be harder, but Joe Reader would still be able to break it, neve tuohtiw gnieb dlot.</p> <p>Good crypto is based on problems that are assumed to be (none proven yet, AFAIK) really difficult. Examples of this include <a href="http://en.wikipedia.org/wiki/RSA#Security" rel="nofollow noreferrer">factoring primes</a>, <a href="http://en.wikipedia.org/wiki/Diffie-Hellman" rel="nofollow noreferrer">finding the log</a>, or really any other <a href="http://en.wikipedia.org/wiki/NP-complete" rel="nofollow noreferrer">NP-complete</a> problem.</p> <p>[Edit: snap, neither of those are <strong>proven</strong> NP-complete. They're all unproven, yet different. Hopefully you still see my point: crypto is based on one-way functions. Those are operations that are easy to do, but hard to undo. ie multiply two numbers vs find the prime factors of the product. Good catch <a href="https://stackoverflow.com/users/20486/tduehr">tduehr</a>]</p> <p>More power to you for playing around with a really cool branch of mathematics, just remember that crypto is based on things that are hard, not complicated. Many crypto algorithms, once you really understand them, are mindbogglingly simple, but still work because they're based on something that is hard, not just switching letters around.</p> <p>Note: With this being said, some algorithms do add in extra quirks (like string seversal) to make brute forcing them that much more difficult. A part of me feels like I read this somewhere referencing <a href="http://en.wikipedia.org/wiki/Data_Encryption_Standard" rel="nofollow noreferrer">DES</a>, but I don't believe it... [EDIT: I was right, see <a href="http://scienceblogs.com/goodmath/2008/09/des_encryption_part_1_encrypti.php" rel="nofollow noreferrer">5th paragraph of this article</a> for a reference to the permutations as useless.]</p> <p>BTW: If you haven't found it before, I'd guess the <a href="http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm" rel="nofollow noreferrer">TEA</a>/<a href="http://en.wikipedia.org/wiki/XTEA" rel="nofollow noreferrer">XTEA</a>/<a href="http://en.wikipedia.org/wiki/XXTEA" rel="nofollow noreferrer">XXTEA</a> series of algorithms would be of interest.</p>
<p>Usually, I start by getting a Ph.D in number theory. Then I do a decade or so of research and follow that up with lots of publishing and peer review. As far as the techniques I use, they are various ones from my research and that of my peers. Occasionally, when I wake up in the middle of the night, I'll develop a new technique, implement it, find holes in it (with the help of my number theory and computer science peers) and then refine from there.</p> <p>If you give a mouse an algorithm...</p>
14,411
<p>Admittedly this might not be a problem on larger screens, but my employer is abit tight and refuses to buy monitors larger than 19inch, this means that I dont have much screen real estate to view all the Visual Studio windows and my code at the same time, or two pieces of code at once. Is there anything that allows me to detach the code panels so that I can view two different classes at once on each of my screens? </p>
<p>You can right click on the tab strip and insert a new vertical (or horizontal) tab group.</p> <p>This allows you to view multiple tabs at the same time.</p>
<p>Hmm.. I don't think there is a way from within Visual Studio. For maximizing real estate and working on simultaneous files, I use that method plus viewing the files on Full Screen mode.</p> <p>Do you multiple monitors?</p>
3,764
<p>In <a href="https://stackoverflow.com/users/23233/mmalc">@mmalc's</a> <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#156288">response</a> to <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa">this question</a> he states that "In general you should <em>not</em> use accessor methods in dealloc (or init)." Why does mmalc say this?</p> <p>The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.</p> <p>Discussion?</p>
<p>It's basically a guideline to minimize the potential for bugs.</p> <p>In this case there is the (possibility) that your setter/getter may inadvertently make direct or indirect assumptions about the state of the object. These assumptions could be a problem when the object is in the midst of being setup or destroyed.</p> <p>For example in the code below the observer does not know that 'Example' is being destroyed and could assume that other properties, which have already been freed, are valid. </p> <p>(You could argue that your object should remove all observers before tearing itself down, which would be good practice, and another guideline to prevent inadvertent problems).</p> <pre><code>@implementation Example -(void) setFoo:(Foo*)foo { _foo = foo; [_observer onPropertyChange:self object:foo]; } -(void) dealloc { ... self.foo = nil; } @end </code></pre>
<p>In fact, for a class that comes and goes rather often (like a detail view controller), you want to use the accessor in the init; otherwise, you could end up releasing a value in viewDidUnload that you try to access later (they show that in CS193P...)</p>
23,420
<p>I have a PPPOE connection on a computer. That computer has two LAN cards and I activated ICS on it. The problem is, the connection kinda degrades over time (don't know why), and a redial would be nice, hourly maybe. I was thinking of writing an AutoIT script that would do this, if, for example I'm sending some data to a port the gateway pc is listening on. The only trouble is, I don't know what's the name of the executable I would have to run.</p> <p>EDIT: I'm interested in the one with the GUI.</p> <p>EDIT 2: I am interested in automating this process, and wouldn't like to have to write the thing in AutoIT (this a last resort option).</p>
<p>you can use rasdial (which is build in into windows) and create a batch script (.bat extension) like so:</p> <pre><code>rasdial connectionname </code></pre> <p>-or- </p> <p>if you want to do it in a programming language, you can just call the command internally</p> <p>C# example:</p> <pre><code>public static int OpenConnection(string connectionName, int Timeout) { int ExitCode; ProcessStartInfo ProcessInfo; Process Process; ProcessInfo = new ProcessStartInfo("cmd.exe", "/C rasdial " + connectionName); ProcessInfo.CreateNoWindow = true; ProcessInfo.UseShellExecute = false; Process = Process.Start(ProcessInfo); Process.WaitForExit(Timeout); ExitCode = Process.ExitCode; Process.Close(); return ExitCode; } </code></pre> <p>and I guess your desired language will have something like this available as well.</p> <p>oh and you can use:</p> <pre><code>rasdial "connection name" /d </code></pre> <p>to drop the connection.</p>
<p>Maybe you can make something for yourself with <a href="http://webtools.live2support.com/windows/rasdial.php" rel="nofollow noreferrer">rasdial</a> and <a href="http://support.microsoft.com/kb/313565" rel="nofollow noreferrer">at</a>?</p>
39,464
<p>I'm working on a project and I want to store some easily enumerated information in a table. MySql's enum data type does exactly what I want: <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/enum.html</a> . Is there an equivalent in SQL Server 2005?</p> <p>I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions. Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.</p>
<p>Does this work for you?</p> <p>From <a href="http://blechie.com/wtilton/archive/2007/08/24/303.aspx" rel="noreferrer">http://blechie.com/wtilton/archive/2007/08/24/303.aspx</a></p> <p>Create table...</p> <p><strong>MySQL:</strong></p> <pre><code>ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add') DEFAULT 'open' </code></pre> <p><strong>SQL Server:</strong></p> <pre><code>ColumnName varchar(10) CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add')) DEFAULT 'open' </code></pre>
<p>One characteristic of MySQL's ENUM data type is that it stores only a numeric index into the list of values, not the string itself, on each row. So it's usually more storage-efficient. Also the default behavior when you sort by an ENUM column is to sort by the numeric index, therefore by the order of elements in the ENUM.</p> <p>Nikki9696 suggests using a VARCHAR column with a CHECK constraint. This satisfies the restriction of values to a certain short list of permitted values, but it doesn't simulate the storage efficiency or the special sort order.</p> <p>One way to get both behaviors is to declare the column as an integer foreign key into a lookup table, in which you store each permitted string.</p>
32,896
<p>I am wondering what the correct mechanism to enable communication between controls in WPF is. My goal is to not use conventional events and have to manually wire them up. The default behavior of routed commands (tunneling, bubbling) seems to be along the right lines but I guess I'm missing something.</p> <blockquote> <p>Routed events are a new infrastructure provided by WPF which allows events to tunnel down the visual tree to the target element, or bubble up to the root element. When an event is raised, it “travels” up or down the visual tree invoking handlers for that event on any element subscribed to that event it encounters en route. <strong>Note that this tree traversal does not cover the entire visual tree, only the ancestral element</strong> </p> </blockquote> <p>That is from this <a href="http://joshsmithonwpf.wordpress.com/2007/06/22/overview-of-routed-events-in-wpf/" rel="nofollow noreferrer">WPF Article</a></p> <p>Using the image in the article, I want "Immediate Element #1" to initiate (raise) an event and then have "Immediate Element #2" handle that event. I'd like to achieve this without having to put any code in the "Root Element".</p> <p>Basically fire an event (save, status updated, selection changed, etc..) from any where in my app, then have it be handled somewhere else with out the 2 parties knowing anything about each other. Is this possible?</p> <p>I dont believe data bainding is the answer. I'd like to use Routed Events / Commands as they were designed just across the entire tree, not just within the source control's branch. Maybe it can't be done using routed events / commands, and data binding is the answer. I just dont know...</p> <p>Any ideas?</p>
<p>The best mechanism is to refactor and separate the data view from the data model.</p> <p>Create a data model that provides DependencyProperty properties (rather than standard C# properties) for each data point, but does not provide a UI. The values in the data model can affect each other when modified.</p> <p>You can then bind each WPF element to the appropriate DependencyProperty from the data model. Modify the value in one element and all other elements are updated to reflect any data model changes in the bound properties.</p>
<p>If you want to transfer data between elements, <code>Binding</code> is the way to go. There are many tutorials and books about this on the net.</p> <p>If you want to effect <code>Style</code> changes, then you can use <code>DataTriggers</code>, which also use Bindings.</p> <p>There is no way to send events in the traditional sense between unrelated controls without wiring it up in the common root.</p>
22,286
<p>I am writing a .NET assembly using C++/CLI (version 9.0), and I would like to use the PIMPL idiom to avoid putting unnecessary stuff in my public header. Unfortunately, when I try to forward declare a class, and then use a tracking handle to it, I get Linker warning 4248: </p> <blockquote> <p>warning LNK4248: unresolved typeref token (0100000E) for 'MyNamespace.PrivateClass'; image may not run</p> </blockquote> <p>This seems to be the case whether I use a CLI class or a native class for the implementation class.</p> <p>Example code appears below:</p> <pre><code>namespace MyNamespace { ref class PrivateClass; // forward dec ref class MyPublicClass { private: PrivateClass^ m_Imp; }; } </code></pre> <p>The Microsoft explanation for the warning is not too informative, unfortunately.</p>
<p>I think you're using two technologies which do not really sit together well:</p> <p>The natural application for pimpl is to avoid having to make header file changes all the time thereby causing big recompilations on big C++ projects.</p> <p>The natural application for C++/cli is to write skinny little interop pieces, and the default behaviour of VS on these projects is to put all the code into the headers, which is about as anti-pimpl as you can get.</p> <p>If you're writing something large enough to warrant pimpl, I wouldn't recommend C++/cli. If you're writing something small enough to make C++/cli appropriate, I wouldn't bother with pimpl.</p> <p>YMMV of course, but that would be my take on it...</p>
<p>Upon further digging and reflecting I have discovered that in some respects .NET does not really need to support PIMPL in the same way as C++, since you can mark a class private to an assembly - this essentially has the same effect, in some ways. However often the PIMPL idiom is used to hide headers that you don't want the client to have to compile. But of course .NET assemblies are not "included" like the headers for C++ are - so I guess there really isn't an issue there either.</p>
43,480
<p>I have a pictures table that has the following columns:</p> <pre><code>PICTURE_ID int IDENTITY(1000,1) NOT NULL, CATEGORY_ID int NOT NULL, IMGDATA image NOT NULL, CAPTION1 text COLLATE SQL_Latin1_General_CP1_CI_AS NULL, MIME_TYPE nchar(20) NOT NULL DEFAULT ('image/jpeg'), IMGTHDATA image NOT NULL </code></pre> <p>In my code-behind I have this:</p> <pre><code>string tableName = "CATPICS"; SqlConnection dbConnection = new SqlConnection(connStr); SqlDataAdapter daCatPics = new SqlDataAdapter("SELECT TOP(3) * FROM CATEGORY_PICTURES", dbConnection); DataSet dsPics = new DataSet(); daCatPics.Fill(dsPics, tableName); gvCatPics.DataSource = dsPics; gvCatPics.DataMember = tableName; gvCatPics.DataBind(); </code></pre> <p>On the markup I pretty much have: </p> <pre><code>&lt;asp:GridView ID="gvCatPics" runat="server"&gt;&lt;/asp:GridView&gt; </code></pre> <p>However when the code executes, it simply ignores the two image columns (IMGDATA and IMGTHDATA). For some reason it doesn't recognize that they are image columns. Does anyone know of the simplest way of having it render the image?</p>
<p>you can make a page that returns the image as a stream and reference that page from an Image column (or an IMG tag in a template column); see <a href="http://www.netomatix.com/development/GridViewDisplayBlob.aspx" rel="nofollow noreferrer">GridViewDisplayBlob.aspx</a></p>
<p>There is no real simple way to do this. Basically you're going to need to create a handler to display the images. Then in your grid you will create an img tag with the URL pointing to your image handler. </p> <p>An example of this can be found <a href="http://blogs.msdn.com/jdixon/articles/495408.aspx" rel="nofollow noreferrer">here</a>. </p> <p><strong>Update:</strong> Much better example of this <a href="http://www.odetocode.com/Articles/172.aspx" rel="nofollow noreferrer">here</a>.</p>
24,364
<p>Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:</p> <pre><code>if (is_number($x)) { ... } </code></pre> <p>would be ideal. A technique that won't throw warnings when the <code>-w</code> switch is being used is certainly preferred.</p>
<p>Use <code>Scalar::Util::looks_like_number()</code> which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this. Note that the strings "inf" and "infinity" are treated as numbers.</p> <h2>Example:</h2> <pre><code>#!/usr/bin/perl use warnings; use strict; use Scalar::Util qw(looks_like_number); my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity); foreach my $expr (@exprs) { print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n"; } </code></pre> <p>Gives this output:</p> <pre><code>1 is a number 5.25 is a number 0.001 is a number 1.3e8 is a number foo is not a number bar is not a number 1dd is not a number inf is a number infinity is a number </code></pre> <h2>See also:</h2> <ul> <li><a href="http://perldoc.perl.org/Scalar/Util.html" rel="noreferrer">perldoc Scalar::Util</a></li> <li><a href="http://perldoc.perl.org/perlapi.html#SV-Body-Allocation" rel="noreferrer">perldoc perlapi</a> for <code>looks_like_number</code></li> </ul>
<p>if ( defined $x &amp;&amp; $x !~ m/\D/ ) {} or $x = 0 if ! $x; if ( $x !~ m/\D/) {}</p> <p>This is a slight variation on Veekay's answer but let me explain my reasoning for the change.</p> <p>Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.</p>
3,373
<p>For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online.</p> <p>Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums.</p> <p>To get this started, since these are the ones I am searching for right now, where are there good online resources for:</p> <ul> <li>C89</li> <li>C99</li> <li>C11</li> <li>C++98</li> <li>C++03</li> <li>C++11</li> <li>C++14</li> <li>C++17</li> </ul>
<h3>PDF versions of the standard</h3> <p>As of <strike>1st September 2014</strike> March 2022, the best locations by price for the official C and C++ standards documents in PDF seem to be:</p> <ul> <li><p>C++20 – ISO/IEC 14882:2020: <a href="https://www.csagroup.org/store/product/CSA%20ISO%25100IEC%2014882%3A21/?format=PDF" rel="noreferrer">212 CAD (about $165 US) from csagroup.org</a></p> </li> <li><p>C++17 – ISO/IEC 14882:2017: <a href="https://www.standards.govt.nz/shop/isoiec-148822017/" rel="noreferrer">$90 NZD (about $65 US) from Standards New Zealand</a></p> </li> <li><p>C++14 – ISO/IEC 14882:2014: <a href="https://www.standards.govt.nz/shop/isoiec-148822014/" rel="noreferrer">$90 NZD (about $65 US) from Standards New Zealand</a></p> </li> <li><p>C++11 – ISO/IEC 14882-2011: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC148822012" rel="noreferrer">$60 from ansi.org</a> or <a href="https://www.techstreet.com/standards/incits-iso-iec-14882-2011-2012?product_id=1852925" rel="noreferrer">$60 from Techstreet</a></p> </li> <li><p>C++03 – INCITS/ISO/IEC 14882:2003: <a href="https://webstore.ansi.org/standards/incits/incitsisoiec148822003" rel="noreferrer">$30 from ansi.org</a></p> </li> <li><p>C++98 – ISO/IEC 14882:1998: <a href="https://www.standards.govt.nz/shop/asnzs-148821999/" rel="noreferrer">$95 NZD (about $65 US) from Standards New Zealand</a></p> </li> <li><p>C17/C18 – INCITS/ISO/IEC 9899:2018: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920182019" rel="noreferrer">$116 from INCITS/ANSI</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">N2176 / c17_updated_proposed_fdis.pdf draft from November 2017</a> (Link broken, see <a href="https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">Wayback Machine N2176</a>)</p> </li> <li><p>C11 – ISO/IEC 9899:2011: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920112012" rel="noreferrer">$60 from ansi.org</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">WG14 draft version N1570</a></p> </li> <li><p>C99 – INCITS/ISO/IEC 9899-1999(R2005): <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC98991999R2005" rel="noreferrer">$60 from ansi.org</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">WG14 draft version N1256</a></p> </li> <li><p>C90 – ISO/IEC 9899:1990: <a href="https://www.standards.govt.nz/shop/isoiec-98991990/" rel="noreferrer">$90 NZD (about $65 USD) from Standards New Zealand</a></p> </li> </ul> <h3>Non-PDF electronic versions of the standard</h3> <p><em><strong>Warning: most copies of standard drafts are published in PDF format, and errors may have been introduced if the text/HTML was transcribed or automatically generated from the PDF.</strong></em></p> <ul> <li>C89 – Draft version in ANSI text format: (<a href="https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt" rel="noreferrer">https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt</a>)</li> <li>C89 – Draft version as HTML document: (<a href="http://port70.net/%7Ensz/c/c89/c89-draft.html" rel="noreferrer">http://port70.net/~nsz/c/c89/c89-draft.html</a>)</li> <li>C90 TC1; ISO/IEC 9899 TCOR1, single-page HTML document: (<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm</a>)</li> <li>C90 TC2; ISO/IEC 9899 TCOR2, single-page HTML document: (<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm</a>)</li> <li>C99 – Draft version (N1256) as HTML document: (<a href="http://port70.net/%7Ensz/c/c99/n1256.html" rel="noreferrer">http://port70.net/~nsz/c/c99/n1256.html</a>)</li> <li>C11 – Draft version (N1570) as HTML document: (<a href="http://port70.net/%7Ensz/c/c11/n1570.html" rel="noreferrer">http://port70.net/~nsz/c/c11/n1570.html</a>)</li> <li>C++11 – Working draft (N3337) as plain text document: (<a href="http://port70.net/%7Ensz/c/c%2B%2B/c%2B%2B11_n3337.txt" rel="noreferrer">http://port70.net/~nsz/c/c%2B%2B/c%2B%2B11_n3337.txt</a>)</li> </ul> <p><em>(The site hosting the plain text version of the C++11 working draft also has some C++14 drafts in this format. But none of them are copies of the final working draft, N4140.)</em></p> <h3>Print versions of the standard</h3> <p>Print copies of the standards are available from national standards bodies and <a href="https://www.iso.org/home.html" rel="noreferrer">ISO</a> but are very expensive.</p> <p>If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of <a href="http://www.catb.org/jargon/html/B/bullschildt.html" rel="noreferrer">Herb Schildt</a>'s book <a href="http://www.davros.org/c/schildt.html" rel="noreferrer"><em>The Annotated ANSI Standard</em></a> at <a href="https://rads.stackoverflow.com/amzn/click/com/0078819520" rel="noreferrer" rel="nofollow noreferrer">Amazon</a>, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).</p> <p>The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):</p> <ul> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0470846747" rel="noreferrer" rel="nofollow noreferrer">C++03 Standard</a> on Amazon</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0470845732" rel="noreferrer" rel="nofollow noreferrer">C99 Standard</a> on Amazon</li> </ul> <h3>Standards committee draft versions (free)</h3> <p>The working drafts for future standards are often available from the committee websites:</p> <ul> <li><a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="noreferrer">C++ committee website</a></li> <li><a href="http://www.open-std.org/jtc1/sc22/wg14/" rel="noreferrer">C committee website</a></li> </ul> <p>If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:</p> <h3>For C:</h3> <ul> <li><p>ANSI X3.159-198 (C89): I cannot find a PDF of C89, but it is almost the same as C90. The only major differences are in the boilerplate and section numbering, although there are some slight textual differences</p> </li> <li><p>ISO/IEC 9899:1990 (C90): (Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. There is at least one textual difference in section 6.5.7 (previously 3.5.7), where <em>&quot;a list&quot;</em> became <em>&quot;a brace-enclosed list&quot;</em>. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as &quot;ANSI/ISO: 9899/99&quot; although this isn't the right name of the later made standard of it, the right name is &quot;ISO/IEC 9899:1990&quot;)</p> </li> <li><p>TC1 for C90: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf</a></p> </li> <li><p>There isn't a PDF link for TC2 on the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log.htm" rel="noreferrer">WG14 website</a>, sadly.</p> </li> <li><p>ISO/IEC 9899:1999 (C99 incorporating all three Technical Corrigenda): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf</a></p> </li> <li><p>An earlier version of C99 incorporating only TC1 and TC2: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf</a></p> </li> <li><p>Working draft for the original (i.e. pre-corrigenda) C99: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm</a> (HTML) and <a href="http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf" rel="noreferrer">http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf</a> (PDF). Note that there were two later working drafts: N869 and N878, but they seem to have been removed from the WG14 website, so this is the latest one available.</p> </li> <li><p>List of changes between C89/C90 and C99: <a href="http://port70.net/%7Ensz/c/c89/c9x_changes.html" rel="noreferrer">http://port70.net/~nsz/c/c89/c9x_changes.html</a></p> </li> <li><p>TC1 for C99 (only the TC, not the standard incorporating it): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF</a></p> </li> <li><p>TC2 for C99 (only the TC, not the standard incorporating it): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf</a></p> </li> <li><p>ISO/IEC 9899:2011 (C11): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf</a></p> <p>For information on the differences between N1570 and the final, published version of C11, see <a href="https://stackoverflow.com/questions/8631228/latest-changes-in-c11/15737472#15737472">Latest changes in C11</a> and <a href="https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw" rel="noreferrer">https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw</a></p> </li> <li><p>ISO/IEC 9899:2011/Cor 1:2012 (C11's only technical corrigendum): This can be viewed at <a href="https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en" rel="noreferrer">https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en</a> but cannot be downloaded. It is the actual corrigendum, not a draft.</p> </li> <li><p>ISO/IEC 9899:2018 (C17/C18): <a href="https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf</a> (N2176)</p> </li> <li><p>C2x work-in-progress - latest working draft as of 7th August 2022 (N3047): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n3047.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n3047.pdf</a></p> </li> </ul> <h3>For C++:</h3> <ul> <li><p>ISO/IEC 14882:1998 (C++98): <a href="http://www.lirmm.fr/%7Educour/Doc-objets/ISO+IEC+14882-1998.pdf" rel="noreferrer">http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf</a></p> </li> <li><p>ISO/IEC 14882:2003 (C++03): <a href="https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf" rel="noreferrer">https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf</a></p> </li> <li><p>ISO/IEC 14882:2011 (C++11): <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf</a></p> </li> <li><p>ISO/IEC 14882:2014 (C++14): <a href="https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true" rel="noreferrer">https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true</a></p> </li> <li><p>ISO/IEC 14882:2017 (C++17): <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf</a></p> </li> <li><p>ISO/IEC 14882:2020 (C++20): <a href="https://isocpp.org/files/papers/N4860.pdf" rel="noreferrer">https://isocpp.org/files/papers/N4860.pdf</a></p> </li> <li><p>ISO/IEC 14882:2023 (C++23 work-in-progress. Working draft dated March 17 2022): <a href="https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/n4910.pdf" rel="noreferrer">https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/n4910.pdf</a></p> </li> </ul> <p>Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.</p> <p>Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.</p> <hr /> <p>It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for &quot;INCITS/ISO/IEC&quot; instead of &quot;ISO/IEC&quot; when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for &quot;INCITS/ISO/IEC 9899:2011&quot; instead of &quot;ISO/IEC 9899:2011&quot; on <a href="https://webstore.ansi.org" rel="noreferrer">webstore.ansi.org</a> you will find the reasonably priced PDF version.</p> <hr /> <p>The site <a href="https://wg21.link/" rel="noreferrer">https://wg21.link/</a> provides short-URL links to the C++ current working draft and draft standards, and committee papers:</p> <ul> <li><a href="https://wg21.link/std11" rel="noreferrer">https://wg21.link/std11</a> - C++11</li> <li><a href="https://wg21.link/std14" rel="noreferrer">https://wg21.link/std14</a> - C++14</li> <li><a href="https://wg21.link/std17" rel="noreferrer">https://wg21.link/std17</a> - C++17</li> <li><a href="https://wg21.link/std20" rel="noreferrer">https://wg21.link/std20</a> - C++20</li> <li><a href="https://wg21.link/std" rel="noreferrer">https://wg21.link/std</a> - current working draft (as of May 2022 still points to the 2021 version)</li> </ul> <hr /> <p>The current draft of the standard is maintained as LaTeX sources on <a href="https://github.com/cplusplus/draft" rel="noreferrer">Github</a>. These sources can be converted to HTML using <a href="https://github.com/Eelis/cxxdraft-htmlgen" rel="noreferrer">cxxdraft-htmlgen</a>. The following sites maintain HTML pages so generated:</p> <ul> <li>Tim Song - <a href="https://timsong-cpp.github.io/cppwp/" rel="noreferrer">Current working draft</a> - <a href="https://timsong-cpp.github.io/cppwp/n3337/" rel="noreferrer">C++11</a> - <a href="https://timsong-cpp.github.io/cppwp/n4140/" rel="noreferrer">C++14</a> - <a href="https://timsong-cpp.github.io/cppwp/n4659/" rel="noreferrer">C++17</a> - <a href="https://timsong-cpp.github.io/cppwp/n4861/" rel="noreferrer">C++20</a></li> <li>Eelis - <a href="http://eel.is/c++draft/" rel="noreferrer">Current working draft</a></li> </ul> <p><a href="https://github.com/timsong-cpp/cppwp" rel="noreferrer">Tim Song</a> also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.</p> <h3>POSIX extensions to the C standard</h3> <p>The <a href="https://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> standard (IEEE 1003.1) requires a compliant operating system to include a C compiler. This compiler must in turn be compliant with the C standard, and must also support various extensions defined in the &quot;System Interfaces&quot; section of POSIX (such as the <code>off_t</code> data type, the <code>&lt;aio.h&gt;</code> header, the <code>clock_gettime()</code> function and the <code>_POSIX_C_SOURCE</code> macro.)</p> <p>So if you've tried to look up a particular function, been informed &quot;This function is part of POSIX, not the C standard&quot;, and wondered why an operating system standard was mandating compiler features and language extensions... now you know!</p> <ul> <li><p>POSIX.1-2001: The System Interfaces section can be downloaded as a separate document from <a href="https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf" rel="noreferrer">https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf</a>. Section 1.7 states that the relevant version of the C standard is C99.</p> <p>The &quot;Shell and Utilities&quot; section (<a href="https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf" rel="noreferrer">https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf</a>) mandates not only that a C99-compliant compiler should exist, but that it should be invokable from the command line under the name &quot;c99&quot;. One way in which this can be implemented is to place a shell script called &quot;c99&quot; in /usr/bin, which calls gcc with the <code>-std=c99</code> option added to the list of command-line parameters, and blocks any competing standards from being specified.</p> <p>POSIX.1-2001 had two technical corrigenda, one dated 2002 and one dated 2004. I don't think they're incorporated into the documents as linked above. There's an online HTML version incorporating the corrigenda at <a href="https://pubs.opengroup.org/onlinepubs/009695399/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/009695399/</a> - but I should add that I've had some trouble with the search box and so using Google to search the site is probably your best bet.</p> <p>There is a paywalled link to download the first corrigendum at <a href="https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html" rel="noreferrer">https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html</a>.</p> <p>There is also a paywalled link for the second at <a href="https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html" rel="noreferrer">https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html</a></p> </li> </ul> <ul> <li><p>There is a draft version of POSIX.1-2008 at <a href="http://www.open-std.org/jtc1/sc22/open/n4217.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/open/n4217.pdf</a>.</p> <p>POSIX.1-2008 also had two technical corrigenda, the latter of the two being dated 2016. There is an online HTML version of the standard incorporating the corrigenda at <a href="https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/</a> - though, again, I have had situations where the site's own search box wasn't good for finding information.</p> </li> <li><p>There is an online HTML version of POSIX.1-2017 at <a href="https://pubs.opengroup.org/onlinepubs/9699919799/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799/</a> - though, again, I recommend using Google instead of that site's searchbox. According to the <a href="https://www.opengroup.org/austin/" rel="noreferrer">Open Group website</a> &quot;IEEE 1003.1-2017 ... is a revision to the 1003.1-2008 standard to rollup the standard including its two technical corrigenda (as-is)&quot;. <a href="https://man7.org/linux/man-pages/man7/standards.7.html" rel="noreferrer">Linux manpages</a> describe it as &quot;technically identical&quot; to POSIX.1-2008 with Technical Corrigenda 1 and 2 applied. This is therefore not a major revision and does not change the value of the <code>_POSIX_C_SOURCE</code> macro.</p> </li> </ul>
<p>Although not an actual standard, there is an amendment to ISO C (C89/90) called C94/95, or Normative Addendum 1. It was integrated into C99, although some compilers such as <a href="http://clang.llvm.org/docs/UsersManual.html" rel="nofollow">Clang</a> allow you to specifiy <code>-std=c94</code> on the command line. ISO/IEC 9899:1990/Amd 1:1995 can be purchased for a hefty price from <a href="http://infostore.saiglobal.com/store/Details.aspx?DocN=isoc000767513" rel="nofollow"><strong>SAI GLOBAL</strong></a> (PDF or hard copy).</p> <ul> <li><a href="http://clc-wiki.net/wiki/The_C_Standard" rel="nofollow">http://clc-wiki.net/wiki/The_C_Standard</a></li> </ul> <p>A summary of the document can be found <a href="http://www.lysator.liu.se/c/na1.html" rel="nofollow">here</a>.</p> <blockquote> <p>When the (then draft) ANSI C Standard was being considered for adoption of an International Standard in 1990, there were several objections because it didn't address internationalization issues. Because the Standard had already been several years in the making, it was agreed that a few changes would be made to provide the basis (for example, the functions in subclause 7.10.7 were added), and work would be carried out separately to provide proper internationalization of the Standard. This work has culminated in Normative Addendum 1.</p> <p>Normative Addendum 1 embodies C's reaction to both the limitations and promises of international character sets. Digraphs and the header were meant to improve the appearance of C programs written in national variants of ISO 646 without, e.g., { or } characters. On the other end of the spectrum, the facilities connected to and extend the old Standard's barely adequate basis into a complete and consistent set of utilities for handling wide characters and multibyte strings.</p> <p>This document summarizes Normative Addendum 1. It is intended to quickly inform readers who are already familiar with the Standard; it does not, and cannot, introduce the complex subject matter behind NA1, nor can it replace the original document as a reference manual. (Nevertheless, it tries to be as accurate as possible, and its author would like to hear about any errors or omissions.)</p> </blockquote> <ul> <li><a href="http://www.lysator.liu.se/c/na1.html" rel="nofollow">http://www.lysator.liu.se/c/na1.html</a></li> </ul>
10,739
<p>I replaced the controller board in my Monoprice Select Mini with an Arduino/Ramps setup and compiled an uploaded Marlin 1.1.0-RC8 to run it. I've got most everything calibrated and working with one exception.</p> <p>I tell the printer to home for xyz and then level my bed with a piece of paper then start a print and the nozzle consistently drops too far down into the bed and nothing can extrude. If I adjust the bed and put 1-2mm gap between the nozzle and bed then it prints fine. </p> <p>I can't find anything in Marlin to adjust for this and I'm kind of stumped. I'm printing the original cat gcode that came with the printer that should just work fine as it always has and shouldn't have anything that a slicer would put in there to screw things up. </p> <p>Can anyone point me in the right direction?</p> <p>This is the output of M503</p> <pre><code>Send: M503 Recv: echo:Steps per unit: Recv: echo: M92 X93.00 Y93.00 Z1097.50 E99.00 Recv: echo:Maximum feedrates (mm/s): Recv: echo: M203 X300.00 Y300.00 Z5.00 E25.00 Recv: echo:Maximum Acceleration (mm/s2): Recv: echo: M201 X3000 Y3000 Z100 E10000 Recv: echo:Accelerations: P=printing, R=retract and T=travel Recv: echo: M204 P3000.00 R3000.00 T3000.00 Recv: echo:Advanced variables: S=Min feedrate (mm/s), T=Min travel feedrate (mm/s), B=minimum segment time (ms), X=maximum XY jerk (mm/s), Z=maximum Z jerk (mm/s), E=maximum E jerk (mm/s) Recv: echo: M205 S0.00 T0.00 B20000 X20.00 Y20.00 Z0.40 E5.00 Recv: echo:Home offset (mm) Recv: echo: M206 X0.00 Y0.00 Z0.00 Recv: echo:Material heatup parameters: Recv: echo: M145 S0 H180 B70 F255 Recv: M145 S1 H240 B110 F0 Recv: echo:PID settings: Recv: echo: M301 P26.15 I2.74 D62.35 Recv: echo: M304 P231.09 I45.21 D295.34 Recv: echo:Filament settings: Disabled Recv: echo: M200 D3.00 Recv: echo: M200 D0 Recv: ok </code></pre> <p>I also wanted to test whether the nozzle is actually moving closer. I did a G28 and manually put a piece of paper's width gap between the nozzle and the bed at all points. Then I started a print with no filament but with the sheet between the nozzle and bed. When it got to temp it homed all the axis and moved the nozzle to the first position. I would expect the paper to maintain the same gap but it tightly presses into the paper. The first gcode move that includes the Z before extruding is :</p> <pre><code>G0 F3600 X42.228 Y46.985 Z0.3 </code></pre> <p>Which you would expect would put even more space between the nozzle and bed for the first .3 layer of filament but it isn't.</p> <p>I printed directly from the SD Card to hopefully rule out Octoprint running gcode before the print so I really think the culprit is Marlin at this point.</p>
<p>I found the issue. When the hotend and bed are at temps for PLA everything works fine but at temps for ABS the Z offset would get all messed up. After a bunch of testing I was able to track it down to a single gcode statment <code>G1 Z15.0 F6000</code> At the higher temps my Z stepper skips steps at that feed rate. </p> <p>The "Custom FDM printer" machine settings I used for my printer in Cura had that statement in it and so did the cat gcode that was on the card from the factory. I changed the feed rate to 200 and was able to print in ABS.</p> <p>I was surprised Marlin didn't have a 'limit the feedrate for Z to this number' setting.</p>
<p>If nozzle sets lower than it should, after heating up, then you may need to calibrate with heater turned on.</p> <p>Another (although less likely) reason can be an incorrect Z steps number. However, if the print, after adjusting the first line height, does well, this should not be the case.</p> <p>Fast track solution is to use <code>M206</code> (something like <code>M206 Z0.3</code>) command to adjust nozzle offset, in your case Z position. This does not fix the root cause but should allow you to mitigate the problem.</p>
557
<p><strong>What libraries are there to write C# internationalized applications?</strong></p> <p>Typical functionalities that should be contained in the library:</p> <ul> <li>Validation of country specific data (e.g. VAT numbers, phone numbers, addresses,...)</li> <li>Validation of bank and financial coordinates (e.g. Credit Card numbers, IBAN,...)</li> <li>Language-specific functionalities (e.g. numbers to words to numbers, summarize,...)</li> <li>Language specific content filtering (e.g. swearword filtering...)</li> </ul> <p>An example of such libraries in Perl would be the <a href="http://search.cpan.org/modlist/Internationalization_Locale" rel="noreferrer">Internationalization/Locale section</a> of CPAN.</p> <p>What C# solutions are available?</p> <hr> <p>Note: I am not looking for an introduction to the System.Globalization namespace :)</p> <hr> <p>Note 2: Should I desume that there are no options available? Is someone interested in joining forces and create one?</p> <hr> <p>Note 3: Edit to make the question appear on front page in hope of more answers. This isn't such a hard question, how is it possible that Stackers don't ever do i18n?</p>
<p>I wouldn't say that no one does i18n, but I don't know of any generic tools that can be used for every project. Maintaining a database with all of the information you are looking for would be an epic project. It sounds like what you're looking for isn't a specific C# library, but more a collection of information online that you can draw from. If you were able to find a repository of swear words in various languages (for example), it would be trivial for you to use this in C#. I think that finding a solution that wraps up all of your requirements into an easy-to-use assembly is going to be impossible to find.</p>
<p>Not exactly a "library", per se, but I've actually ran into a great service (for pay), by a company called <a href="http://www.fiftyone.com/" rel="nofollow noreferrer">E4X</a> (former client of mine).<br> What they provide is complete localization of your ecommerce site, including language translations, currency exchanges, local billing and handling of financial transactions including region-specific taxes etc, and more. They even deal with logisitics of physical shipping... </p> <p>Worth looking into, for an ecommerce business. Let 'em know I sent you... ;-)</p>
13,316
<p>For practicality sake, I need to print a design such that there will be weight hanging parellel to the layer lines. Is there an infill pattern that would be better than others at handling this?</p> <p>I realize that all kinds of infill will still have the same layer boundaries. Just wondering if choosing any given infill might provide better results.</p>
<p>Yes, some infill patterns are better than others for preventing separation of layers. Basically (modulo some assumptions about uniformity of distribution of force), the shearing strength of the part in the Z direction at a particular layer is going to be proportional to the <em>surface area</em> of bonding between successive layers. So infill patterns that stack identical infill extrusions on top of each other at each layer should be expected to be much stronger than patterns where successive layers make only partial contact. In other words, "2D infill patterns" - grid, lines, triangles, tri-hexagon - should be a lot stronger than "3D infill patterns" - cubic, octet, gyroid, ... This matches my experience printing bolts oriented along the Z-axis - ones printed with gyroid snap easily unless other measures are taken to strengthen them, while ones printed with triangles are fairly strong (though nowhere near as strong as ones printed oriented in the XY plane.</p> <p>If you have other reason to prefer a "3D infill pattern", its weakness can be mitigated mostly by increasing the infill line width, so that the lines of successive layers which don't entirely overlap still touch on more surface area. (Just increasing the infill line width also works to make "2D infill patterns" even stronger.) However, be aware that with high print speed typically used for infill, increasing infill line width can easily exceed the capability of your hotend, resulting in underextrusion, extruder skipping, and stringing all over the place.</p>
<p>0scar's answer is the "solution" or true answer to the question.</p> <p>Watching youtube the last few days, cubic needs to be considered. I was surprised at what I saw. More to consider is adding design elements:</p> <ul> <li>The concept of flutes along the perimeter.</li> <li>Adding through holes increases strength incredibly.</li> </ul>
1,588
<p>I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement. </p> <p>Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise?</p> <p>--edit</p> <p>It seems I was vague like the exception =). The point is to _not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception</p> <p>@ W. Craig Trader</p> <p>Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just <strong><em>tweak</em></strong> me to no end, and lead me to posting this question to the community. </p> <p>Thanks for everyone's suggestions.</p>
<p>At the point where the NRE is thrown, there is no target object -- that's the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you're having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you're doing too much on one line of code.</p> <p>A better solution to this sort of problem is <a href="http://en.wikipedia.org/wiki/Design_By_Contract" rel="nofollow noreferrer">Design by Contract</a>, either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won't work with bad data.</p> <p><strong>[Edit to match question edit:]</strong></p> <p>I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program:</p> <pre><code>public class NullPointerExample { public static void Main() { Object foo; System.Console.WriteLine( foo.ToString() ); } } </code></pre> <p>When you run this, it's going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There's a class and a method, but no object.</p> <hr> <p>Re: Chris Marasti-Georg's <a href="https://stackoverflow.com/questions/115573/detecting-what-the-target-object-is-when-nullreferenceexception-is-thrown#115619">answer</a>:</p> <p>You should never throw NRE yourself -- that's a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn't initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you'll only confuse the next programmer who has to maintain your app.</p>
<p>you can check the Message and InnerException properties</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx</a></p>
14,090
<p>I've found databases typically come in two flavors, your traditional row-oriented RDBMS or an object oriented database (OODBMS). However, in the mid 90s I remember, a new breed of databases showing up that were column oriented. Some of these were given the term 4GL, but I don't think it was a term that stuck.</p> <p>What I'd like to know is the following:</p> <ul> <li>What column oriented databases still exist?</li> <li>What are the performance characteristics of these databases?</li> <li>Are there any open source column oriented databases?</li> <li>What platforms do they interoperate with (.NET, Java, etc)</li> <li>What's been your general experience with them?</li> </ul> <p>The two column oriented databases that I remember working with are FAME and KDB.</p>
<p><a href="http://en.wikipedia.org/wiki/HBase" rel="noreferrer">HBase</a> is an open-source column-oriented database system modelled on <a href="http://en.wikipedia.org/wiki/BigTable" rel="noreferrer">Google's BigTable</a>.</p>
<p>Sybase IQ is column oriented . All columns are automatically indexed when you create a table and data is nicely compressed in the columns.</p> <p>It's a nice OLAP database (...data warehouse) but I would not recommend it for any kind of transaction processing as it is designed for data warehouse operations.</p> <p>As for performance characteristics, SELECTS are very fast for large volumes of data but INSERT / UPDATE / DELETEs are very slow compared to a standard OLTP DB such as Sybase ASE for example. Table locking is also very different to a OLTP database so expect exclusive table locks for write operations (INSERTS etc) when working in the MAIN data store.</p> <p>Otherwise it supports T-SQL (Sybase version) and Watcom SQL.</p> <p>Cheers,</p> <p>Kevin</p>
41,580
<p>Ruby is becoming <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="noreferrer">popular</a>, largely from the influence Ruby on Rails, but it feels like it is currently struggling through its adolescence. There are a lot of similarities between Ruby and Smalltalk -- <a href="http://ruby.gemstone.com/" rel="noreferrer">maglev</a> is a testament to that. Despite having a more unusual syntax, Smalltalk has all (if not more) of the object-oriented beauty of Ruby. </p> <p>From what I have read, Smalltalk seems to have Ruby beat on:</p> <ul> <li>Maturity (developed in the 1970's)</li> <li>Stability</li> <li>Commercial support</li> <li><a href="http://www.wiresong.ca/monticello/" rel="noreferrer">Distributed source control</a> (understands structure of code, not just text diffing)</li> <li>Several <a href="http://en.wikipedia.org/wiki/Smalltalk#List_of_implementations" rel="noreferrer">implementations of the VM</a></li> <li>Cross-platform support</li> <li>The <a href="http://www.seaside.st/" rel="noreferrer">seaside web framework</a> as a <a href="http://www.sauria.com/blog/2005/11/10" rel="noreferrer">strong alternative to Rails</a> </li> </ul> <p>It seems like Ruby is just reinventing the wheel. So, why don't Ruby developers use SmallTalk? <strong>What does Ruby have the Smalltalk doesn't?</strong> </p> <p><em>For the record: I'm a Ruby guy with little to no experience in Smalltalk, but I'm starting to wonder why.</em></p> <hr> <p><strong>Edit:</strong> I think the ease-of-scripting issue has been addressed by <a href="http://en.wikipedia.org/wiki/GNU_Smalltalk" rel="noreferrer">GNU Smalltalk</a>. As I understand it, this allows you to write smalltalk in regular old text files, and you no longer need to be in the Smalltalk IDE. You can then <a href="http://www.gnu.org/software/smalltalk/manual/html_node/Invocation.html#Invocation" rel="noreferrer">run your scripts</a> with:</p> <pre><code>gst smalltalk_file </code></pre>
<p>I'm more of a Pythonista than a Ruby user, however the same things hold for Ruby for much the same reasons.</p> <ul> <li><p>The architecture of Smalltalk is somewhat insular whereas Python and Ruby were built from the ground up to facilitate integration. Smalltalk never really gained a body of hybrid application support in the way that Python and Ruby have, so the concept of 'smalltalk as embedded scripting language' never caught on.<br><br>As an aside, Java was not the easiest thing to interface with other code bases (JNI is fairly clumsy), but that did not stop it from gaining mindshare. IMO the interfacing argument is significant - ease of embedding hasn't hurt Python - but this argument only holds moderate weight as not all applications require this capability. Also, later versions of Smalltalk did substantially address the insularity.</p></li> <li><p>The class library of most of the main smalltalk implementations (VisualWorks, VisualAge etc.) was large and had reputation for a fairly steep learning curve. Most key functionality in Smalltalk is hidden away somewhere in the class library, even basic stuff like streams and collections. The language paradigm is also something of a culture shock for someone not familiar with it, and the piecemeal view of the program presented by the browser is quite different to what most people were used to.<br><br>The overall effect is that Smalltalk got a (somewhat deserved) reputation for being difficult to learn; it takes quite a bit of time and effort to become a really proficient Smalltalk programmer. Ruby and Python are much easier to learn and to bring new programmers up to speed with.</p></li> <li><p>Historically, mainstream Smalltalk implementations were quite expensive and needed exotic hardware to run, as can be seen <a href="http://groups.google.co.uk/group/net.lang.st80/browse_thread/thread/c35c4ad7fad659c4?hl=en#" rel="noreferrer">this net.lang.st80 posting from 1983</a>. Windows 3.1, NT and '95 and OS/2 were the first mass market operating systems on mainstream hardware capable of supporting a Smalltalk implementation with decent native system integration. Previously, Mac or workstation hardware were the cheapest platforms capable of running Smalltalk effectively. Some implementations (particularly Digitalk) supported PC operating systems quite well and did succeed in gaining some traction.<br><br>However, OS/2 was never that successful and Windows did not achieve mainstream acceptance until the mid 1990s. Unfortunately this coincided with the rise of the Web as a platform and a large marketing push behind Java. Java grabbed most of the mindshare in the latter part of the 1990s, rendering Smalltalk a bit of an also-ran.</p></li> <li><p>Ruby and Python work in a more conventional toolchain and are not tightly coupled to a specific development environment. While the Smalltalk IDEs I have used are nice enough I use PythonWin for Python development largely because it has a nice editor with syntax highlighting and doesn't get underfoot.<br><br>However, Smalltalk is was designed to be used with an IDE (in fact, Smalltalk was the original graphical IDE) and still has some nice features not replicated by other systems. Testing code with highlight and 'Show it' is still a very nice feature that I have never seen in a Python IDE, although I can't speak for Ruby.</p></li> <li><p>Smalltalk was somewhat late coming to the web application party. Early efforts such as VisualWave were never terribly successful and it was not until Seaside came out that a decent web framework got acceptance in Smalltalk circles. In the meantime Java EE has had a complete acceptance lifecycle starting with raving fanboys promoting it and finally getting bored and moving onto Ruby ;-}<br><br>Ironically, Seaside is starting to get a bit of mindshare among the cognoscenti so we may find that Smalltalk rides that cycle back into popularity.</p></li> </ul> <p>Having said that, Smalltalk is a very nice system once you've worked out how to drive it. </p>
<p>I think part of the problem is the development-environment-is-the-runtime. This gives a lot of power, but it also presents a larger learning curve. </p> <p><a href="http://wiki.squeak.org/squeak/2230" rel="nofollow noreferrer">Here</a> is a hello world tutorial.</p> <p>This is very different from other languages where I just need to know how to open a text editor and copy and paste text, hit save, and run a compiler. I HAVE to know how to use the environment. That tutorial doesn't even show me how to create a basic program (which is likely more a fault of that tutorial) that I can run.</p> <p>There is definately a higher cost of just getting things going than most other languages.</p> <p>Most languages have some nice eye-catching code that they can show off. I haven't seen that with Smalltalk. I also think that there is some stigma to Smalltalk because it has been around so long and it is still relatively obscure.</p>
22,691
<p>Errors that occur deep down in a data access layer or even higher up, (say within ADO.net operations for example) rarely make much sense to an end user. Simply bubbling these errors up to a UI and displaying them will usually achieve nothing except frustration for an end user.</p> <p>I have recently employed a basic technique for reporting errors such as this whereby I catch the error and at least add some user friendly text so that at least the end user understands what failed.</p> <p>To do this I am catching an exception within each specific function (say for example a fetch function in a data access layer), then raising a new error with user friendly text about the function that has failed and probably cause, but then embedding the original exception in the new exception as the "inner exception" of that new exception. </p> <p>This can then occur at each layer if necessary, each consumer of the lower level function adding it's own context to the error message, so that what reaches the UI is an increasingly user friendly error message.</p> <p>Once the error reaches the UI - if necessary - it can then iterate through the nested exceptions in order to display an error message that firstly tells the user which operation failed, but also provides a bit of technical information about what actually went wrong.</p> <p>e.g. </p> <blockquote> <p>"The list of customer names your requested could not be displayed."</p> <p>"Obtaining the list of customers you requested failed due to an error with the database."</p> <p>"There was an error connecting to the database when retrieving a list of customers"</p> <p>"Login failed for user xx"</p> </blockquote> <p>My question is this: Is this horribly inefficient (all those nested exceptions)? I suspect it is not best practice so what should I be doing to achieve the same thing - or should I in fact be trying to achieve something better?</p>
<p>It is just slightly horrible.</p> <p>If you are showing an error to the end user, the user is supposed to be able to act about it. In "The list of customer names your requested could not be displayed." case, your user will just think "so what?" On all of these cases, just display a "something bad happened" message. You do not even need to catch these exceptions, when something goes bad, let some global method (like application_error) handle it and display a generic message. When you or your user can do something about the error, catch it and do the thing or notify the user.</p> <p>But you will want to log every error that you do not handle.</p> <p>By the way, displaying information about the errors occuring may yield to security vulnerabilities. The less the attackers know about your system, the less likely they will find ways to hack it (remember those messages like "Syntax error in sql statement: Select * From Users Where username='a'; drp database;--'..." expected: 'drop' instead of 'drp'. They do not make sites like these anymore).</p>
<p>Generally when you're dealing with exceptions, performance and efficiency are the least of your worries. You should be more worried about doing something to help the user recover from the problem. If there was a problem writing a certain record to the database, either roll the changes back or at least dump the row information so the user doesn't lose it.</p>
13,502
<p>I've downloaded the IKVM sources (<a href="http://www.ikvm.net/" rel="nofollow noreferrer">http://www.ikvm.net/</a>) from <a href="http://sourceforge.net/cvs/?group_id=69637" rel="nofollow noreferrer">http://sourceforge.net/cvs/?group_id=69637</a></p> <p>Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?</p> <p>I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors.</p> <p>As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse.</p> <p>So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio.</p> <p>Let me know if you need any more info. Thanks for any help!</p> <p><strong>Edit:</strong> I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of:</p> <pre><code>JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a re you missing an assembly reference?) JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) </code></pre> <p><strong>Edit #2</strong>: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error:</p> <p>ikvm-native-win32:</p> <pre><code> [mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. [cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. BUILD FAILED C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10): 'cl' failed to start. The system cannot find the file specified Total time: 0.2 seconds. </code></pre> <p><strong>Edit #3</strong>: OK solved that by putting <code>cl.exe</code> in the path, still getting other errors though. <strong><em>Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...</em></strong></p> <p><strong>Edit #4</strong>: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?!</p> <pre><code> [exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java [exec] Usage: javac &lt;options&gt; &lt;source files&gt; [exec] use -help for a list of possible options </code></pre> <p><strong>Edit #5</strong>: Got an answer from the author. See below or at <a href="http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf" rel="nofollow noreferrer">http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf</a> Let's see if it works...</p> <p><strong>Edit #6</strong> As I feared, next problem: "cannot open windows.h", see separate question <a href="https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory">here</a>.</p> <p><strong>Final Edit: Found Solution!</strong> After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me.</p>
<p>I don't know that this would do it for you but can you try building from the command line?</p> <p>msbuild ________</p> <p>I think that's how I built the application due to the same issues.</p>
<p>This is how I built IKVM 8.1.5717.0 from source. Visual Studio is not required.</p> <ul> <li><p>Create a folder: c:\ikvm\</p></li> <li><p>Add the above folder to PATH (e.g. set PATH=%PATH%;c:\ikvm and leave command prompt open for later).</p></li> <li><p>Download: ikvmsrc-8.1.5717.0.zip (<a href="http://www.frijters.net/ikvmsrc-8.1.5717.0.zip" rel="nofollow noreferrer">http://www.frijters.net/ikvmsrc-8.1.5717.0.zip</a>)</p></li> <li><p>Unzip and place "ikvm-8.1.5717.0" folder in c:\ikvm\</p></li> <li><p>Download: openjdk-8u45-b14-stripped.zip (<a href="http://www.frijters.net/openjdk-8u45-b14-stripped.zip" rel="nofollow noreferrer">http://www.frijters.net/openjdk-8u45-b14-stripped.zip</a>)</p></li> <li><p>Unzip and place "openjdk-8u45-b14" folder in c:\ikvm\</p></li> <li><p>Download: Java 8 SDK (<a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" rel="nofollow noreferrer">http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html</a>)</p></li> <li><p>Install and make sure location is added to path</p></li> <li><p>Download: NAnt 0.92 (<a href="https://sourceforge.net/projects/nant/files/nant/0.92/nant-0.92-bin.zip/download" rel="nofollow noreferrer">https://sourceforge.net/projects/nant/files/nant/0.92/nant-0.92-bin.zip/download</a>)</p></li> <li><p>Unzip and place "nant-0.92" folder in c:\ikvm\</p></li> <li><p>ICSharpCode.SharpZipLib.dll (<a href="http://www.icsharpcode.net/opensource/sharpziplib/Download.aspx" rel="nofollow noreferrer">http://www.icsharpcode.net/opensource/sharpziplib/Download.aspx</a>)</p></li> <li><p>Place "ICSharpCode.SharpZipLib.dll" in C:\ikvm\ikvm-8.1.5717.0\bin\</p></li> <li><p>Open the following file in a text editor and change the version number: C:\ikvm\ikvm-8.1.5717.0\CommonAssemblyInfo.cs.in</p></li> <li><p>Using command prompt from earlier, cd to: C:\ikvm\ikvm-8.1.5717.0\ikvm\</p></li> <li><p>Run: ..\nant-0.92\bin\NAnt.exe</p></li> <li><p>If successful all the binaries will be in: C:\ikvm\ikvm-8.1.5717.0\bin</p></li> </ul>
9,713
<p>We try to convert from string to <code>Byte[]</code> using the following Java code:</p> <pre><code>String source = "0123456789"; byte[] byteArray = source.getBytes("UTF-16"); </code></pre> <p>We get a byte array of length 22 bytes, we are not sure where this padding comes from. How do I get an array of length 20?</p>
<p><a href="https://stackoverflow.com/questions/228987/convert-string-to-byte-in-java#228998">Alexander's answer</a> explains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name:</p> <pre><code>String source = "0123456789"; byte[] byteArray = source.getBytes("UTF-16LE"); // Or UTF-16BE </code></pre>
<p>Try printing out the bytes in hex to see where the extra 2 bytes are added - are they at the start or end?</p> <p>I'm picking that you'll find a <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark" rel="noreferrer">byte order marker</a> at the start (0xFEFF) - this allows anyone consuming (receiving) the byte array to recognise whether the encoding is little-endian or big-endian.</p>
28,339
<p>Basically, I have an <code>iframe</code> embedded in a page and the <code>iframe</code> has some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> routines I need to invoke from the parent page.</p> <p>Now the opposite is quite simple as you only need to call <code>parent.functionName()</code>, but unfortunately, I need exactly the opposite of that.</p> <p>Please note that my problem is not changing the source <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URL</a> of the <code>iframe</code>, but invoking a function defined in the <code>iframe</code>.</p>
<p>Assume your iFrame's id is "targetFrame" and the function you want to call is <code>targetFunction()</code>:</p> <pre><code>document.getElementById('targetFrame').contentWindow.targetFunction(); </code></pre> <p>You can also access the frame using <code>window.frames</code> instead of <code>document.getElementById</code>.</p> <pre><code>// this option does not work in most of latest versions of chrome and Firefox window.frames[0].frameElement.contentWindow.targetFunction(); </code></pre>
<p>Use following to call function of a frame in parent page</p> <pre><code>parent.document.getElementById('frameid').contentWindow.somefunction() </code></pre>
31,311
<p>I have this doubt, I've searched the web and the answers seem to be diversified. Is it better to use mysql_pconnect over mysql_connect when connecting to a database via PHP? I read that pconnect scales much better, but on the other hand, being a persistent connection... having 10 000 connections at the same time, all persistent, doesn't seem scalable to me.</p> <p>Thanks in advance.</p>
<p>Persistent connections should be unnecessary for MySQL. In other databases (such as Oracle), making a connection is expensive and time-consuming, so if you can re-use a connection it's a big win. But those brands of database offer connection pooling, which solves the problem in a better way.</p> <p>Making a connection to a MySQL database is quick compared to those other brands, so using persistent connections gives proportionally less benefit for MySQL than it would for another brand of database.</p> <p>Persistent connections have a downside too. The database server allocates resources to each connection, whether the connections are needed or not. So you see a lot of wasted resources for no purpose if the connections are idle. I don't know if you'll reach 10,000 idle connections, but even a couple of hundred is costly.</p> <p>Connections have state, and it would be inappropriate for a PHP request to "inherit" information from a session previously used by another PHP request. For example, temporary tables and user variables are normally cleaned up as a connection closes, but not if you use persistent connections. Likewise session-based settings like character set and collation. Also, <code>LAST_INSERT_ID()</code> would report the id last generated during the session -- even if that was during a prior PHP request.</p> <p>For MySQL at least, the downside of persistent connections probably outweighs their benefits. And there are other, better techniques to achieve high scalability.</p> <hr> <p>Update March 2014:</p> <p>MySQL connection speed was always low compared to other brands of RDBMS, but it's getting even better.</p> <p>See <a href="http://mysqlserverteam.com/improving-connectdisconnect-performance/" rel="noreferrer">http://mysqlserverteam.com/improving-connectdisconnect-performance/</a></p> <blockquote> <p>In MySQL 5.6 we started working on optimizing the code handling connects and disconnects. And this work has accelerated in MySQL 5.7. In this blog post I will first show the results we have achieved and then describe what we have done to get them.</p> </blockquote> <p>Read the blog for more details and speed comparisons.</p>
<p><strong>MYSQL_CONNECT()</strong></p> <p>1.mysql_connect can be used to close the connection.Every time it is opening and closing the database connection, depending on the request .</p> <p>2.Here database is opened everytime when the page is loaded in MYSQL connect</p> <p>3.When the page is loaded, the database is loaded everytime</p> <p>4.It is used to close the connection</p> <p>Example:</p> <pre><code>&lt;?php $conn = mysql_connect(‘host’, ‘mysql_user’, ‘mysql_password’); if(!$conn){ die(‘Could not connect: ‘ . mysql_error()); } echo ‘Connected successfully’; mysql_close($conn); ?&gt; </code></pre> <p>Description:</p> <p>host: Specifies a host name or an IP address like localhost.</p> <p>mysql_user: Specifies the MySQL username</p> <p>mysql_password: Specifies the MySQL password</p> <p><strong>MYSQL_PCONNECT()</strong></p> <p>1.We use the mysql_pconncet(), it initially tries to find an open persistent connection.</p> <p>2.The mysql_pconncet() opens persistant connection</p> <p>3.The mysql_pconnect() does not support the close connection</p> <p>4.mysql_pconnect() cannot close the connection. Here open a persistant connection to the database</p> <p>5.Here database need not be connected everytime.</p> <p>6.The database need not be connected every time in mysql_pconncet().</p> <p>more details:<a href="http://prittytimes.com/difference-between-mysql_connect-and-mysql_pconnect/" rel="nofollow">http://prittytimes.com/difference-between-mysql_connect-and-mysql_pconnect/</a></p>
30,784
<p>What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?</p> <p>These objects are stored in ActiveRecord so using AR's methods would be fine too. </p>
<p>Use <a href="http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq" rel="noreferrer"><code>Array#uniq</code></a> with a block:</p> <pre><code>@photos = @photos.uniq { |p| p.album_id } </code></pre>
<p>Now if you can sort on the attribute values this can be done:</p> <pre><code>class A attr_accessor :val def initialize(v); self.val = v; end end objs = [1,2,6,3,7,7,8,2,8].map{|i| A.new(i)} objs.sort_by{|a| a.val}.inject([]) do |uniqs, a| uniqs &lt;&lt; a if uniqs.empty? || a.val != uniqs.last.val uniqs end </code></pre> <p>That's for a 1-attribute unique, but the same thing can be done w/ lexicographical sort ...</p>
13,501
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet <a href="https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument">Python produces unexpected behavior in these situations</a>.</p> <p>If for example, I have a function:</p> <pre><code>def my_func(working_list=[]): working_list.append(&quot;a&quot;) print(working_list) </code></pre> <p>The first time it is called, the default will work, but calls after that will update the existing list (with one <code>&quot;a&quot;</code> each call) and print the updated version.</p> <p>So, what is the Pythonic way to get the behavior I desire (a fresh list on each call)?</p>
<pre class="lang-py prettyprint-override"><code>def my_func(working_list=None): if working_list is None: working_list = [] # alternative: # working_list = [] if working_list is None else working_list working_list.append(&quot;a&quot;) print(working_list) </code></pre> <p><a href="https://docs.python.org/reference/compound_stmts.html#function-definitions" rel="noreferrer">The docs</a> say you should use <code>None</code> as the default and explicitly <a href="https://stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none">test for it</a> in the body of the function.</p>
<p>I took the UCSC extension class <code>Python for programmer</code></p> <p>Which is true of: def Fn(data = []):</p> <blockquote> <p>a) is a good idea so that your data lists start empty with every call.</p> <p>b) is a good idea so that all calls to the function that do not provide any arguments on the call will get the empty list as data.</p> <p>c) is a reasonable idea as long as your data is a list of strings.</p> <p>d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.</p> </blockquote> <p>Answer:</p> <blockquote> <p>d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.</p> </blockquote>
47,829
<p>While an applet is loading, it displays a white rectangle for a split second. How can we get rid of it?</p>
<p>I found a solution that does not require any third-party library or custom tasks using the <a href="http://ant.apache.org/manual/Tasks/script.html" rel="noreferrer"><code>&lt;script&gt;</code> task</a> that allows for using JavaScript (or any other <a href="http://jakarta.apache.org/bsf" rel="noreferrer">Apache BSF</a> or <a href="https://scripting.dev.java.net/" rel="noreferrer">JSR 223</a> supported language) from within an Ant target.</p> <pre><code>&lt;target name="insert-filesize"&gt; &lt;length file="${afile}" property="fs.length.bytes" /&gt; &lt;script language="javascript"&gt; &lt;![CDATA[ var length_bytes = project.getProperty("fs.length.bytes"); var length_kbytes = Math.round((length_bytes / 1024) * Math.pow(10,2)) / Math.pow(10,2); var length_mbytes = Math.round((length_kbytes / 1024) * Math.pow(10,2)) / Math.pow(10,2); project.setNewProperty("fs.length.kb", length_kbytes); project.setNewProperty("fs.length.mb", length_mbytes); ]]&gt; &lt;/script&gt; &lt;copy todir="${target.dir}"&gt; &lt;fileset dir="${source.dir}"&gt; &lt;include name="**/*" /&gt; &lt;exclude name="**/*.zip" /&gt; &lt;/fileset&gt; &lt;filterset begintoken="$$$$" endtoken="$$$$"&gt; &lt;filter token="SIZEBYTES" value="${fs.length.bytes}"/&gt; &lt;filter token="SIZEKILOBYTES" value="${fs.length.kb}"/&gt; &lt;filter token="SIZEMEGABYTES" value="${fs.length.mb}"/&gt; &lt;/filterset&gt; &lt;/copy&gt; &lt;/target&gt; </code></pre>
<p>There is a math task at <a href="http://ant-contrib.sourceforge.net/" rel="nofollow noreferrer">http://ant-contrib.sourceforge.net/</a> that may be useful</p>
40,298
<p>What is the equivalent of varchar(max) in MySQL?</p>
<p>The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):</p> <pre><code>VARCHAR(65535) </code></pre> <p>However, note that the limit is lower if you use a multi-byte character set:</p> <pre><code>VARCHAR(21844) CHARACTER SET utf8 </code></pre> <hr> <p>Here are some examples:</p> <p>The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.</p> <pre><code>mysql&gt; CREATE TABLE foo ( v VARCHAR(65534) ); ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs </code></pre> <p>But if we try decreasing lengths, we find the greatest length that works:</p> <pre><code>mysql&gt; CREATE TABLE foo ( v VARCHAR(65532) ); Query OK, 0 rows affected (0.01 sec) </code></pre> <p>Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't <em>necessarily</em> use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.</p> <pre><code>mysql&gt; CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8; ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead </code></pre> <p>In spite of what the last error told us, InnoDB still doesn't like a length of 21845.</p> <pre><code>mysql&gt; CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8; ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs </code></pre> <p>This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.</p> <pre><code>mysql&gt; CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8; Query OK, 0 rows affected (0.32 sec) </code></pre>
<p>Mysql Converting column from VARCHAR to TEXT when under limit size!!!</p> <pre><code>mysql&gt; CREATE TABLE varchars1(ch3 varchar(6),ch1 varchar(3),ch varchar(4000000)) ; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql&gt; SHOW WARNINGS; +-------+------+---------------------------------------------+ | Level | Code | Message | +-------+------+---------------------------------------------+ | Note | 1246 | Converting column 'ch' from VARCHAR to TEXT | +-------+------+---------------------------------------------+ 1 row in set (0.00 sec) mysql&gt; </code></pre>
43,128
<p>I am looking for any kind of information (prefer Moq) on how to unit test the Application_Start method in Global.asax. I am using ASP.NET MVC and trying to get to that elusive 100% code coverage!</p> <p>The fact that I'm using MVC is not the point. And saying that not testing Start is not necessary isn't really the answer either. What if I had other code in there? I need to know how to test it.</p>
<p>Some organizations do require those meaningless numbers, and have issues beyond cost. For companies dealing with $ensitive information "Good enough" is not good enough. I had exactly the same issue and like Klas Mellbourn, need to get to 100% (if not higher!) The following worked for me. Although, I'd have preferred to mark it "Exclude from code coverage"</p> <pre><code>public class Global : HttpApplication { public override void Init() { AreaRegistration.RegisterAllAreas(); //will error out on app_start base.Init(); } /// &lt;summary&gt; /// Application_Start method. /// &lt;/summary&gt; /// &lt;param name="sender"&gt;The caller&lt;/param&gt; /// &lt;param name="e"&gt;The event arguments&lt;/param&gt; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "KMM: This method is called dynamically by the framework.")] protected void Application_Start(object sender, EventArgs e) { var container = StructureMapRegistry.Initialize(); GlobalConfiguration.Configuration.DependencyResolver = new StructureMapResolver(container); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); } } </code></pre> <p>Then the unit test looked like this:</p> <pre><code> public class GlobalTest : Global { private HttpRequestMessage FakeRequest; DateTime? effectiveDate = DateTime.Now.AddYears(-4); private string policyNumber = "1234567890"; [TestMethod] public void ApplicationStart() { var sender = new object(); var e = new EventArgs(); try { Application_Start(sender, e); // this will error b/c not fully loaded yet. } catch (InvalidOperationException) { Thread.Sleep(2000); // give the app time to launch Application_Start(sender, e); } Assert.IsTrue(true); } } </code></pre> <p>and finally, I needed to set a flag in my WebApiConfig to prevent the routes from being registered twice.</p> <pre><code> public static class WebApiConfig { private static bool isRegistered; /// &lt;summary&gt; /// Registers the configuration. /// &lt;/summary&gt; /// &lt;param name="config"&gt;The Http Configuration.&lt;/param&gt; public static void Register(HttpConfiguration config) { if (isRegistered) { return; } config.MapHttpAttributeRoutes(); </code></pre> <p>Now, before the haters and purists start marking this down, the assignment is to test all code. I personally detest modifying code to suit tests. That's not the same thing as making code testable. Adding the isRegistered flag is an example of the sort of artifact that is necessary to support the test needing to call the app_start 2x. It's a small thing and since that code only gets called on app_start, I'm not going to fuss over it too much. I would certainly be interested in what others have done in this regard.</p>
<p>this function is called the first time your site is visited. recycling the app pool will cause it to be triggered again</p> <p>In most situations, this <em>event handler has no code</em>, so don't waste time pursuing meaningless numbers!</p>
48,620
<p>We are changing some of the text for our old, badly written error messages. What are some resources for best practices on writing good error messages (specifically for Windows XP/Vista).</p>
<p>In terms of wording your error messages, I recommend referring to the following style guides for Windows applications:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" rel="nofollow noreferrer">Windows user experience guidelines</a>, and specifically the section on error messages <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dn742469.aspx" rel="nofollow noreferrer">here</a>.</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0735648719" rel="nofollow noreferrer" rel="nofollow noreferrer">Microsoft Manual of Style</a></li> </ul>
<p>Support for multilanguage applies for all kinds of messages, but tends to be forgotten in the case of error messages.</p>
14,263
<p>I'm writing by own blogging engine in PHP with a MYSQL backend database. MY question is: How would you go about making user comments and blog posts include newlines wherever they are appropriate?</p> <p>For example, if a user hits the return key in the message/comments box how would this translate into a new line that would show in the browser when the comment is viewed?</p>
<p>PHP has a function: nl2br which turns new lines into <code>&lt;br /&gt;</code></p> <p><a href="http://us2.php.net/nl2br" rel="nofollow noreferrer">www.php.net/nl2br</a></p>
<p>It's also important what your using for a comment editor. If your using a standard textbox then yes, nl2br is what your looking for. If your going a bit more advanced such as using a WYSIWYG editor like tinyMCE, then it has configuration that can handle that for you.</p>
15,072
<p>I´m using <code>Transaction Binding=Explicit Unbind</code> in the connection string as recommended <a href="http://weblogs.asp.net/ryangaraygay/archive/2008/04/14/issue-with-system-transactions-sqlconnection-and-timeout.aspx" rel="noreferrer">here</a> since I´m also using TransactionScope with timeout. The problem is that the connections does not seem to close after being disposed and eventually there are no more connections available in the connection pool. I got the same result when I modified the TransactionTimeoutIssueDemo (see the link) and ran TransactionScopeTest() (with the explicit unbind connection string) enough times in a loop to use up all available connections in the connection pool. Default value for connections in the pool is 100 but this can be changed by using the setting <code>Max Pool Size =10</code> for instance. It seems that the connections will not be released when using explicit unbind even though both the SqlConnection and the TransactionScope are used with the <code>using</code> clause. Anyone know how to handle this?</p>
<p>The connections only seem to stay in the pool and not being reused in case you get an exception, just like the example. If you increase the timeout the connection will be reused.</p> <p>A workaround to this problem is to clear the connection pool in case you get an exception like this:</p> <pre><code>using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); try { Console.WriteLine("Server is {0}", con.ServerVersion); Console.WriteLine("Clr is {0}", Environment.Version); for (int i = 0; i &lt; 5; i++) { using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "insert into TXTEST values ( " + i + " )"; cmd.ExecuteNonQuery(); } Console.WriteLine("Row inserted"); } Thread.Sleep(TimeSpan.FromSeconds(1)); } catch { SqlConnection.ClearPool(con); throw; } } </code></pre> <p>In most cases the transaction will complete within the timeout and everything will be fine and dandy. When the transaction <strong>actually do</strong> timeout you clear the pool in order to clean up the dirty connections that won't get reused. This will of course affect other connections in the pool that isn't affected by this problem.</p> <p>This is a ugly workaround but it seems to work.</p>
<p>For what it's worth, this issue was fixed in .Net 4.0.</p>
40,572
<p>I've got a generic&lt;> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?</p> <p>So equivalent to the sql: select *, 'bar' as Foo from items</p> <pre><code>foreach (var item in items) { var newItem = new { item, // I'd like just the properties here, not the 'item' object! Foo = "bar" }; newItems.Add(newItem); } </code></pre>
<p>There's no easy way of doing what you're suggesting, as all types in C# are strong-typed, even the anonymous ones like you're using. However it's not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It's possible to obtain a list of properties from your anonymous item using:</p> <pre><code>foreach(PropertyInfo info in item.GetType().GetProperties()) Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null)); </code></pre>
<pre><code>from item in items where someConditionOnItem select { propertyOne, propertyTwo }; </code></pre>
13,518
<p>From the Displays pane in System Preferences, I can manually change the main monitor by dragging the menu bar from one display to the other. I'd like to automate this and make it part of an AppleScript.</p>
<p>The tool I wrote, <a href="https://github.com/jakehilborn/displayplacer" rel="noreferrer">displayplacer</a>, does this.</p> <p>Configure your screens how you like, drag the "white bar" to your primary screen in the macOS system settings, and then execute <code>displayplacer list</code>. It will output the command to run to put your screens in their current configuration. The screen with <code>origin:(0,0)</code> is the main display with the "white bar". Run this terminal command through a script, Automator, BetterTouchTool, etc.</p> <p>Example profile 1 puts the white bar on the menu bar on the left monitor. <code>displayplacer "id:&lt;leftScreenId&gt; res:1920x1080 scaling:on origin:(0,0) degree:0" "id:&lt;rightScreenId&gt; res:1920x1080 scaling:on origin:(1920,0) degree:0"</code></p> <p>Example profile 1 puts the white bar on the menu bar on the right monitor. <code>displayplacer "id:&lt;leftScreenId&gt; res:1920x1080 scaling:on origin:(1920,0) degree:0" "id:&lt;rightScreenId&gt; res:1920x1080 scaling:on origin:(0,0) degree:0"</code></p> <p>Also available via Homebrew <code>brew tap jakehilborn/jakehilborn &amp;&amp; brew install displayplacer</code></p>
<p>Much like you can tell System Events.app to sleep your Mac, you can tell Image Events.app to mess with your displays. The Image Events application provides a "displays" collection. Each display has a "profile" with lots of goodies. However, everything I just mentioned is read-only, so I don't have a good way to do it from within script.</p> <p>You might have better luck in Automator – Hit record, run System Preferences, go to Displays, drag the menu bar to the other screen, and hit stop. I bet something will work.</p>
9,392
<p>I just recently upgraded my Printrbot Simple Metal with a heated bed (and longer x-axis). I looked up some tutorials, and all of them placed the thermistor as in the picture on the left below, so I did too. However, the design of the heat plate seems to strongly suggest thermistor placement as in the picture on the right, inside the small hole near the center.</p> <p><a href="https://i.stack.imgur.com/2nF92.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2nF92.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/tzmTq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tzmTq.png" alt="enter image description here"></a></p> <p>I can certainly see the upside of that. The reported temperature may overshoot the average bed temperature (the reasoning used in the tutorials I read), but most of my prints are built in the center of the bed, and the center placement would surely make the temperature control system more responsive.</p> <p>What are the pros and cons of these placements? And what would be the proper technique for putting the sensor in the center? Should I still use kapton tape? Do I need to make sure the thermistor makes physical contact with the aluminum of the print bed?</p>
<p>You are correct about the walls. Using a <em>Solidify</em> object modifier is probably your best bet. A low <em>Thickness:</em> value (<em>0.1</em> is probably good) helps keep the walls thin but strong. You can monitor the thickness while you adjust the value from <em>Wireframe</em> view.</p> <p><a href="https://i.stack.imgur.com/u4wif.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u4wif.png" alt="enter image description here"></a></p> <p>Additionally, and <strong>this is probably the most important thing to know</strong>, your mesh must be clean. By clean, I mean it must all be one piece. No separate cubes, cylinders, etc. that you added while modeling, just one solid piece. Think about it this way. If you have added a cube and part of that cube is inside the rest, it might look good from the outside. But the 3D Printer isn't printing the outside, it's printing everything. So that wall, albeit hidden, that is present on the inside of your mesh <strong>will be printed</strong>.</p> <p><em>Bad:</em></p> <p><a href="https://i.stack.imgur.com/de7eW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/de7eW.png" alt="enter image description here"></a></p> <p><em>Good:</em></p> <p><a href="https://i.stack.imgur.com/RQXI3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RQXI3.png" alt="enter image description here"></a></p> <p>Lastly, if you have parts of your mesh that can't be printed from the bottom up, or wouldn't stand by itself, consider adding supports. You can always cut these off later.</p> <p><em>Leg added because it wouldn't stand by itself:</em></p> <p><a href="https://i.stack.imgur.com/H1tqC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H1tqC.png" alt="enter image description here"></a></p>
<blockquote> <p>What are the things that i have to watch out for when 3d printing? </p> </blockquote> <p><a href="https://blender.stackexchange.com/q/7910/2816">non manifold geometry</a> : geometry that can not exist in the real world. </p> <p>It's a good idea to check if the dimensions of your mesh are correct before exporting: </p> <p><a href="https://i.stack.imgur.com/cfYiB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfYiB.png" alt="enter image description here"></a> <hr> Turning on mesh analysis allows visual inspection of problems such as intersecting faces, sharp edges ,edges with thickness below a threshold and other criterias.<br> <em>the inspection tool will color the faces with those problems.</em> </p> <p><a href="https://i.stack.imgur.com/BLGEK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BLGEK.png" alt="enter image description here"></a> <hr> And lastly you can make selections by traits, such as loose geometry, interior faces or unconnected vertices. </p> <p><a href="https://i.stack.imgur.com/phD8w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/phD8w.png" alt="enter image description here"></a></p> <p><em>note that those are just tools to help you find the problems , none of them will fix the mesh for 3d printing.</em> </p>
306
<p>I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive.</p> <p>The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times.</p> <p>The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer?</p> <p>The question is mainly about Linux, but any Win32 pointers will be more than welcome too.</p>
<p><code>man readom</code>, a program that comes with cdrecord:</p> <pre><code> -noerror Do not abort if the high level error checking in readom found an uncorrectable error in the data stream. -nocorr Switch the drive into a mode where it ignores read errors in data sectors that are a result of uncorrectable ECC/EDC errors before reading. If readom completes, the error recovery mode of the drive is switched back to the remembered old mode. ... retries=# Set the retry count for high level retries in readom to #. The default is to do 128 retries which may be too much if you like to read a CD with many unreadable sectors. </code></pre>
<p>dd(1) is your friend.</p> <p>dd if=/dev/cdrom of=image bs=2352 conv=noerror,notrunc</p> <p>The drive may still retry a bit, but I don't think you'll get any better without modifying firmware.</p>
17,969
<p>I'm trying to write a piece of code that will do the following:</p> <p>Take the numbers 0 to 9 and assign one or more letters to this number. For example:</p> <pre><code>0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, 8 = H or CH or J, 9 = G </code></pre> <p>When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility:</p> <p>NVL and NFL</p> <p>It should be obvious that this gets even &quot;worse&quot; with longer numbers that include several digits like 5,6 or 8.</p> <p>Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck.</p> <p>Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated.</p> <h3>Update:</h3> <p>Some more background: (and thanks a lot for the quick responses!)</p> <p>The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as &quot;pseudo-numerology&quot;.</p> <p>I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember.</p>
<p>It can be done easily recursively.</p> <p>The idea is that to handle the whole code of size n, you must handle first the n - 1 digits. Once you have all answers for n-1 digits, the answers for the whole are deduced by appending to them the correct(s) char(s) for the last one.</p>
<p>Could you do the following: Create a results array. Create an item in the array with value ""</p> <p>Loop through the numbers, say 051 analyzing each one individually.</p> <p>Each time a 1 to 1 match between a number is found add the correct value to all items in the results array. So "" becomes N.</p> <p>Each time a 1 to many match is found, add new rows to the results array with one option, and update the existing results with the other option. So N becomes NV and a new item is created NF</p> <p>Then the last number is a 1 to 1 match so the items in the results array become NVL and NFL</p> <p>To produce the results loop through the results array, printing them, or whatever.</p>
12,803
<p>What's the easiest way to remove last row from the text file using SQL Server Integration Services?</p> <p>Thanks.</p>
<p>Because SSIS is pipeline based, there's no good way to look ahead and know that a line is the last line.</p> <p>However, depending on your actual goal, there are a number of ways to achieve this:</p> <ul> <li>If the last row has some identifying information, it can simply be filtered out using the built-in filter component.</li> <li>You can create a custom component which does buffer the pipeline a little and leaves off the last row.</li> <li>You can add a row counter, output the file to a raw file and then read the raw file, excluding the last row using a filter</li> </ul>
<p>Cade has some excellent answers, but just to add another option, you may wish to preprocess the file in a more generaly language like PowerShell or Python to create a new version omitting the offending last line before bringing it in to SQL.</p>
24,549
<p>ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus. They do not, however, show their tooltips, unless the form is focused. I have seen the <a href="http://blogs.msdn.com/rickbrew/archive/2006/01/09/511003.aspx" rel="noreferrer">ToolStrip 'click-though' hack</a>. Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?</p> <p>Thanks!</p>
<p>The problem is that the ToolStrip "controls" like ToolStripButton or ToolStripDropDownButton don't inherit from Control. For now I addressed the problem by focusing the ToolStrip whenever a user hovers over a button. The button's MouseHover event is fired too late -- after the "show tooltip" code would have been run, so I extended the ToolStripDropDownButton class and used my new button. This method should work for any of the other button-like classes inheriting from ToolStripItem</p> <pre><code>public class ToolStripDropDownEx : ToolStripDropDownButton { public ToolStripDropDownEx(string text) { } protected override void OnMouseHover(EventArgs e) { if (this.Parent != null) Parent.Focus(); base.OnMouseHover(e); } } </code></pre>
<p>I was trying to do the same thing and determined it was going to be pretty challenging and not worth it. The reason is that internally, the .NET code is specifically designed to only show the tooltip if the window is active - they are checking this at a Win32 level so its going to be hard to fake the code out.</p> <p>Here is the code snippet in ToolTip.cs that checks "GetActiveWindow()" and returns false. You can see the comment in the code "ToolTips should be shown only on active Windows." </p> <p>By the way, you can see all the source code for the .NET BCL with Visual Studio 2008, here are the instructions I used:</p> <p><a href="http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx</a></p> <pre><code>// refer VsWhidbey 498263: ToolTips should be shown only on active Windows. private bool IsWindowActive(IWin32Window window) { Control windowControl = window as Control; // We want to enter in the IF block only if ShowParams does not return SW_SHOWNOACTIVATE. // for ToolStripDropDown ShowParams returns SW_SHOWNOACTIVATE, in which case we DONT want to check IsWindowActive and hence return true. if ((windowControl.ShowParams &amp; 0xF) != NativeMethods.SW_SHOWNOACTIVATE) { IntPtr hWnd = UnsafeNativeMethods.GetActiveWindow(); IntPtr rootHwnd =UnsafeNativeMethods.GetAncestor(new HandleRef(window, window.Handle), NativeMethods.GA_ROOT); if (hWnd != rootHwnd) { TipInfo tt = (TipInfo)tools[windowControl]; if (tt != null &amp;&amp; (tt.TipType &amp; TipInfo.Type.SemiAbsolute) != 0) { tools.Remove(windowControl); DestroyRegion(windowControl); } return false; } } return true; } </code></pre>
17,279
<p>I have a class and I want to be able to iterate over a certain array member. I did a quick search and found <code>IteratorAggregate</code>:</p> <pre><code>class foo implements IteratorAggregate { protected $_array = array('foo'=&gt;'bar', 'baz'=&gt;'quux'); public function getIterator() { return new ArrayIterator($this-&gt;_array); } } </code></pre> <p>which works great, but doesn't that create a new <code>ArrayIterator</code> instance every time <code>foreach</code> is used on it?</p> <p>So I thought I should store the iterator instance in a member:</p> <pre><code> protected $_iterator; public function getIterator() { if (!$this-&gt;_iterator instanceof ArrayIterator) { $this-&gt;_iterator = new ArrayIterator($this-&gt;_array); } return $this-&gt;_iterator; } </code></pre> <p>The problem is that the iterator uses a copy of <code>$this->_array</code> during the first call of <code>getIterator()</code>, so changes to the member aren't reflected on subsequent <code>foreach</code> constructs.</p> <p>I was thinking I should subclass <code>ArrayIterator</code>, add a <code>setArray($array)</code> method and call it before returning it in <code>getIterator()</code>, but I don't know the member name of the array it uses internally and whether or not it's overwriteable by a subclass.</p> <p>The question is: is this a premature and/or unnecessary optimization? If no, what's the best way to achieve this?</p>
<p>I don't think you do want to use MAX() as you don't want to group the OrderID. What you need is an ordered sub query with a SELECT TOP 1.</p> <pre><code>select * from Customers inner join Orders on Customers.CustomerID = Orders.CustomerID and OrderID = ( SELECT TOP 1 subOrders.OrderID FROM Orders subOrders WHERE subOrders.CustomerID = Orders.CustomerID ORDER BY subOrders.OrderDate DESC ) </code></pre>
<p>Something like:</p> <pre><code>SELECT a.* FROM Customer a INNER JOIN Order b ON a.OrderID = b.Id INNER JOIN (SELECT Id, max(EntryTime) as EntryTime FROM Order b GROUP BY Id) met ON b.EntryTime = met.EntryTime and b.Id = met.Id </code></pre>
42,932
<p>For some reason, I can't seem to get CruiseControl.net to checkout code to anywhere but the starteam working folder for a specificed view.</p> <p>I've tried both overrideViewWorkingDir and overrideFolderWorkingDir, and neither seem to work.</p> <p>Has anyone been able to do this?</p>
<p>Are you looking for the project's <a href="http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block" rel="nofollow noreferrer">workingDirectory element</a> instead of the <a href="http://confluence.public.thoughtworks.org/display/CCNET/StarTeam+Source+Control+Block" rel="nofollow noreferrer">starteam override</a>?</p>
<pre><code>&lt;sourcecontrol type="starteam"&gt; &lt;executable&gt;C:\Program Files\starbase\StarTeam 5.4\stcmd.exe&lt;/executable&gt; &lt;project&gt;ProjectName/ViewName&lt;/project&gt; &lt;username&gt;UserName&lt;/username&gt; &lt;password&gt;Password&lt;/password&gt; &lt;host&gt;127.0.0.1&lt;/host&gt; &lt;port&gt;49201&lt;/port&gt; &lt;autoGetSource&gt;true&lt;/autoGetSource&gt; &lt;overrideViewWorkingDir&gt;C:\temp\ProjectName&lt;/overrideViewWorkingDir&gt; &lt;/sourcecontrol&gt; </code></pre>
6,428
<p>My colleague here argues that new programmers must learn ASP first, before they learn ASP.Net. </p> <p>I seem to agree with him as most new programmers who start with ASP.Net do not understand web get, post and state management :(</p> <p>Which is best to learn web programming Classic ASP or ASP.Net?</p>
<p>I'd pick ASP.NET MVC over classic ASP. The problem with classic ASP is the support level for it. With MVC, you learn both about web get/post and state management, while at the same time getting the advantage of using your favorite OO language.</p>
<p>I would recommend just going with ASP.Net. ASP is so old a technology that they will have to learn so many work arounds to things that are common place.</p> <p>I would also go with straight ASP.Net over MVC as the jury is still out (for me anyway) on how valuable MVC really is. It takes a lot of control away from the developer.</p>
44,115
<p>Is there a way to read the properties inside an <a href="https://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow noreferrer">MSI</a> file?</p> <p>For example, given a MSI file named <em>Testpackage.msi</em>, I need to find</p> <pre><code>productName PackageCode version </code></pre> <p>This I am going to use it with WMI uninstall</p> <pre><code>string objPath = string.Format(&quot;Win32_Product.IdentifyingNumber='{0}', Name='{1}', Version='{2}'&quot;, &quot;{AC9C1263-2BA8-4863-BE18-01232375CE42}&quot;, &quot;testproduct&quot;, &quot;10.0.0.0&quot;); </code></pre> <p>Using <a href="http://msdn.microsoft.com/en-us/library/aa370557(v=vs.85).aspx" rel="nofollow noreferrer">Orca</a> is a great option, if this can be achieved programmatically. Then I can use this to generate automatic release notes. And in un-installing program too.</p>
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/aa367810(VS.85).aspx" rel="nofollow noreferrer">COM-based API for working with MSI</a>, and do something like</p> <pre class="lang-vb prettyprint-override"><code>Function GetVersion(ByVal msiName) Const msiOpenDatabaseModeReadOnly = 0 Dim msi, db, view Set msi = CreateObject("WindowsInstaller.Installer") Set db = msi.OpenDataBase(msiName, msiOpenDatabaseModeReadOnly) Set view = db.OpenView("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'") Call view.Execute() GetVersion = view.Fetch().StringData(1) End Function </code></pre>
<p>I found a lightweight non-programmatic solution in <a href="http://code.google.com/p/lessmsi/" rel="nofollow">lessmsi</a>. It apparently uses wix and just explodes the whole .msi into a specified folder. (It also has a UI but it didn't render great for me on Win7).</p>
38,273
<p>I have a project that utilizes the javax.mail.internet.MimeMessage and other related classes that does mime parsing for emails that we receive. This needs to be ported to .NET.</p> <p>What .Net 3rd party or built in library can I use to replace the Java classes that I'm using?</p> <p>EDIT: Anything change in the last 9 months since I asked this question?</p>
<p>I've recently released <a href="https://github.com/jstedfast/MimeKit">MimeKit</a> which is far more robust than any of the other open source .NET MIME parser libraries out there and it's orders of magnitude faster as well due to the fact that it is an actual stream parser and not a recursive descent string parser (which also has the added benefit of it using a LOT less memory).</p> <p>It has full support for S/MIME v3.2 (including compression, which none of the other libraries that claim "full" support actually support) and OpenPGP.</p> <p>For SMTP, POP3, and IMAP you can use my <a href="https://github.com/jstedfast/MailKit">MailKit</a> library which supports a bunch of SASL authentication mechanisms including XOAUTH2 (used by Google). The SMTP client supports PIPELINING which can improve performance of sending mail and the IMAP client supports a growing number of extensions that allow clients to optimize their bandwidth as well.</p>
<p>Try using <a href="http://www.limilabs.com/mail/" rel="nofollow noreferrer">Mail.dll IMAP component</a>, it's on the market for quite a while, and is well tested.</p> <pre><code>using(Imap imap = new Imap()) { imap.Connect("imapServer"); imap.UseBestLogin("user", "password"); imap.SelectInbox(); List&lt;long&gt; uids = imap.SearchFlag(Flag.Unseen); foreach (long uid in uids) { byte[] eml = imap.GetMessageByUID(uid); IMail message = new MailBuilder() .CreateFromEml(eml); Console.WriteLine(message.Subject); } imap.Close(); } </code></pre> <p>Please note that Mail.dll is a commercial product that I've created.</p> <p>You can download it here: <a href="http://www.limilabs.com/mail/" rel="nofollow noreferrer">http://www.limilabs.com/mail</a>.</p>
3,958
<p>I have a <code>DataTable</code> with a <code>Name</code> column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the <em>order by</em> clause.</p> <pre><code>var names = (from DataRow dr in dataTable.Rows orderby (string)dr["Name"] select (string)dr["Name"]).Distinct(); </code></pre> <p>Why does the <code>orderby</code> not get enforced?</p>
<p><strong>The problem is that the Distinct operator does not grant that it will maintain the original order of values.</strong></p> <p>So your query will need to work like this</p> <pre><code>var names = (from DataRow dr in dataTable.Rows select (string)dr["Name"]).Distinct().OrderBy( name =&gt; name ); </code></pre>
<p>Try the following</p> <pre><code>var names = (from dr in dataTable.Rows select (string)dr["Name"]).Distinct().OrderBy(name =&gt; name); </code></pre> <p>this should work for what you need.</p>
2,246