instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>How can I make this java generic cast ?</p> <pre><code>public interface IField { } class Field implements IField { // package private class } public class Form { private List&lt;Field&gt; fields; public List&lt;IField&gt; getFields() { return this.fields; } } </code></pre> <p>The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code.</p> <p>If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class .</p> <p>Can I force that damn compiler to bend it's rules and compile that return statement ?</p> <p>Thanks in advance.</p>
<p>A better solution, IMO, is to change the signature of your method to use a bounded wildcard:</p> <pre><code>public List&lt;? extends IField&gt; getFields() </code></pre> <p>This will let the caller treat anything coming "out" of the list as an IField, but it won't let the caller add anything into the list (without casting or warnings), as they don't know what the "real" type of the list is.</p>
<p>Sunlight is right, you can just cast it.</p> <p>Another fix is to double-check that you really need a <code>List&lt;Field&gt;</code>, or whether you can change your internal <code>fields</code> variable to <code>List&lt;IField&gt;</code>.</p> <p>As long as you only ever use methods on the contents of the list that are on the <code>IField</code> interface, you should be able to do a strightforward swap.</p>
40,512
<p>I have a string of test like this:</p> <pre><code>&lt;customtag&gt;hey&lt;/customtag&gt; </code></pre> <p>I want to use a RegEx to modify the text between the "customtag" tags so that it might look like this:</p> <pre><code>&lt;customtag&gt;hey, this is changed!&lt;/customtag&gt; </code></pre> <p>I know that I can use a MatchEvaluator to modify the text, but I'm unsure of the proper RegEx syntax to use. Any help would be much appreciated.</p>
<p>I wouldn't use regex either for this, but if you must this expression should work: <code>&lt;customtag&gt;(.+?)&lt;/customtag&gt;</code></p>
<pre><code>//This is to replace all HTML Text var re = new RegExp("&lt;[^&gt;]*&gt;", "g"); var x2 = Content.replace(re,""); //This is to replace all &amp;nbsp; var x3 = x2.replace(/\u00a0/g,''); </code></pre>
38,442
<p>My G29 command reports</p> <pre><code>+0.178 +0.281 +0.830 -0.614 -0.012 +0.371 -1.208 -0.849 -0.351 </code></pre> <p>So should I tighten up the screw of the bed, close to 0,0 position or loosen it?</p> <p>I have a feeling that when I loosen it, it gets away from zero and I expect the opposite to happen.</p> <p>For bed leveling i use a capacitive probe and after playing around with the screws here is the result</p> <pre><code>+0.406 +0.127 +0.411 -0.161 -0.007 -0.041 -0.572 -0.652 -0.668 </code></pre> <p>Finally the leveling process was found <a href="https://www.youtube.com/watch?v=y_1Kg45APko" rel="nofollow noreferrer">here</a> But the question remains. The value <code>-0.572</code> corresponds close to <code>0,0</code> ?</p>
<p>Using Repetier Host V2.1.2 and slicing with Slic3r (or with CuraEngine), there is an "edit Gcode" button under the Print Preview tab. It is located at the top right of the screen. With that button you can access, examine and change the Gcode of the project you are working on.</p>
<p>After you use the Slice Now button (and the slicing progress bar shows completed), select the preview tab. To the right of the window you will see a pair of vertical sliders. Each slider changes the start and finish locations for the filament layers.</p> <p>You can slide the left one to the bottom, which will "empty" the virtual print bed. Each movement upward will display a succeeding layer, showing the placement of the filament. This ostensibly will present to you alignment information as well as unexpected holes or other failure points.</p> <p>I don't know of any slicer that lacks a preview. That doesn't mean one does not exist, but why would such a useful feature be omitted?</p>
944
<p>I've been playing with RSS feeds this week, and for my next trick I want to build one for our internal application log. We have a centralized database table that our myriad batch and intranet apps use for posting log messages. I want to create an RSS feed off of this table, but I'm not sure how to handle the volume- there could be hundreds of entries per day even on a normal day. An exceptional make-you-want-to-quit kind of day might see a few thousand. Any thoughts?</p>
<p>If you are building a system with notifications that must not be missed, then a pub-sub mechanism (using XMPP, one of the other protocols supported by ApacheMQ, or something similar) will be more suitable that a syndication mechanism. You need some measure of coupling between the system that is generating the notifications and ones that are consuming them, to ensure that consumers don't miss notifications.</p> <p>(You can do this using RSS or Atom as a transport format, but it's probably not a common use case; you'd need to vary the notifications shown based on the consumer and which notifications it has previously seen.)</p>
<p>Without knowing your application, I can't offer specific advice. </p> <p>That said, it's common in these sorts of systems to have a level of severity. You could have a query string parameter that you tack on to the end of the URL that specifies the severity. If set to "DEBUG" you would see every event, no matter how trivial. If you set it to "FATAL" you'd only see the events that that were "System Failure" in magnitude. </p> <p>If there are still too many events, you may want to sub-divide your events in to some sort of category system. Again, I would have this as a query string parameter. </p> <p>You can then have multiple RSS feeds for the various categories and severities. This should allow you to tune the level of alerts you get an acceptable level. </p>
8,478
<p>[EDIT]In Short: How would you write an automatic spell checker? The idea is that the checker builds a list of words from a known good source (a dictionary) and automatically adds new words when they are used often enough. Words which haven't been used a while should be phased out. So if I delete part of a scene which contains "Mungrohyperiofier", the checker should remember it for a while and when I type "Mung&lt;Ctrl+Space&gt;" in another scene, it should offer it again. If I don't use the word for, say, a few days, it should forget about it.</p> <p>At the same time, I'd like to avoid adding typos to the dictionary.[/EDIT]</p> <p>I want to write a text editor for SciFi stories. The editor should offer word completion for any word used anywhere in the current story. It will only offer a single scene of the story for editing (so you can easily move scenes around).</p> <p>This means I have three sets:</p> <ol> <li>The set of all words in all other scenes</li> <li>The set of word in the current scene <em>before</em> I started editing it</li> <li>The set of words in the current editor</li> </ol> <p>I need to store the sets somewhere as it would be too expensive to build the list from scratch every time. I think a simple plain text file with one-word-per-line is enough for that.</p> <p>As the user edits the scene, we have these situations:</p> <ol> <li>She deletes a word. This word is not used anywhere else in the current scene.</li> <li>She types a word which is new</li> <li>She types a word which already exists</li> <li>She types a word which already exists but makes a typo</li> <li>She corrects a typo in a word which is in set #2.</li> <li>She corrects a typo in a word which is in set #1 (i.e. the typo is elsewhere, too).</li> <li>She deletes a word which she plans to use again. After the deletion, the word is no longer in the sets #1 and #3, though.</li> </ol> <p>The obvious strategy would be to rebuilt the word sets when a scene is saved and build the set #1 from a word-list file per scene.</p> <p>So my question is: Is there a clever strategy to keep words which aren't used anywhere anymore but still be able to phase out typos? If possible, this strategy should work in the background without the user even noticing what is going on (i.e. I want to avoid to have to grab the mouse to select "add word to dictionary" from the menu).</p> <p>[EDIT] Based on a comment from <a href="https://stackoverflow.com/users/34329/grieve">grieve</a></p>
<p>So you want to write a spelling checker. Here's <a href="http://norvig.com/spell-correct.html" rel="nofollow noreferrer">Peter Norvig's paper about writing a spelling corrector</a>. It describes a simple and robust spelling corrector. You can use the already-written part of the book, plus a reference list (say from a free dictionary) for the language model. I would also go to existing open-source spelling checkers, such as <a href="http://aspell.net/" rel="nofollow noreferrer">aspell</a> and <a href="http://hunspell.sourceforge.net/" rel="nofollow noreferrer">hunspell</a>, to get some ideas.</p>
<p>The structure you should use is a trie. Tail/suffix compression will help with memory. You can use a pseudo reference counting GC for keeping track of usage.</p> <p>For the actual nodes, you would probably need no more than a 32-bit integer, 21-bits for unicode, and the rest for various other tags and information.</p>
43,365
<p>As far as I can tell there's no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset into the text within that node. IE seems to just have pixel offsets. There are methods to create, extend and compare ranges, so it would be possible to write an algorithm to calculate the character offset, but I feel I must be missing something.</p> <p>So, what's the easiest way to calculate the character offset of the start of an Internet Explorer TextRange?</p>
<p>I'd suggest <a href="http://code.google.com/p/ierange/" rel="nofollow noreferrer">IERange</a>, or just the <code>TextRange</code>-to-<code>DOM Range</code> algorithm from it.</p> <h2>Update, 9 August 2011</h2> <p>I'd now suggest using my own <a href="http://code.google.com/p/rangy" rel="nofollow noreferrer">Rangy</a> library, which is similar in idea to IERange but much more fully realized and supported.</p>
<p>You can iterate through the body element's <code>TextRange.text</code> property using <code>String.substring()</code> to compare against the TextRange for which you want the character offset.</p> <pre><code>function charOffset(textRange, parentTextRange) { var parentTxt = parentTextRange.text; var txt = textRange.text; var parentLen = parentTxt.length; for(int i=0; i &lt; parentLen ; ++i) { if (parentTxt.substring(i, txt.length+i) == txt) { var originalPosition = textRange.getBookmark(); //moves back one and searches backwards for same text textRange.moveStart("character",-1); var foundOther = textRange.findText(textRange.text,-parentLen,1); //if no others were found return offset if (!foundOther) return i; //returns to original position to try next offset else textRange.moveToBookmark(originalPosition); } } return -1; } </code></pre> <p>[<a href="http://msdn.microsoft.com/en-us/library/ms536422(VS.85).aspx" rel="nofollow noreferrer">Reference for <code>findText()</code></a>]</p>
19,842
<p>The problem is you can't tell the user how many characters are allowed in the field because the escaped value has more characters than the unescaped one.</p> <p>I see a few solutions, but none looks very good:</p> <ul> <li>One whitelist for each field <em>(too much work and doesn't quite solve the problem)</em></li> <li>One blacklist for each field <em>(same as above)</em></li> <li>Use a field length that could hold the data even if all characters are escaped <em>(bad)</em></li> <li>Uncap the size for the database field <em>(worse)</em></li> <li>Save the data hex-unescaped and pass the responsibility entirely to output filtering <em>(not very good)</em></li> <li>Let the user guess the maximum size <em>(worst)</em></li> </ul> <p>Are there other options? Is there a "best practice" for this case?</p> <p>Sample code:</p> <pre><code>$string = 'javascript:alert("hello!");'; echo strlen($string); // outputs 27 $escaped_string = filter_var('javascript:alert("hello!");', FILTER_SANITIZE_ENCODED); echo strlen($escaped_string); // outputs 41 </code></pre> <p>If the length of the database field is, say, 40, the escaped data will not fit.</p>
<p>Don't build your application around the database - build the database for the application!</p> <p>Design how you want the interface to work for the user first, work out the longest acceptable field length, and use that.</p> <p>In general, don't escape before storing in the database - store raw data in the database and format it for display. If something is going to be output many times, then store the processed version.</p> <p>Remember disk space is relatively cheap - don't waste effort trying to make your database compact.</p>
<p>This is an interesting problem.</p> <p>I think the solution will be a problem if you assign any responsibility to them because of the sanitization. If they are responsible for guessing the maximum length, then they may well give up and pick something else (and not understand why their input was invalid).</p> <p>Here's my idea: make the database field 150% the size of the input. This extra size serves as "padding" for the space of the hex-sanitization, and the maximum size shown to the user and validator is the actual desired size. Thus if you check the input length before sanitization and it is below that 66% limit on the length your sanitized data <em>should</em> be good to go. If they exceed that extra 34% field space for the buffer, then the input probably should not be accepted.</p> <p>The only trouble is that your database tables will be larger. If you want to avoid this, well, you could always escape only the SQL sensitive characters and handle everything else on output.</p> <p><strong>Edit:</strong> Given your example, I think you're escaping far too much. Either use a smaller range of sanitization with <code>HTMLSpecialChars()</code> on output, or make your database fields as much as 200% of their present size. That's just bloated if you ask me.</p>
20,570
<p>I'm not sure why the TSpeedButton has this property but when a TSpeedButton is the only button of a given groupindex, it doesn't stay pressed, whether or not "AllowAllUp" is pressed. Maybe a Jedi control would suffice, but hopefully there's some fix. Any help or anecdotes are appreciated.</p> <p>BTW, I'm (still) using Delphi 7, not sure if this is an across the board conundrum.</p>
<p>I have no D7 here, but in D2006 a Speedbutton stays down if the GroupIndex has a value > 0.</p> <p>If this is not the behaviour you wish, you can set the Down-Property manually in the OnClick-Eventhandler (make sure, that the GroupIndex is 0).</p>
<p>I was searching for a solution for my problem and I think this is kind of the same one. I wanted to make a SpeedButton toggle the up and down state just like a switch, and I managed this by setting the properties: </p> <pre><code>AllowAllUp := True; GroupIndex := 1; </code></pre> <p>Then in the <code>OnClick</code> event of the button I wrote:</p> <pre><code>procedure TForm1.SpeedButton1Click(Sender: TObject); begin if( SpeedButton1.AllowAllUp ) then begin SpeedButton1.AllowAllUp := False; SpeedButton1.Down := True; end else begin SpeedButton1.AllowAllUp := True; SpeedButton1.Down := False; end; end; </code></pre> <p>This toggles the button down when it's clicked and up when it's clicked again.</p> <p>Hope it'll be of any help</p>
24,792
<p>I have a "Status" class in C#, used like this:</p> <pre><code>Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } </code></pre> <p>You get the idea. All callers of MyFunction <em>should</em> check the returned Status:</p> <pre><code>Status myStatus = MyFunction(); if ( ! myStatus.IsOK() ) // handle it, show a message,... </code></pre> <p>Lazy callers however can ignore the Status.</p> <pre><code>MyFunction(); // call function and ignore returned Status </code></pre> <p>or </p> <pre><code>{ Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it </code></pre> <p>Is it possible to make this impossible? e.g. an throw exception</p> <p><strong>In general</strong>: is it possible to write a C# class on which you <em>have</em> to call a certain function?</p> <p>In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the <em>destructor</em> and ring some bells when someone doesn't check this instance.</p> <p>What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class"</p> <p>Is the Dispose method of the IDisposable interface an option?</p> <p>In this case there are no unmanaged resources to free. Additionally, it is not determined <em>when</em> the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not <em>required</em> for lazy callers.</p>
<p>I know this doesn't answer your question directly, but if "something went wrong" within your function (unexpected circumstances) I think you should be throwing an exception rather than using status return codes.</p> <p>Then leave it up to the caller to catch and handle this exception if it can, or allow it to propogate if the caller is unable to handle the situation.</p> <p>The exception thrown could be of a custom type if this is appropriate.</p> <p>For <em>expected</em> alternative results, I agree with @Jon Limjap's suggestion. I'm fond of a bool return type and prefixing the method name with "Try", a la:</p> <pre><code>bool TryMyFunction(out Status status) { } </code></pre>
<p>You can throw an exception by:</p> <pre><code>throw MyException; [global::System.Serializable] public class MyException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public MyException () { } public MyException ( string message ) : base( message ) { } public MyException ( string message, Exception inner ) : base( message, inner ) { } protected MyException ( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context ) : base( info, context ) { } } </code></pre> <p>The above exception is fully customizable to your requirements.</p> <p>One thing I would say is this, I would leave it to the caller to check the return code, it is their responsability you just provide the means and interface. Also, It is a lot more efficient to use return codes and check the status with an if statement rather than trhowing exceptions. If it really is an <em>Exceptional</em> circumstance, then by all means throw away... but say if you failed to open a device, then it might be more prudent to stick with the return code.</p>
4,001
<p>I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.</p> <p>How do you create a admin_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?</p> <p>The show, edit and index of the original resource are not usuable for the administrator.</p>
<p>I think namespaces is the solution to the problem you have here:</p> <pre><code>map.namespace :admin do |admin| admin.resources :customers end </code></pre> <p>Which will create routes <code>admin_customers</code>, <code>new_admin_customers</code>, etc.</p> <p>Then inside the <code>app/controller</code> directory you can have an <code>admin</code> directory. Inside your admin directory, create an admin controller:</p> <pre><code>./script/generate rspec_controller admin/admin class Admin::AdminController &lt; ApplicationController layout "admin" before_filter :login_required end </code></pre> <p>Then create an admin customers controller:</p> <pre><code>./script/generate rspec_controller admin/customers </code></pre> <p>And make this inhert from your ApplicationController:</p> <pre><code>class Admin::CustomersController &lt; Admin::AdminController </code></pre> <p>This will look for views in <code>app/views/admin/customers</code> and will expect a layout in <code>app/views/layouts/admin.html.erb</code>.</p> <p>You can then use whichever plugin or code you like to actually do your administration, streamline, ActiveScaffold, whatever personally I like to use <code>resourcecs_controller</code>, as it saves you a lot of time if you use a <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="nofollow noreferrer">REST</a> style architecture, and forcing yourself down that route can save a lot of time elsewhere. Though if you inherited the application that's a moot point by now.</p>
<p>Use <a href="https://github.com/sferik/rails_admin" rel="nofollow">https://github.com/sferik/rails_admin</a>.</p>
13,309
<p>Difficult question. The answer is probably no, if all I found in the Intertubes is right, but it is worth a try. I need to override the <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Esc</kbd> and the <kbd>Ctrl</kbd> + <kbd>Esc</kbd> combinations. It would be good to be able to override the <kbd>Win</kbd> key combinations, but I have a low level hook that does such, I only wish I didn't need it. If I can manage to block the start menu and the task manager entirely by policy, the overrides will no longer be needed but I couldn't find the correct policy to do so.</p>
<p>You can override <kbd>Ctrl</kbd> + <kbd>Esc</kbd> (I just tried in AutoHotkey, it works), but not <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Esc</kbd>, no more than <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Del</kbd>.</p> <p>So using policies is probably the way to go... No experience in this field, I fear.</p>
<p>So you need do override Hotkeys on your application? Then the answer is probably yes, how? No idea, but if this(<a href="http://www.inchwest.com/mapkeyboard.aspx" rel="nofollow noreferrer">http://www.inchwest.com/mapkeyboard.aspx</a>) program can, so can you </p>
23,412
<p>I have a table cell, and I want a div within it to always be at the bottom left corner. The following works fine in IE and Safari, but Firefox is positioning the <code>div</code> absolutely on the page, not within the cell (code based on the solution solution <a href="https://stackoverflow.com/questions/104953/position-an-html-element-relative-to-its-container-using-css">here</a>). I have tested both with and without the DTD, which put Firefox in Quirks mode and Standards mode, and neither worked properly. I'm stuck - any ideas?</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;style type="text/css"&gt; table { width:500px; } th, td { vertical-align: top; border:1px solid black; position:relative; } th { width:100px; } .manage { text-align:right; position:absolute; bottom:0; right:0; } &lt;/style&gt; &lt;/head&gt; &lt;body &gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Some info about the following thing and this is actually going to span a few lines&lt;/th&gt; &lt;td&gt;&lt;p&gt;A short blurb&lt;/p&gt;&lt;div class="manage"&gt;Edit | Delete&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Some info about the following thing and this is actually going to span a few lines&lt;/th&gt; &lt;td&gt;&lt;p&gt;A short blurb&lt;/p&gt;&lt;div class="manage"&gt;Edit | Delete&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>According to the <a href="http://www.w3.org/TR/CSS21/visuren.html#propdef-position" rel="noreferrer">W3C</a>, position:relative has no effect on table cells:</p> <blockquote> <p>"The effect of 'position:relative' on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined."</p> </blockquote> <p>The solution is to add an extra wrapping div to the table cell. </p> <p><strong>EDIT:</strong> This div requires a <code>height:100%</code> and <code>position:relative;</code> to be set.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div style="position:relative;height:100%;"&gt; Normal inline content. &lt;div class="manage"&gt;your absolute-positioned content&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
<p><code>position: relative</code> is apparently not globally supported for the <code>td</code> tag. I couldn't find definitive sources unfortunately.</p> <p>You might want to put a <code>div</code> block into the <code>td</code> with the desired size and apply <code>position: relative</code> to that instead.</p>
37,008
<p>As per c99 standard, size of <code>long long</code> should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 <code>long long</code>s). Also, What is the equivalent of <code>long long</code> in C++.</p>
<p>On the IA32 architecture, 64-bit integer are implemented in using two 32-bit registers (eax and edx).</p> <p>There are platform specific equivalents for C++, and you can use the stdint.h header where available (boost provides you with <a href="http://www.boost.org/doc/libs/1_37_0/boost/cstdint.hpp" rel="noreferrer">one</a>).</p>
<p>If you care about bit-sizes, you should use</p> <pre><code>#include &lt;stdint.h&gt; int32_t n; </code></pre> <p>and friends. This works for C++ as well.</p> <p>64-bit numbers on 32-bit machines are implemented as you think, by 4 extra bytes. You could therefore implement your own 64-bit datatype by doing something like this:</p> <pre><code>struct my_64bit_integer { uint32_t low; uint32_t high; }; </code></pre> <p>You would of course have to implement mathematical operators yourself.</p> <p>There is an int64_t in the stdint.h that comes with my GCC version, and in Microsoft Visual C++ you have an __int64 type as well.</p>
42,796
<p>I am inside of...</p> <pre><code>public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { Some code... </code></pre> <p>and after "some code" I want to trigger</p> <pre><code>[WebMethod] public static void DoSome() { } </code></pre> <p>Which triggers some javascript. Is this possible?</p> <p>Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried:</p> <pre><code>public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { ...my C# code to perform on dropdown selection... //now I want to trigger some javascript... // Define the name and type of the client scripts on the page. String csname1 = "PopupScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname1)) { String cstext1 = "alert('Hello World');"; cs.RegisterStartupScript(cstype, csname1, cstext1, true); } } </code></pre> <p>}</p> <p>I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.</p>
<p>I'm not sure I fully understand the sequence of what you are trying to do, what's client-side and what's not....</p> <p>However, you could add a Start-up javascript method to the page which would then call the WebMethod. When calling a WebMethod via javascript, you can add a call-back function, which would then be called when the WebMethod returns.</p> <p>If you add a ScriptManager tag on your page, you can call WebMethods defined in the page via Javascript. </p> <pre><code>&lt;asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true" /&gt; </code></pre> <p>From the Page_Load function you can add a call to your WebMethod..</p> <pre><code>Page.ClientScript.RegisterStartupScript( this.GetType(), "callDoSome", "PageMethods.DoSome(Callback_Function, null)", true); </code></pre> <p>Callback_Function represents a javascript function that will be executed after the WebMethod is called... </p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; function Callback_Function(result, context) { alert('WebMethod was called'); } &lt;/script&gt; </code></pre> <p><b>EDIT:</b></p> <p>Found this link for <a href="http://edndoc.esri.com/arcobjects/9.2/NET_Server_Doc/developer/ADF/custom_tools_commands.htm" rel="nofollow noreferrer">Web ADF controls</a>. Is this what you are using??</p> <p>From that page, it looks like something like this will do a javascript callback.</p> <pre><code>public void ServerAction(ToolbarItemInfo info) { string jsfunction = "alert('Hello');"; Map mapctrl = (Map)info.BuddyControls[0]; CallbackResult cr = new CallbackResult(null, null, "javascript", jsfunction); mapctrl.CallbackResults.Add(cr); } </code></pre>
<p>hmmm... the question changed dramatically since my original answer.</p> <p>Now I think the answer is no. But I might be wrong.</p>
18,571
<p>I knew of some performance reasons back in the SQL 7 days, but do the same issues still exist in SQL Server 2005? If I have a resultset in a stored procedure that I want to act upon individually, are cursors still a bad choice? If so, why?</p>
<p>Because cursors take up memory and create locks.</p> <p>What you are really doing is attempting to force set-based technology into non-set based functionality. And, in all fairness, I should point out that cursors <em>do</em> have a use, but they are frowned upon because many folks who are not used to using set-based solutions use cursors instead of figuring out the set-based solution.</p> <p>But, when you open a cursor, you are basically loading those rows into memory and locking them, creating potential blocks. Then, as you cycle through the cursor, you are making changes to other tables and still keeping all of the memory and locks of the cursor open.</p> <p>All of which has the potential to cause performance issues for other users.</p> <p>So, as a general rule, cursors are frowned upon. Especially if that's the first solution arrived at in solving a problem.</p>
<p>The basic issue, I think, is that databases are designed and tuned for set-based operations -- selects, updates, and deletes of large amounts of data in a single quick step based on relations in the data.</p> <p>In-memory software, on the other hand, is designed for individual operations, so looping over a set of data and potentially performing different operations on each item serially is what it is best at.</p> <p>Looping is not what the database or storage architecture are designed for, and even in SQL Server 2005, you are not going to get performance anywhere close to you get if you pull the basic data set out into a custom program and do the looping in memory, using data objects/structures that are as lightweight as possible.</p>
8,255
<p>Is there a way to take a class name and convert it to a string in C#? </p> <p>As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.</p> <p>Thus, is there a way that I could do this:</p> <pre><code>class Foo { } tblBar.Include ( Foo.GetType().ToString() ); </code></pre> <p>I don't think I can do GetType() without an instance. Any ideas?</p>
<p>You can't use <code>.GetType()</code> without an instance because <code>GetType</code> is a method.</p> <p>You can get the name from the type though like this:</p> <pre><code>typeof(Foo).Name </code></pre> <p>And as pointed out by Chris, if you need the assembly qualified name you can use</p> <pre><code>typeof(Foo).AssemblyQualifiedName </code></pre>
<p>You can use an <code>DbSet&lt;contact&gt;</code> instead of <code>ObjectSet&lt;contact&gt;</code>, so you can use lambda as a parameter, eg <code>tblBar.Include(a =&gt; a.foo)</code></p>
21,676
<p>I am attempting to build a simple method that creates an XML file from a database in ruby on rails. I feel like my code is right but I am not seeing all of the users in the XML.<br> I am a complete newbie to RoR.</p> <p>Here's my code:</p> <pre><code>def create_file @users = User.find(:all) file = File.new('dir.xml','w') doc = Document.new make = Element.new "make" @users.each do |y| make.add_element "name" make.elements["name"].text = y.name make.add_element "description" make.elements["description"].text = y.description end doc.add_element make file.puts doc file.close end </code></pre> <p>And my XML output:</p> <pre><code>&lt;make&gt; &lt;name&gt;sammy&lt;/name&gt;&lt;description&gt;samsdescription&lt;/description&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;/make&gt; </code></pre> <p>I don't get why all the fields aren't populated. Why is just one of the database entires showing up? I really appreciate the help.</p>
<p>There's a bug in your code. In each iteration you create an element with <a href="http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Element.html#M003015" rel="nofollow noreferrer"><code>add_element</code></a> and then try to access that element with <a href="http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Elements.html#M002900" rel="nofollow noreferrer"><code>Elements#[]</code></a>. But when you use a node name in <code>Elements#[]</code> it returns only the first matching node. So you are creating a node in every iteration but updating only the first one. Try to change the code to the following:</p> <pre><code>@users.each do |y| name_node = make.add_element "name" name_node.text = y.name desc_node = make.add_element "description" desc_node.text = y.description end </code></pre> <p>By the way, your XML structure is a bit strange. Wouldn't it be more clear if you wrapped every name/description pair inside another node (say, <em>user</em>) and then have many <em>user</em> nodes?</p>
<p>You ought to investigate <code>@users.to_xml</code> to see if it is something you could use instead of rolling your own solution. Read more about it in the <a href="http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000798" rel="nofollow noreferrer">Rails API docs</a>.</p>
32,089
<p>I'll phrase this in the form of an example to make it more clear.</p> <p>Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?</p> <pre><code>class Dog: public Animal{/*...*/}; class Cat: public Animal{/*...*/}; int main() { vector&lt;Animal*&gt; stuff; //cramming the dogs and cats in... for(/*all elements in stuff*/) //Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/} } </code></pre> <p>I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.</p> <p>Is there a way to do this? Thanks in advance.</p>
<p>As others has noted, you should neither use the <code>typeid</code>, nor the <code>dynamic_cast</code> operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness. </p> <p>Anyway here is what you do if you <strong>really</strong> want to do it (note that dereferencing an iterator will give you <code>Animal*</code> . So if you do <code>**it</code> you will get an <code>Animal&amp;</code>):</p> <pre><code>for(std::vector&lt;Animal*&gt;::iterator it = v.begin(); it != v.end(); ++it) { if(typeid(**it) == typeid(Dog)) { // it's a dog } else if(typeid(**it) == typeid(Cat)) { // it's a cat } } </code></pre> <p>Note you can apply the <code>typeid</code> operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like <code>typeid(*it)</code> . Using it like that will give you just <code>typeid(Animal*)</code> which isn't useful.</p> <p>Similar, <code>dynamic_cast</code> can be used:</p> <pre><code>for(std::vector&lt;Animal*&gt;::iterator it = v.begin(); it != v.end(); ++it) { if(Dog * dog = dynamic_cast&lt;Dog*&gt;(*it)) { // it's a dog (or inherited from it). use the pointer } else if(Cat * cat = dynamic_cast&lt;Cat*&gt;(*it)) { // it's a cat (or inherited from it). use the pointer. } } </code></pre> <p>Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.</p>
<p>You can use the <code>typeid</code> operator to do this, e.g.</p> <pre><code>if (typeid(stuff[i].getClass())==typeid(Dog)) </code></pre> <p>This can't catch if it's a derived class of <code>Dog</code>, though. You can use a <code>dynamic_cast</code> for that. However, any use of <code>typeid</code> or <code>dynamic_cast</code> is often indicative of a design flaw. Usually, you don't need to know what your derived types are, and there's probably a better way that involves polymorphism. It's hard to give the right advice without a real example, though.</p>
43,163
<p>In a fictitious web application ...</p> <ol> <li>The user clicks a link </li> <li>The server starts to prepare the response, but it takes several seconds</li> <li>The user cancels the page load</li> </ol> <p>What happens to the request? Does the server continue to prepare the response? Does the response arrive to the browser?</p>
<p>The server will continue to prepare the response. When it tries to send the response to the client, it'll fail. When this actually happens will probably depend on the actual application server implementation, whether the response is buffered etc.</p> <p>In Java EE app servers (Tomcat and WebLogic, probably others as well), you'll get the following exception:</p> <pre><code>java.net.SocketException: Connection reset by peer: socket write error </code></pre>
<p>I would think that the actual TCP connection is closed by the browser and therefore the web-server will be unable to send data, and unless it is specifically programmed to detect broken connections whilst preparing the data, then the page will be fully processed even if the user cancels.</p> <p>I have little knowledge on these things though, but that would be my guess.</p>
30,488
<p>I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently.</p> <p>Is there are way to do something like this:</p> <pre><code>installutil.exe myservice.exe /customarg1=username /customarg2=password </code></pre>
<p>Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call:</p> <pre><code>installutil.exe /user=uname /password=pw myservice.exe </code></pre> <p>It is done by overriding OnBeforeInstall in the installer class:</p> <pre><code>namespace Test { [RunInstaller(true)] public class TestInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller serviceProcessInstaller; public OregonDatabaseWinServiceInstaller() { serviceInstaller = new ServiceInstaller(); serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Test"; serviceInstaller.DisplayName = "Test Service"; serviceInstaller.Description = "Test"; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.Add(serviceInstaller); serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.User; Installers.Add(serviceProcessInstaller); } public string GetContextParameter(string key) { string sValue = ""; try { sValue = this.Context.Parameters[key].ToString(); } catch { sValue = ""; } return sValue; } // Override the 'OnBeforeInstall' method. protected override void OnBeforeInstall(IDictionary savedState) { base.OnBeforeInstall(savedState); string username = GetContextParameter("user").Trim(); string password = GetContextParameter("password").Trim(); if (username != "") serviceProcessInstaller.Username = username; if (password != "") serviceProcessInstaller.Password = password; } } } </code></pre>
<p>You can also force your service to run as User using <strong>ServiceProcessInstaller::Account = ServiceAccount.User</strong>;</p> <p>A popup asking "[domain\]user, password" will appear during service installation.</p> <pre><code>public class MyServiceInstaller : Installer { /// Public Constructor for WindowsServiceInstaller public MyServiceInstaller() { ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller(); ServiceInstaller serviceInstaller = new ServiceInstaller(); //# Service Account Information serviceProcessInstaller.Account = ServiceAccount.User; // and not LocalSystem; .... </code></pre>
16,947
<p>I have an auditing trigger that automatically places the time something was updated and the user that updated in fields in all my tables. I have another set of triggers that write event information from updates to an events table. The issue is when someone updates something, the event information is fired twice because of the first triggers. How to I suppress the duplicate entries?</p>
<p>Look into TRIGGER_NESTLEVEL function. It returns the current level of trigger nesting. You can check that to prevent the duplicates.</p>
<p>Disabling trigger-fires-trigger behavior can also be done in SS2005 by going into SS Mgt Studio and selecting the icon of the server in question, right-clicking, then select "Properties". Then select "Advanced" from the list on the left and set the value for "Allow Triggers to Fire Others" to 'False'.</p>
35,337
<p>I have Flex based consumer <a href="http://www.rollingrazor.com" rel="nofollow noreferrer">website</a> where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales. </p> <p>For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated.</p> <p>I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor.</p> <p>I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs.</p> <p>Any suggestions? </p>
<p>Ok, this is very tricky. The reason for me to say that is because you are asking for two things:</p> <ul> <li>relaxed repository schema so that you can store various data and change what gets saved dynamically later</li> <li>fixed database schema so that you can query data effectively</li> </ul> <p>The solution will be a compromise. You have to understand that. </p> <p>Let's assume that you have User table:</p> <pre><code>+---------------- | User +---------------- | UserId (PK) | ... +---------------- </code></pre> <p>1) XML blob approach You can either save your data as a blog (big XML) into a table (actually a property bag) but querying (filtering) will be a nightmare.</p> <pre><code>+---------------- | CustomProperty +---------------- | PropId (PK) | UserId (FK) | Data of type memo/binary/... +---------------- </code></pre> <p>Advantage is that you (business logic) own the schema. This is at the same time disadvantage of this solution. Another HUGE disadvantage is that querying/filtering will be EXTREMELY difficult and SLOW!</p> <p>2) Table per property Another solution is to make a special table per property (homepage, etc.). This table would contain value per user (FK based realtionship to the User table).</p> <pre><code>+---------------- | HomePage +---------------- | HomePageId (PK) | UserId (FK) | Value of type string +---------------- </code></pre> <p>Advantage of this approach is that you can very quickly see all the values for that property. Disadvantage is that you will have too many tables (one per custom property) and that you will join tables often during query operations.</p> <p>3) CustomProperty table In this solution you have one table holding all custom properties. </p> <pre><code>+---------------- | CustomPropertyEnum +---------------- | PropertyId (PK) | Name of type string +---------------- +---------------- | CustomProperty +---------------- | PropId (PK) | PropertyId (FK) | UserId (FK) | Value of type string +---------------- </code></pre> <p>In this solution you store all custom properties in one table. You also have a special enum table that allows you to more efficiently query data. The disadvantage is that you will join tables often during query operations.</p> <p>Choose for yourself. I would decide between 2 and 3 depending on your workload (most probably 3 because it is easier).</p>
<p>This is a classic case for using a NoSQL database. It could be used to store various key value pairs with ease and without any predefined schema. </p>
18,829
<p>I have written a KornShell (ksh) script that sets an array the following way:</p> <pre><code>set -A fruits Apple Orange Banana Strawberry </code></pre> <p>but when I am trying to run it from within cron, it raises the following error:</p> <pre><code>Your "cron" job on myhost /myScript.sh produced the following output: myScript.sh: -A: bad option(s) </code></pre> <p>I have tried many crontab syntax variants, such as:</p> <p>Attempt 1:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/myScript.sh </code></pre> <p>Attempt 2:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/./myScript.sh </code></pre> <p>Attempt 3:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script &amp;&amp; ./myScript.sh </code></pre> <p>Any workaround would be sincerely appreciated. Thanks much in advance!</p>
<p>Although I'm not sure it's the best way to do it, I've managed to solve it this way:</p> <p>Attempt 4:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script &amp;&amp; ksh ./myScript.sh </code></pre>
<p>Although I'm not sure it's the best way to do it, I've managed to solve it this way:</p> <p>Attempt 4:</p> <pre><code>0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script &amp;&amp; ksh ./myScript.sh </code></pre>
39,429
<p>Does NetworkStream.DataAvailable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...</p> <p>Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the receiver has got - not what the sender originally sent - but I'm not a sockets expert.</p> <p>Am I wrong? Or is length-prefix the way to go?</p> <p>(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).</p>
<p>One side of a connection is not going to know whether the other side's send buffer is empty.</p> <p><code>DataAvailable</code> only indicates whether there is incoming data to be read. You could use that prior to <code>Read()</code>, but it alone doesn't give you the information you want. It doesn't tell you the beginning and ending of each batch.</p> <p>I've coded back-and-forth conversation before, and I used length-prefixes in the data. What I did was write helper functions that read an exact number of bytes (chunks at a time) and no more.</p> <p>The only alternative to length-of-batch values in the stream is some way of examining the incoming data and recognizing the beginnings and endings of batches.</p>
<p>If you are needing to know when the receiver has received all of the data for a particular message then you definitely need to length prefix.</p> <p>I typically define a struct similar to this that goes out at the front of any binary messages i send.</p> <pre><code>struct Header { int packetIdentifier; int protocolVersion; int messageType; int payloadSize; } </code></pre> <p>The identifier lets you determine if you have a valid message of your protocol type. The version lets you revision your protocol. The message type is the type of message (ie: CommsOnline). The payload size is the size of the body of the message.</p>
20,115
<p>I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one. </p> <p>Clone would do, if the namespaces were the same. Is there a nice way to do it? (The substructure will change later on - but will be kept identical.)</p>
<p>Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace.</p> <p>Consider the following input XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;test xmlns="http://tempuri.org/ns_old"&gt; &lt;child attrib="value"&gt;text&lt;/child&gt; &lt;/test&gt; </code></pre> <p>Now you need a template that says "copy structure and name of everything you see, but declare a new namespace while you're at it":</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:old="http://tempuri.org/ns_old" &gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" omit-xml-declaration="no" /&gt; &lt;xsl:template match="node()|@*"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="node()|@*"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="old:*"&gt; &lt;xsl:element name="{local-name()}" namespace="http://tempuri.org/ns_new"&gt; &lt;xsl:apply-templates select="node()|@*"/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>When you run the above XML through it, this produces:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;test xmlns="http://tempuri.org/ns_new"&gt; &lt;child attrib="value"&gt;text&lt;/child&gt; &lt;/test&gt; </code></pre> <p>All your <code>http://tempuri.org/ns_old</code> elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.</p>
<p>Not sure if this applies, but I've done something similar working with two xml docs in vb.net:</p> <pre><code>Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement) CopyElement(FromE, ToE, Nothing) End Sub Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement, ByVal overAttr As Xml.XmlAttributeCollection) Dim NewE As Xml.XmlElement Dim e As Xml.XmlElement NewE = ToE.OwnerDocument.CreateElement(FromE.Name) CopyAttributes(FromE, NewE) If Not overAttr Is Nothing Then OverrideAttributes(overAttr, NewE) End If For Each e In FromE CopyElement(e, NewE, overAttr) Next ToE.AppendChild(NewE) End Sub Private Shared Sub CopyAttributes(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement) Dim a As Xml.XmlAttribute For Each a In FromE.Attributes ToE.SetAttribute(a.Name, a.Value) Next End Sub Private Shared Sub OverrideAttributes(ByVal AC As Xml.XmlAttributeCollection, ByVal E As Xml.XmlElement) Dim a As Xml.XmlAttribute For Each a In AC If Not E.Attributes.ItemOf(a.Name) Is Nothing Then E.SetAttribute(a.Name, a.Value) End If Next End Sub </code></pre>
31,085
<p>How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an <code>os.chdir()</code>, the cwd will not be changed after the function is called.</p>
<p>The answer for a decorator has been given; it works at the function definition stage as requested.</p> <p>With Python 2.5+, you also have an option to do that at the function <em>call</em> stage using a context manager:</p> <pre><code>from __future__ import with_statement # needed for 2.5 ≤ Python &lt; 2.6 import contextlib, os @contextlib.contextmanager def remember_cwd(): curdir= os.getcwd() try: yield finally: os.chdir(curdir) </code></pre> <p>which can be used if needed at the function call time as:</p> <pre><code>print "getcwd before:", os.getcwd() with remember_cwd(): walk_around_the_filesystem() print "getcwd after:", os.getcwd() </code></pre> <p>It's a nice option to have.</p> <p>EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.</p>
<pre><code>def preserve_cwd(function): def decorator(*args, **kwargs): cwd = os.getcwd() result = function(*args, **kwargs) os.chdir(cwd) return result return decorator </code></pre> <p>Here's how it's used:</p> <pre><code>@preserve_cwd def test(): print 'was:',os.getcwd() os.chdir('/') print 'now:',os.getcwd() &gt;&gt;&gt; print os.getcwd() /Users/dspitzer &gt;&gt;&gt; test() was: /Users/dspitzer now: / &gt;&gt;&gt; print os.getcwd() /Users/dspitzer </code></pre>
20,404
<p>Is there a way in Ruby to find the version of a file, specifically a .dll file?</p>
<p>For Windows EXE's and DLL's:</p> <pre><code>require "Win32API" FILENAME = "c:/ruby/bin/ruby.exe" #your filename here s="" vsize=Win32API.new('version.dll', 'GetFileVersionInfoSize', ['P', 'P'], 'L').call(FILENAME, s) p vsize if (vsize &gt; 0) result = ' '*vsize Win32API.new('version.dll', 'GetFileVersionInfo', ['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result) rstring = result.unpack('v*').map{|s| s.chr if s&lt;256}*'' r = /FileVersion..(.*?)\000/.match(rstring) puts "FileVersion = #{r ? r[1] : '??' }" else puts "No Version Info" end </code></pre> <p>The 'unpack'+regexp part is a hack, the "proper" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)</p>
<p>For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is. There is no API or common method to determine a file version in Ruby.</p> <p>Note that it would be easier if the file version were in the file name.</p>
10,210
<p>With LINQ to SQL most likely going to not get as much active development as Entity Framework do you think it's best to switch to Entity Framework?</p> <p>I've personally found EF to be very clunky and hard to use compared to LINQ to SQL which feels very natural.</p> <p>EDIT: I recently posted an article on my blog about my feelings towards this potential decision...</p> <p><a href="http://weblogs.asp.net/chadmoran/archive/2008/11/09/ado-net-v-linq-to-sql.aspx" rel="noreferrer">ADO.NET v LINQ to SQL</a></p>
<p>IMO, not at the moment.</p> <p>It is clear (from <a href="http://blogs.msdn.com/adonet/archive/2008/10/31/clarifying-the-message-on-l2s-futures.aspx" rel="nofollow noreferrer">recent announcements</a> especially) that EF is in for some heavy revisions as the "<a href="http://codebetter.com/blogs/ian_cooper/archive/2008/11/03/linq-to-sql-ef-and-the-thunderdome-solution.aspx" rel="nofollow noreferrer">thunderdome</a>" scenario plays out between LINQ-to-SQL and EF. Whatever happens, EF (in a few years) will almost certainly look quite different to EF today. Or certainly "different enough" ;-p</p> <p>As such, my view is: stick with simple. And simple is LINQ-to-SQL.</p> <p>I don't see much benefit learning a notoriously complex system if I know it is going to change very soon.</p> <p>And I'm 100% with you on LINQ-to-SQL ;-p</p> <p>If I needed something more than LINQ-to-SQL right now, I'd look at <a href="http://www.nhibernate.org/" rel="nofollow noreferrer">NHibernate</a> or maybe <a href="http://www.llblgen.com/" rel="nofollow noreferrer">LLBLGen Pro</a>.</p> <p>(<strong>edit</strong> - as an update, my position has softened a little bit, <a href="http://marcgravell.blogspot.com/2008/12/entity-framework-in-reality.html" rel="nofollow noreferrer">here</a> and <a href="http://marcgravell.blogspot.com/2009/03/back-to-coal-face.html" rel="nofollow noreferrer">here</a> - but I'm still using LINQ-to-SQL as my primary tool; also - LINQ-to-SQL <a href="http://marcgravell.blogspot.com/2009/02/linq-to-sql-not-quite-dead-yet.html" rel="nofollow noreferrer">isn't quite dead yet</a> ;-p).</p>
<p>Recently, i had to research which ORM project should use. At first - tried L2S. It wasn't bad at all, but it's already obsolete (MS won't support it anymore), that's why i started to check out L2E. I'm fine with generated code, but creating fake views, entities and mappings between them just to make stored procedure available not to fill all fields of entity was an overkill for me. And i wanted to separate my dataaccess layer, so - i had to map data from generated objects to ones i made. </p> <p>It took me few hours of experimenting with NHibernate+Fluent NHibernate+LINQ to NHibernate<br> to stick with this combination.</p>
34,857
<p>I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction.</p> <p>In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel.</p> <p>Can anyone suggest how to fix this?</p> <p>I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/&gt; &lt;script type="text/javascript" src="ext/ext-base.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ext/ext-all-debug.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "-&gt;", {id: "continue", text: 'Continue'} ] }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<h3>2015 update: the flexbox approach</h3> <p>There are two other answers briefly mentioning <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">flexbox</a>; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now.</p> <blockquote> <p>Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.</p> <p>(taken from <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes</a>)</p> </blockquote> <p>All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim.</p> <p>To check current support you can also see here: <a href="http://caniuse.com/#feat=flexbox" rel="noreferrer">http://caniuse.com/#feat=flexbox</a></p> <h3>Working example</h3> <p>With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --&gt; &lt;div class="box"&gt; &lt;div class="row header"&gt; &lt;p&gt;&lt;b&gt;header&lt;/b&gt; &lt;br /&gt; &lt;br /&gt;(sized to content)&lt;/p&gt; &lt;/div&gt; &lt;div class="row content"&gt; &lt;p&gt; &lt;b&gt;content&lt;/b&gt; (fills remaining space) &lt;/p&gt; &lt;/div&gt; &lt;div class="row footer"&gt; &lt;p&gt;&lt;b&gt;footer&lt;/b&gt; (fixed height)&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>In the CSS above, the <a href="https://developer.mozilla.org/en/CSS/flex" rel="noreferrer">flex</a> property shorthands the <a href="https://developer.mozilla.org/en/CSS/flex-grow" rel="noreferrer">flex-grow</a>, <a href="https://developer.mozilla.org/en/CSS/flex-shrink" rel="noreferrer">flex-shrink</a>, and <a href="https://developer.mozilla.org/en/CSS/flex-basis" rel="noreferrer">flex-basis</a> properties to establish the flexibility of the flex items. Mozilla has a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">good introduction to the flexible boxes model</a>.</p>
<p>it <strong>never worked for me in other way then with use of the JavaScript</strong> as NICCAI suggested in the very first answer. I am using that approach to rescale the <code>&lt;div&gt;</code> with the Google Maps. </p> <p>Here is the full example how to do that (works in Safari/FireFox/IE/iPhone/Andorid (works with rotation)):</p> <p>CSS</p> <pre><code>body { height: 100%; margin: 0; padding: 0; } .header { height: 100px; background-color: red; } .content { height: 100%; background-color: green; } </code></pre> <p>JS</p> <pre><code>function resize() { // Get elements and necessary element heights var contentDiv = document.getElementById("contentId"); var headerDiv = document.getElementById("headerId"); var headerHeight = headerDiv.offsetHeight; // Get view height var viewportHeight = document.getElementsByTagName('body')[0].clientHeight; // Compute the content height - we want to fill the whole remaining area // in browser window contentDiv.style.height = viewportHeight - headerHeight; } window.onload = resize; window.onresize = resize; </code></pre> <p>HTML</p> <pre><code>&lt;body&gt; &lt;div class="header" id="headerId"&gt;Hello&lt;/div&gt; &lt;div class="content" id="contentId"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre>
11,559
<p>I've inherited a WSDL file for a web service on a system that I don't have access to for development and testing.</p> <p>I need to generate a web service that adheres to that WSDL. The wrapper is .NET, but if there's an easy way to do this with another platform, we might be able to look at that. The production web service is Java-based.</p> <p>What's the best way to go about doing this?</p> <p>Note: The inherited wsdl doesn't appear to be compatible with <b>wsdl.exe</b> because it doesn't conform to WS-I Basic Profile v1.1. In particular, the group that passed it on mentioned it uses another standard that the Microsoft tool doesn't support, but they didn't clarify. The error is related to a required 'name' field:</p> <pre>Error: Element Reference '{namespace}/:viewDocumentResponse' declared in schema type '' from namespace '' - the required attribute 'name' is missing</pre> <p>For clarity's sake, I understand that I can easily create a .NET wrapper class from the WSDL file, but that's not what I need. It's like this:</p> <p>Update: The original web service was created using Axis.</p> <p><a href="http://paulw.us/blog/uploads/SO-WSDL-Question2.gif" rel="nofollow noreferrer">Diagram of system showing unavailable web service and mock web service http://paulw.us/blog/uploads/SO-WSDL-Question2.gif</a></p>
<p>You may find useful the <a href="http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx" rel="noreferrer">command line utility <code>wsdl.exe</code></a> of .NET by using the <code>/serverInterface</code> option. According to the documentation:</p> <blockquote> <p>Generates interfaces for server-side implementation of an ASP.NET Web Service. An interface is generated for each binding in the WSDL document(s). The WSDL alone implements the WSDL contract (classes that implement the interface should not include either of the following on the class methods: Web Service attributes or Serialization attributes that change the WSDL contract). Short form is '/si'.</p> </blockquote>
<p>Try mock the wrapper interface using <a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">RhinoMocks</a> and <a href="http://structuremap.sourceforge.net/Default.htm" rel="nofollow noreferrer">StructureMap</a> .</p>
29,080
<p>I want to create two piece labels for storage containers. The main piece would be the “badge” which would have text cut out of it (e.g. “Paint”, “Electrical” etc.). The second piece would be a positive of the text which is would be in a different colour, and would fit inside the cut out on the badge. Because of the tolerance of 3D printers, I need to make the insert slightly smaller than the cut out. Initially, I thought I could just scale the insert but that would affect the letter spacing. Then I thought it would work if I could somehow taper the letters so they are slightly smaller at the top than the bottom. So my question is, how I do that. I did the original in OpenScad but I would try Fusion360 if that’s a better solution. Any and all suggestions are welcome. Thanks.</p>
<p>In OpenSCAD, apply the <code>offset</code> transformation to inset the letter outlines before extruding them. However you may find it works better to fill the sunken letter shapes with nail polish then remove the overflow with acetone; see my question &amp; answer <a href="https://3dprinting.stackexchange.com/a/10872/11157">https://3dprinting.stackexchange.com/a/10872/11157</a>.</p>
<p>You will need to run test prints to see how your printer behaves with your choice of filaments. Then you'll know how much narrower the letter-lines (not the letter dimensions) need to be to fit. </p> <p>The problem with that is one of making letters with narrow solid parts but without "shrinking" the open parts so that they fit into the badge receptacle regions. You can't just reduce the dimensions of the letters themselves. </p> <p>Other than what Trish's answer suggests, I'd recommend either using a very small nozzle diameter and setting a narrow linewidth to reduce the "over-dimensioning" effects. Even better would be to identify the letters separately from the badge but keep them as a single STL and use a two-color printer (twin extruders, etc) to make the badge in one run. </p>
1,555
<p>I recently changed filament and for starters it worked perfectly well, but quickly I got some problems with my first layer. It's like droplets are forming on the surface (finished item + 3 undersides):</p> <p><a href="https://i.stack.imgur.com/qgPyl.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qgPyl.jpg" alt="enter image description here"></a></p> <p>The final part is (for me) okay but I'd like to get rid of those pesky 'drops'.</p> <p><strong>As the defect is quite stable and quite recognizable and it happens all the time, I bet somebody more experienced than me knows what's going on!</strong></p> <p>Info:</p> <p>I'm using a 1 week old eSun filament, a E3D V6 Hotend 1.75mm on my scratch CoreXY printer, short Bowden direct drive, Repetier, Marlin, Linear advance (M900 K60 so quite low).</p> <p>The print is done using a 0.4mm diameter nozzle at 0.2mm height at:</p> <p>50°C(122°F) heat-bed and 214°C(417°C) hot-end for first layer, then lower a bit to</p> <p>40°C(104°F) heat-bed and 211°C(412°F) hot-end.</p> <p>I use Blue-painter tape.</p> <p>Worked perfectly well with my black eSun and my white eSun.</p> <p><strong>What's my problem?</strong></p> <p>Thank you all!</p> <p>[Edit]</p> <p>Tried about everything (more temp, less temp, fan on item, more / less bed temp, underextrude, moving around z delta, removing linear advance, radically lowering speed) but the only thing that worked about okay (problem was quite reduced but didn't go away totally) was to bump up the layer thickness to 0.3mm</p> <p>[Edit 2] Finally it seems it was, as it usually is, a conjuncture of several problems that I will list here:</p> <ul> <li>The bed was not perfectly flat</li> <li>The heatbed moved/bended when going from a hot first layer to a colder second (and on) layer</li> <li>Maybe the speed was a bit high for the first layer (25mm/s)</li> </ul> <p>I fixed this by installing a borosilicate glass bed on top of the heat bed which ensures a perfect flatness.</p> <p>I had to change my inductive sensor to an 8mm one (insteéad of the 4mm I had previously added) to make this function. I think it is not as good as it can be as it detects the heatbed under the glass (which is not perfectly flat), but it's enough for now. I'm thinking about how to make the glass conductive, like aluminium or something, but that's for another day/post.</p> <p>I also put blue tape on the glass because the first layer was tricky. This might be because the inductive sensor doesn't do its job that well (see above).</p> <p>Heatbed temperature for first layer: 70°C</p> <p>Extruder temperature anywhere from 190°C to 220°C works fine, that was not the problem, or it is no longer a problem.</p> <p>I also lowered the first layer speed to 20mm/s because the first layer didn't stick easily directly onto the glass, with blue painters tape it sticks even too much so I'll try higher speeds. It did mitigate problems though so it might be a path to try if you run into similar problems.</p> <p>And now it seems that it works even amazingly well, I just have to print something really big to see!</p> <p>---------------Old:</p> <p>Moving z up made spaghetti :-) and different temperatures made quite extreme warping:</p> <p><a href="https://i.stack.imgur.com/eV7UJ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eV7UJ.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/7VeCT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7VeCT.jpg" alt="enter image description here"></a></p>
<p>Mine is more of an educated guess than a definitive diagnosis, but <strong>it looks to me like if your printer may be overextruding</strong> (it's difficult to say with certainty with this particular picture, but your top layers too do not look as good as they should).</p> <p><strong>I wonder if you have <a href="https://www.matterhackers.com/articles/how-to-calibrate-your-extruder" rel="noreferrer">calibrated your extrusion</a> for this particular spool of filament</strong>? This is something that you should do for each and every new spool of filament, regardless of whether you have already used the same brand and material, as different batches and colours may differ slightly in diameter or hardness, and both factors can lead to a different overall flow out of your nozzle (I just checked eSun website, and they state "Accuracy:1.7-1.8mm", and 6% variance is quite a lot).</p> <p>Possibly unrelated, but <strong>211+°C is also quite on the high end of the correct temperature for printing PLA</strong> (if that is what you are using). Still in the range recommended by the manufacturer - so it should be ok - but you may wish to try bringing it down a notch (205°C perhaps?).</p>
<p>Mine is more of an educated guess than a definitive diagnosis, but <strong>it looks to me like if your printer may be overextruding</strong> (it's difficult to say with certainty with this particular picture, but your top layers too do not look as good as they should).</p> <p><strong>I wonder if you have <a href="https://www.matterhackers.com/articles/how-to-calibrate-your-extruder" rel="noreferrer">calibrated your extrusion</a> for this particular spool of filament</strong>? This is something that you should do for each and every new spool of filament, regardless of whether you have already used the same brand and material, as different batches and colours may differ slightly in diameter or hardness, and both factors can lead to a different overall flow out of your nozzle (I just checked eSun website, and they state "Accuracy:1.7-1.8mm", and 6% variance is quite a lot).</p> <p>Possibly unrelated, but <strong>211+°C is also quite on the high end of the correct temperature for printing PLA</strong> (if that is what you are using). Still in the range recommended by the manufacturer - so it should be ok - but you may wish to try bringing it down a notch (205°C perhaps?).</p>
804
<p>How does one do namespaced controllers in Merb, for instance to create an admin section to the site? In Rails one would use Admin::CategoriesController, is this similar in Merb or is this another recommended way of doing it?</p>
<p>The namespace method seems to do it.</p> <p>This is placed in the routes file (router.rb):</p> <pre><code>namespace :admin do resources :categories end </code></pre> <p>This generates routes like:</p> <pre> edit_admin_category - /admin/categories/:id/edit(.:format) delete_admin_category - /admin/categories/:id/delete(.:format) admin_categories - /admin/categories(/index)(.:format) new_admin_category - /admin/categories/new(.:format) admin_category - /admin/categories/:id(.:format) </pre> <p>I then put my controller in a module like this:</p> <pre><code>module Admin class Categories &lt; Application def index ... end . . . end end </code></pre> <p>I am not sure if this is the recommended way, any suggestions to this would be great.</p>
<p>The above answer is correct, but for what it's worth, I had a hard time trying to make use of the new route with link_to in my views.</p> <p>I ended up getting this to work:</p> <pre><code>&lt;%= link_to("Categories Admin", resource(:admin, :categories) %&gt; </code></pre>
35,788
<p>Is there a way, in Axapta/Dynamics Ax, to create an Extended Data Type of type integer which only allows enering values in a specified range (i.e., if the extended data type is meant for storing years, I should be able to set a range like 1900-2100), or do I have to manage the range using X++ code?</p> <p>And if I need to use X++ code to manage the range, which is the best way to do it?</p>
<p>I suggest you use the ''validateField'' of the corresponding table. Search for the method in AOT\Data Dictionay\Tables to see many examples.</p>
<p>You can can't specify the range on the extended data type itself. If the type is used for a table field, you can add code to the insert and update methods of the table, in order to validate the value whenever the record is updated. This approach could however have a cost in terms of performance.</p> <p>You can also choose to just add code the the validateWrite method of the table, if you are satisfied with the validation only taking place when the value is modified from the UI.</p>
47,659
<p>What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?</p> <p>One idea I had (in python)</p> <pre><code>def validate_password(passwd): conditions_met = 0 conditions_total = 3 if len(passwd) &gt;= 6: if passwd.lower() != passwd: conditions_met += 1 if len([x for x in passwd if x.isdigit()]) &gt; 0: conditions_met += 1 if len([x for x in passwd if not x.isalnum()]) &gt; 0: conditions_met += 1 result = False print conditions_met if conditions_met &gt;= 2: result = True return result </code></pre>
<p>Depending on the language, I usually use regular expressions to check if it has:</p> <ul> <li>At least one uppercase and one lowercase letter</li> <li>At least one number</li> <li>At least one special character</li> <li>A length of at least six characters</li> </ul> <p>You can require all of the above, or use a strength meter type of script. For my strength meter, if the password has the right length, it is evaluated as follows:</p> <ul> <li>One condition met: weak password</li> <li>Two conditions met: medium password</li> <li>All conditions met: strong password</li> </ul> <p>You can adjust the above to meet your needs.</p>
<p>Password strength checkers, and if you have time+resources (its justified only if you are checking for more than a few passwords) use Rainbow Tables.</p>
10,066
<p>I have a class which extends SWFLoader, I use it like a normal SWFLoader:</p> <pre><code>var loader:MySWFLoader = new MySWFLoader(); loader.load("myFile.SWF"); myScene.addChild(loader); </code></pre> <p>The loading works OK, except that it remains 0 because the width &amp; height never change from 0. I had to override the width/height get properties to make it work:</p> <pre><code>class MySWFLoader extends SWFLoader { public override function get width():Number{ return contentWidth; } public override function get height():Number{ return contentHeight; } } </code></pre> <p>As well as being a big hack this isn't quite correct; especially since the SWF has multiple frames and the frames are of different width/height.</p> <p>Why aren't width/height working in the first place? Shouldn't they be automatically set during loading? Is it possible the issue lies with the SWF itself somehow?</p> <p><strong>Update</strong>: Changing scaleContent to true or false makes no difference.</p>
<p>I'm not sure if this applies for SWF loading, but whenever I'm loading content, i cannot access width and height before the whole thing is loaded.</p> <p>So make an event listener that listens when the loading is completed, and then read the height/width.</p> <p>Also take a look at the loaderInfo class in AS3</p>
<p>By default the SWFLoader scales the content to the size of the loader, so you have to set the size of the loader. If you want the loader to scale to the size of the content then you have to set the scaleContent property to false.</p>
25,511
<p>I have a really long 3 column table. I would like to </p> <pre><code>&lt;table&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Start&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;End&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre> <p>This is the result I'm trying to obtain using jQuery.</p> <pre><code>Column1 Column2 Column1 Column2 ...Show Full Table... Column1 Column2 Column1 Column2 </code></pre> <p>I would like to use jQuery's show/hide feature to minimize the table but still show part of the top and bottom rows. The middle rows should be replace with text like "Show Full Table" and when clicked will expand to show the full table from start to finish.</p> <p>What is the best way to do this in jQuery?</p> <p>BTW I've already tried adding a class "Table_Middle" to some of the rows but it doesn't hide it completely the space it occupied is still there and I don't have the text to give the user a way to expand the table fully.</p> <p><strong>[EDIT] Added Working Example HTML inspired by Parand's posted answer</strong></p> <p><strong><em>The example below is a complete working example, you don't even need to download jquery. Just paste into a blank HTML file.</em></strong></p> <p><em>It degrades nicely to show only the full table if Javascript is turned off. If Javascript is on then it hides the middle table rows and adds the show/hide links.</em></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=windows-1252"&gt; &lt;title&gt;Example Show/Hide Middle rows of a table using jQuery&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#HiddenRowsNotice").html("&lt;tr&gt;&lt;td colspan='2'&gt; &lt;a href='#'&gt;&gt;&gt; some rows hidden &lt;&lt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;"); $("#ShowHide").html("&lt;tr&gt;&lt;td colspan='2'&gt;&lt;a href='#'&gt;show/hide middle rows&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;"); $("#HiddenRows").hide(); $('#ShowHide,#HiddenRowsNotice').click( function() { $('#HiddenRows').toggle(); $('#HiddenRowsNotice').toggle(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tbody id="ShowHide"&gt;&lt;/tbody&gt; &lt;tr&gt;&lt;th&gt;Month Name&lt;/th&gt;&lt;th&gt;Month&lt;/th&gt;&lt;/tr&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;Jan&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody id="HiddenRowsNotice"&gt;&lt;/tbody&gt; &lt;tbody id="HiddenRows"&gt; &lt;tr&gt;&lt;td&gt;Feb&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Mar&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Apr&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;May&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>[EDIT] Link my <a href="http://www.developerbuzz.com/2008/10/use-jquery-to-show-and-hide-part-of.html" rel="nofollow noreferrer">blog post</a> and working example.</p>
<p>Something like this could work:</p> <pre><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr class="Show_Rows"&gt;&lt;td&gt;Start&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody class="Table_Middle" style="display:none"&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody&gt; &lt;tr class="Show_Rows"&gt;&lt;td&gt;End&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; $('#something').click( function() { $('.Table_Middle').hide(); $('.Show_Rows').show(); }); $('.Show_Rows').click( function() { $('.Show_Rows').hide(); $('.Table_Middle').show(); }); </code></pre>
<p>I'd probably do it like this:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Col1&lt;/th&gt; &lt;th&gt;Col2&lt;/th&gt; &lt;th&gt;Col3&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;/tr&gt; ... &lt;/tbody&gt; &lt;tbody id="hidden-rows"&gt; &lt;tr&gt; &lt;td colspan="3"&gt; &lt;a href="#" onclick="$('#hidden-rows').hide();$('#extra-rows').show();"&gt; Show hidden rows &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tbody id="extra-rows" style="display: none;"&gt; &lt;tr&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;/tr&gt; ... &lt;/tbody&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;td&gt;data1&lt;/td&gt; &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>It's not a great method, because it doesn't degrade nicely.</p> <p>To get it to degrade nicely, you'd have to have all the rows shown initially, and then hide them with your jQuery document ready function, and also create the row with the link in.</p> <p>Also, your method of giving the rows to hide a particular class should also work. The jQuery would look something like this:</p> <pre><code>$(document).ready(function() { $('tr.Table_Middle').hide(); }); </code></pre> <p>You'd still need to create the row with the link to unhide them though.</p>
26,450
<p>I am hosting <a href="http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference" rel="nofollow noreferrer">SpiderMonkey</a> in a current project and would like to have template functions generate some of the simple property get/set methods, eg:</p> <pre><code>template &lt;typename TClassImpl, int32 TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToInt32(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Used:</p> <pre><code>::JSPropertySpec Vec2::s_JsProps[] = { {"x", 1, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::x&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::x&gt;}, {"y", 2, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::y&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::y&gt;}, {0} }; </code></pre> <p>This works fine, however, if I add another member type:</p> <pre><code>template &lt;typename TClassImpl, JSObject* TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToObject(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Then Visual C++ 9 attempts to use the JSObject* wrapper for int32 members!</p> <pre><code>1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const ' 1&gt; Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* ' 1&gt; d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp' 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp' 1&gt; None of the functions with this name in scope match the target type </code></pre> <p>Surprisingly, parening JSObject* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject* PObject; ..., PObject TClassImpl::<em>mem>", void</em>, struct Undefined*, and double. Since the function usage is fully instantiated: "&amp;ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.</p> <p>Vec2 is just:</p> <pre><code>class Vec2 { public: int32 x, y; Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv); static ::JSClass s_JsClass; static ::JSPropertySpec s_JsProps[]; }; </code></pre> <p>JSPropertySpec is described in JSAPI link in OP, taken from header:</p> <pre><code>typedef JSBool (* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id, jsval *vp); ... struct JSPropertySpec { const char *name; int8 tinyid; uint8 flags; JSPropertyOp getter; JSPropertyOp setter; }; </code></pre>
<p>Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:</p> <pre><code>struct X { int i; void* p; }; template&lt;int X::*P&gt; void foo(X* t) { t-&gt;*P = 0; } template&lt;void* X::*P&gt; void foo(X* t) { t-&gt;*P = 0; } int main() { X x; foo&lt;&amp;X::i&gt;(&amp;x); foo&lt;&amp;X::p&gt;(&amp;x); } </code></pre> <p>VC++ 2008SP1, however, is having none of it.</p> <p>I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here.</p>
<p>Try changing the JSObject * to another pointer type to see if that reproduces the error. Is JSObject defined at the point of use? Also, maybe JSObject* needs to be in parens.</p>
13,766
<p>I have a large query in a PostgreSQL database. The Query is something like this:</p> <pre><code>SELECT * FROM table1, table2, ... WHERE table1.id = table2.id... </code></pre> <p>When I run this query as a sql query, the it returns the wanted row.</p> <p>But when I tries to use the same query to create a view, it returns an error:</p> <p>"error: column "id" specified more than once."</p> <p>(I use pgAdminIII when executing the queries.)</p> <p>I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?</p>
<p>That happens because a view would have two id named columns, one from table1 and one from table2, because of the select *.</p> <p>You need to specify which id you want in the view.</p> <pre><code>SELECT table1.id, column2, column3, ... FROM table1, table2 WHERE table1.id = table2.id </code></pre> <p>The query works because it can have equally named columns...</p> <pre><code>postgres=# select 1 as a, 2 as a; a | a ---+--- 1 | 2 (1 row) postgres=# create view foobar as select 1 as a, 2 as a; ERROR: column "a" duplicated postgres=# create view foobar as select 1 as a, 2 as b; CREATE VIEW </code></pre>
<p>No built-in way in the language to solve it (and frankly, * is a bad practice in general because it can cause latent defects to arise as the table schemas change - you can do table1.*, table2.acolumn, tabl2.bcolumn if you want all of one table and selectively from another), but if PostgreSQL supports INFORMATION_SCHEMA, you can do something like:</p> <pre><code>DECLARE @sql AS varchar SELECT @sql = COALESCE(@sql + ', ', '') + '[' + TABLE_NAME + '].[' + COLUMN_NAME + ']' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN ('table1', 'table2') ORDER BY TABLE_NAME, ORDINAL_POSITION PRINT @sql </code></pre> <p>And paste the results in to save a lot of typing. You will need to manually alias the columns which have the same name, of course. You can also code-gen unique names if you like (but I don't):</p> <pre><code>SELECT @sql = COALESCE(@sql + ', ', '') + '[' + TABLE_NAME + '].[' + COLUMN_NAME + '] ' + 'AS [' + TABLE_NAME + '_' + COLUMN_NAME + ']' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN ('table1', 'table2') ORDER BY TABLE_NAME, ORDINAL_POSITION </code></pre>
25,498
<p>The question sort of says it all.</p> <p>Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. </p> <p>Bonus points for parsimonious and readable code samples. </p>
<p>I believe the following will work:</p> <pre><code>Dim b As CommandButton Set b = ocx.GetButton("btnPrint") b = True </code></pre> <p><code>CommandButton</code>s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a <code>CheckBox</code>. The default property of the <code>CommandButton</code> is actually the <code>Value</code> property that indicates whether a button is toggled. By setting the property, the <code>Click</code> event is generated. This is done even if the button is not styled as a <code>ToggleButton</code> and therefore doesn't change its state.</p>
<p>Do you have access to the OCX code? You shouldn't really be directly invoking the click of a button. You should refactor the code so that the OCX button click code calls a function, e.g.</p> <pre><code>CMyWindow::OnLButtonDown() { this-&gt;FooBar(); } </code></pre> <p>Then from your VB6 app, directly call the FooBar method. If you can't directly call functions from VB6 you can wrap the FooBar() method with a windows message proc function, e.g.</p> <pre><code>#define WM_FOOBAR WM_APP + 1 </code></pre> <p>Then use <code>SendMessage</code> in the VB6, like <code>SendMessage(WM_FOOBAR, ...)</code></p>
6,238
<p>What are the advantages/disadvantages to running time based jobs using:</p> <ol> <li><p>windows services</p></li> <li><p>Application_BeginRequest to start seperate threads / timers.</p></li> </ol> <p>One disadvantage of running the jobs in the context of a asp.net web appplication is during .net recycling things will have to be setup again, any others?</p>
<p>To my mind, there's no real benefit to doing time-based things in a web app. Go straight to a windows service. You know the process should be up and running all the time.</p> <p>The ASP.NET site may simply unload, and will only operate again once someone starts browsing. The lifecycle is all wrong -- it's much 'choppier' than a service. </p> <p>Lastly, services aren't very hard to create.</p>
<p>If you have administrative access to the server, I would either run a Windows Service or a scheduled SQL job depending on what you are trying to achieve. </p> <p>It is nice to be able to stop/start and log these jobs independent of your web application. Also, if you have problems or errors in the job, it could adversely affect your website. </p> <p>Finally, you are forcing the web application to go through code at <strong>every</strong> request to see if the timer has elapsed, which is an unnecessary overhead.</p> <p>As I said to start with, the implementation depends on what the job is. If it is simply to update a number of database records, I'd use a scheduled job in SQL Server. If you need file I/O or access to external services, then a Windows Service might be more appropriate. </p> <p>It is worth noting that you need to build in your own scheduling and thread safety into Windows Services. An alternative is to build a console application and use an application like <a href="http://www.firedaemon.com/" rel="nofollow noreferrer">FireDaemon</a> for the scheduling.</p>
39,317
<p>Environment: Windows 2003 Server (32 bit); IIS6, ASP.NET 2.0 (3.5); 4Gb Ram; 1 Worker Process </p> <p>We have a situation where we have a very large System.XmlDocument is being loaded into memory, and then it heads into a complied XSL transform. What is happening is when a web request comes in the server is sitting in an idle state with 2500Mb of available system memory.</p> <p>As the XML DOM is populated, the available memory drops approx 500Mb at which point we get a System.OutOfMemoryException event. At this point the system should theoretically still have 2000Mb of available memory available to service the request (according to Perfmon).</p> <p>The related questions I have are: </p> <p>1) At what level in the stack is this out of memory limitation being met? OS? IIS? ASP.NET? worker process? Is this a per individual web request limit?</p> <p>2) Is this limit configurable somewhere?</p> <p>3) Why can’t this web request access the full available system memory?</p>
<p>1) I would guess at the worker process but this should be configurable within IIS to the limit of memory that a worker process can use. Another factor is what level of bits does your software use, e.g. 32 bit has a physical limit of 4 GB since this is the total address space.</p> <p>2) Probably but don't forget that memory fragmentation may play a role in getting to out of memory faster than you think, e.g. if there is a memory request for a contiguous 1000 Mb piece of memory then this may not necessarily be found in the current memory.</p> <p>3) Have you examined dump data to see what is in the memory when the exception gets thrown? If not, there are ways to get a snapshot of the memory to see what it looks like as this may give you more clues about what is going on.</p>
<p>I'm sure there are some bright heads here that can answer your specific questions, but have you asked yourself if there is another way to do what you want? I specifically mean that you probably do not want to process a very large XML document, but you probably more specifically want to return something back to the client. Could you rewrite the code to avoid this XML document altogether, or perhaps not load it all into memory at the same time, and still produce the same end-result?</p>
49,282
<p>Do you know any applications to synchronize two databases - during development sometimes it's required to add one or two table rows or new table or column. Usually I write every sql statement in some file and during uploading path I evecute those lines on my production database (earlier backing it up). I work with mySQL and postreSQL databases.</p> <p>What is your practise and what applications helps you in that.</p>
<p>You asked for a tool or application answer, but what you really need is a a process answer. The underlying theme here is that you should be versioning your database DDL (and DML, when needed) and providing change scripts to be able to update any version of your database to a higher version.</p> <p>This set of links provided by Jeff Atwood and written by K. Scott Allen explain in detail what this ought to look like - and they do it better than I can possibly write up here: <a href="http://www.codinghorror.com/blog/2008/02/get-your-database-under-version-control.html" rel="noreferrer">http://www.codinghorror.com/blog/2008/02/get-your-database-under-version-control.html</a></p>
<p>Siebel (CRM, Sales, etc. management product) has a built-in tool to align the production database with the development one (dev2prod).</p> <p>Otherwise, you've got to stick with manually executed scripts.</p>
31,933
<p>I am looking for a specific desgin pattern.</p> <p>For example i have an article class, clsArticle. This class contains member variables like Id, title, author, article, and so on. Imagine i want to show all the articles in a list. So somewhere i have to create a method getAllArticles(). Since clsArticle is not responsible for getting all the articles, i have to put this method in another class, clsArticleFact (Where Fact stands for Factory).</p> <p>Does someone know how this pattern is called? Is this way of working a design pattern?</p>
<p>Yeap. That's correct. </p> <p>It may be either an AbstractFactory or a DataAccessObject.</p> <p>The first is when you want to let the implementation return different kinds of articles</p> <p>For instance let's say you have a condition where the articles behave different according with the platform.</p> <pre><code>ArticleFactory.getAll(): Article[] </code></pre> <p>Would return the correct list in each platform.</p> <p>The impl may be:</p> <pre><code>WindowsArticleFactory </code></pre> <p>or</p> <pre><code>OSXArticleFactory </code></pre> <p>The former may be used to abstract the place where the articles are retrieved from:</p> <p>You may have </p> <pre><code>ArticleDao.getAll(): Article[] </code></pre> <p>and the implementations:</p> <pre><code>XmlArticleDao // Return a list of articles from an XML </code></pre> <p>or </p> <pre><code>DatabaseArticleDao // return the list from the database. </code></pre> <p>The point here is to decouple the creation ( getAll() ) from the usage ( Article ) </p> <p>If you application is simple enough you can use a factoryMethod instead.</p> <pre><code> class Article { static Article[] getAll() { // do whatever is neede here... } } </code></pre> <p>I hope this helps. </p>
<p>Well, create a static class for that purpose:</p> <pre><code>public static class clsArticles { public static clsArticles[] GetAllArticles() { /* actual code */ } } </code></pre>
46,790
<p>For an application (*) I'm developing I need a mixture of dynamically generated and static pages. It would be cool to use a wiki such that once a dynamic page has been accessed for the first time it becomes a static page that can be annotated by a user just like any other static wiki page.</p> <p>In other words, I want to override whatever outputs the message "This topic does not exist yet" (or whatever) with something that a) generates the new content in wiki format and stores it in the database then b) parses and displays that text.</p> <p>Oh and this should be recursive - the created page may have links to more dynamically generated pages and so on.</p> <p>I will generate the dynamic page based on its name (including category/namespace info to some arbitrary depth).</p> <p>One last thing - it would also be nice (but not essential) to do the creation of some of the dynamic pages upfront by a batch script (mainly for performance because these are pages it may take some time to generate).</p> <p>So my question is which wiki software would be easiest to modify/write a plugin for to do this?</p> <p>(*) Imagine a coredump analyser (think gdb) where you are presented with a list of dumps (maybe stored on some remote machine). You click on a dump, it gives you a list of threads. You click on a thread, it gives you the stack. You click on a stack frame it shows you the memory. You click on a word of memory and it displays the page of memory at that address and so on.</p> <p>As you navigate the dump, you add notes about what you've discovered about the problem to assist you later or to share with your colleagues who might also be looking at the dump.</p> <p>A few months later, the dump may have disappeared from the remote machine (takes a lot of space to archive all these dumps) but now you come across a similar problem. You enter one of the function names from a stack trace in your recent dump into the wiki search box and you retrieve the saved info about the previous occurrence.</p> <p>Update: thanks for all the answers. I may actually go with MediaWiki. It looks as though I can create an <a href="http://www.mediawiki.org/wiki/Category:ArticleViewHeader_extensions" rel="nofollow noreferrer">ArticleViewHeader extension</a> that can then call <a href="http://organicdesign.co.nz/MediaWiki_code_snippets#Edit_or_create" rel="nofollow noreferrer">doEdit</a> to create the page if it doesn't yet exist. There is a <a href="http://www.mediawiki.org/wiki/Extension:VirtualPage" rel="nofollow noreferrer">VirtualPage extension</a> that appears to do something similar.</p>
<p>I've seen this done with <a href="http://www.pmwiki.org/" rel="nofollow noreferrer">pmwiki</a>.</p>
<p>The direct answer to your question is: Almost any OpenSource Wiki should be easily modifiable - pick the one (wiki or language) you are most familiar with. </p> <p>I known that <a href="http://www.jspwiki.org" rel="nofollow noreferrer">jspwiki</a> provides this feature out of the box if I understood your question correctly. It's currently in apaches incubator. Check an <a href="http://sandbox.jspwiki.org" rel="nofollow noreferrer">JspWiki's Sandbox</a>.</p>
23,930
<p>I have a field on a table in MS Access, tblMyTable.SomeID, and I want to set the default value as a user preference in tblUserPref.DefaultSomeID. It doesn't appear that I can set the default value to use a query in the table definition of tblMyTable. I have a form where records are entered into tblMyTable. I've tried to set the default value of the field on the form, but doesn't seem to accept a query either. So, as a last resort, I'm trying to do it with VBA. I can query the value that I want in VBA, but I can't figure out which event to attach the code to.</p> <p>I want to run the code whenever a new blank record is opened in the form, before the user starts to type into it. I do not want to run the code when an existing record is opened or edited. However, if the code runs for both new blank records and for existing records, I can probably code around that. So far, all of the events I have tried on the field and on the form itself have not run when I wanted them to. Can anyone suggest which event I should use, and on which object?</p>
<p>I'm not certain I've understood the problem, but I think you're asking to insert a value in the field that is drawn from a different table, based on some runtime information (such as the user name). In that case, you could use the domain lookup function, DLookup(), and you'd pass it the name of the field you want returned, the name of the table or query you're looking it up from, and the criteria for limiting the result to one row (which would, I assume, depend on values you can gather at runtime). That DLookup() formula could then be set permanently as the default value on the form control, and would not cause the form to be dirtied before you've created a real record.</p> <p>Of course, I may have completely misinterpreted what you're trying to do, so this may not work, but you seemed to want to look something up in a recordset and use the result as your value for new records, and DLookup() would allow you to do that without any coding at all (as well as having the benefit of not dirtying the record prematurely).</p>
<p>He're a suggested alternative approach. Rather than explicitly INSERTing the default when the user has not specified an explicit value, instead leave that value as missing (I'd probably model this in a dedicated table and model the missing value by, well, not INSERTing a row, but I know many people aren't averse to having many nullable columns in their tables). Then you can replace the missing value in a <em>query</em>. This may or may not be valid in your application, as I say just another approach to handling missing data :)</p>
19,082
<p>Are there any ways to secure stored procedure consistency at the software level, so as to be sure that they're going to do what they're expected to do?</p> <p>I'm reluctant to use sprocs because reading and modifying them is so easy as long as you have administrative access to the computer and a copy of Management Studio Express. This is a common environment in a lot of installations where the clients own the server, and previous experience has taught me that clients (or competition) can't be trusted to keep their grubby hands off the database.</p> <p>If a stored procedure can be modified to do anything, unless the software does constant checking, it could be silently made to do things that it shouldn't, and it would be none the wiser. This makes me feel really uncomfortable - to know I'm not in control over what the software does. </p> <p>Is this a valid concern? </p>
<p>Its possible to encrypt stored procedures using the <a href="http://msdn.microsoft.com/en-us/library/aa258259(SQL.80).aspx" rel="nofollow noreferrer">WITH ENCRYPTION</a> hint - there are cons such as the stored proc then being extremely difficult to decrypt.</p> <p>Another option would be to use an ORM tool (or similar) that generates the SQL code dynamically e.g. Linq to SQL/Entities, NHibernate etc</p> <p>Or you could just make sure that the client is aware that the system will no longer be supported if any modifications have been made at a DB level - this may be enough incentive for them not to meddle.</p>
<p>I use Stored Procedures as 'interfaces' .Apart from the performance benefits (Stored procs almost always outperform ad hoc queries) , it allows loose coupling between my db and the UI code. </p>
49,915
<p>I upgraded to a dual Mk9 extruder, and quickly discovered how critical it is to get the ends of both nozzles exactly level with each other -- that is, equally distant from the build plate at all times. Otherwise the lower one will crash against the plastic just extruded by the higher one.</p> <p>So, what's a good procedure for getting the nozzles accurately level? About all I've figure out is to move the heads down close to Z=0, and then run X and Y back and forth and eyeball and adjust; then move even closer to Z=0 and repeat. Is there a better / more efficient way?</p>
<ol> <li>Make sure that the <strong>bed is level</strong>. As the saying goes, a level bed is next to godliness or something like that. Pay extra attention to the direction the nozzles are offset by (if one nozzle is offset on the X-axis, pay extra attention to the bed leveling along the X-axis). <a href="http://wiki.solidoodle.com/leveling-the-print-bed" rel="noreferrer">This can be done with just one nozzle and a business card or piece of paper</a>.</li> <li>Use a <strong>bubble level</strong> to get the nozzles about right. Move your z-axis up a bit and put a bubble level against the nozzles. Adjust as necessary so it's exactly level. The nozzles should be level enough that the bubble stays in the middle.</li> <li>Fine-tune it with a <strong>business card</strong>. When you home the z- axis, you should be able to just fit a business card under both nozzles with a moderate amount of resistance. Don't force the card. If sliding the business card under produces a different amount of resistance for one nozzle than for another, adjust the nozzle a <em>tiny</em> amount. You can also use an index card or playing card.</li> <li>Once it passes the card test, try a test print. If it doesn't work, make sure your bed is level, your nozzle offset is correct in the slicing software, and try calibrating with an index card again. If the nozzles become way off, try the bubble level again.</li> </ol> <p>As for physically adjusting the level, another answer suggests shims made from aluminum foil, which work well. Personally, my extruder was off-level by almost exactly 1mm, so a pair of washers worked nicely for that.</p> <p>Happy printing!</p> <p>Leveling with a bubble:</p> <p><a href="https://i.stack.imgur.com/O1IDe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/O1IDe.jpg" alt="Almost level, sorry for the bad lighting"></a></p>
<p>Another option, that I found was the simplest one that worked for me: </p> <ol> <li>Level your bed using just the first nozzle (temporarily lock the 2nd nozzle higher than the 1st one).</li> <li>Move the printhead at the center of the bed</li> <li>Loosen the grub screws on both nozzles (IMPORTANT, don't skip this step)</li> <li>If you're not using a glass bed, temporarily clip a sheet of glass on your bed.</li> <li>Home the Z-Axis</li> <li>Move the the head sideways, front and back a few times just to be sure (X, Y)</li> <li>Move the printhead back at the center</li> <li>Lock the grub screws on both nozzles. Lock them slowly alternating between the top and bottom screws. Also make sure the wirings don't pull on the head (it's actually better if they push the nozzles down).</li> <li>Relevel the bed, this time checking with the 2 nozzles</li> </ol> <p>The sheet of glass ensures a completely flat and solid surface, on top of your properly leveled bed.</p> <p>Try the above in case nothing else works for you.</p>
155
<p>I have a self-signed root certificate with just the code signing extension (no other extensions) in my Mac keychain; I use it to sign all code coming out of ∞labs using Apple's codesign tool and it works great.</p> <p>I was looking to expand myself a little and doing some Java development. I know Apple provides a KeyStore implementation that reads from the Keychain, and I can list all certificates I have in the 'chain with:</p> <pre><code>keytool -list -provider com.apple.crypto.provider.Apple -storetype KeychainStore -keystore NONE -v </code></pre> <p>However, whenever I try to use jarsigner to sign a simple test JAR file, I end up with:</p> <pre><code>$ jarsigner -keystore NONE -storetype KeychainStore -providerName Apple a.jar infinitelabs_codesigning_2 Enter Passphrase for keystore: &lt;omitted&gt; jarsigner: Certificate chain not found for: infinitelabs_codesigning_2. infinitelabs_codesigning_2 must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain. </code></pre> <p>What am I doing wrong?</p> <p>(The certificate was created following <a href="http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Procedures/chapter_3_section_2.html#//apple_ref/doc/uid/TP40005929-CH4-SW1" rel="noreferrer">Apple's instructions for obtaining a signing identity</a>.)</p>
<p>I think that your keystore entry alias must be wrong. Are you using the alias name of a keystore object with an entry type of "keyEntry"? The same command works perfectly for me.</p> <p>From the jarsigner man page:</p> <blockquote> <p>When using jarsigner to sign a JAR file, you must specify the alias for the keystore entry containing the private key needed to generate the signature.</p> </blockquote>
<p>Have you tried to export the key from the apple keychain and import it via keytool? Perhaps Apple hasn't properly integrated keytool with their keychain (not like they have a stellar track record with supporting Java).</p> <p>Edit:</p> <p>Hmm... I just tried taking a key that worked from the java store that I imported into the apple keychain (has a private/public key) and it doesn't work. So ether my importing is wrong, you cannot access the apple Keychain in this way, or something else is going wrong :-)</p>
15,069
<p>A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.</p> <p>For example, given the interface:</p> <pre><code>public interface IAnything { void m1(); void m2(); void m3(); } </code></pre> <p>the following abstract class gets merrily compiled without a warning or an error:</p> <pre><code>public abstract class AbstractThing implements IAnything { public void m1() {} public void m3() {} } </code></pre> <p>Can you explain why?</p>
<p>That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.</p> <p>Following your example code, try making a subclass of <code>AbstractThing</code> without implementing the <code>m2</code> method and see what errors the compiler gives you. It will force you to implement this method.</p>
<p>Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.</p>
24,089
<p>I've come across a few different applications that monitor my usage while on the computer, but what have you used, and like? whether it be writing down your activities in a composition notbook or install an app that reports silently to a server? what do you like?</p>
<p>For explicit time tracking for projects I use <a href="http://slimtimer.com" rel="nofollow noreferrer">SlimTimer</a>. I also run <a href="http://www.rescuetime.com/" rel="nofollow noreferrer">RescueTime</a> to track my time implicitly, but I end up not looking at that data very often.</p>
<p>I prefer writing the times down using pen and paper. That way you can more fairly weigh things that would have been miscalculated if you were recording them with a stopwatch or timer.</p> <p>If you start on something and have to get up for a few minutes, a timer may count that toward your working time had you neglected to stop or pause the timer. The good-old pen and paper are going to more accurately show which tasks you focused most of your time and energy on...not just the ones that you started earliest and ended latest. It may not be 100% accurate, but neither is the timer if you don't use it properly.</p> <p>I have used both in the past, and find that there are problems with both, but I prefer the pen and paper method.</p>
9,893
<p>My Django app has a Person table, which contains the following text in a field named <code>details</code>:</p> <p><code>&lt;script&gt;alert('Hello');&lt;/script&gt;</code></p> <p>When I call <code>PersonForm.details</code> in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed). I'm confused by this behavior because I always thought <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow noreferrer">Django 1.0 autoescaped</a> template content by default.</p> <p>Any idea what may be going on here?</p> <p><strong>UPDATE:</strong> Here's the snippet from my template. Nothing terribly sexy:</p> <pre><code>{{ person_form.details }} </code></pre> <p><strong>UPDATE 2:</strong> I have tried <code>escape</code>, <code>force-escape</code>, and <code>escapejs</code>. None of these work.</p>
<p>You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):</p> <pre><code>{{ value|safe }} </code></pre> <p>Could you post a sample of the template? Might make it easier to see what's wrong</p> <p><strong>[Edit]</strong> ..or are you saying that you <em>want</em> it to escape the values (make them safe)? Have you tried manually escaping the field:</p> <pre><code>{{ value|escape }} </code></pre> <p><strong>[Edit2]</strong> Maybe <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escapejs" rel="noreferrer">escapejs from the Django Project docs</a> is relevent:</p> <pre><code>escapejs New in Django 1.0. Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON. </code></pre> <p><strong>[Edit3]</strong> What about force_escape:</p> <pre><code> {{ value|force_escape }} </code></pre> <p>...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)</p>
<p>Found the problem. The JSON string I'm using to render data to some Ext widgets is the culprit. Big thanks to Jon Cage. Answer accepted despite the problem being caused by another source.</p>
18,608
<p>I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?</p>
<p>Hmmm, isn't simply overriding Form.ShowWithoutActivation enough?</p> <pre><code>protected override bool ShowWithoutActivation { get { return true; } } </code></pre> <p>And if you don't want the user to click this notification window either, you can override CreateParams:</p> <pre><code>protected override CreateParams CreateParams { get { CreateParams baseParams = base.CreateParams; const int WS_EX_NOACTIVATE = 0x08000000; const int WS_EX_TOOLWINDOW = 0x00000080; baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW ); return baseParams; } } </code></pre>
<p>When you create a new form using </p> <pre><code>Form f = new Form(); f.ShowDialog(); </code></pre> <p>it steals focus because your code can't continue executing on the main form until this form is closed.</p> <p>The exception is by using threading to create a new form then Form.Show(). Make sure the thread is globally visible though, because if you declare it within a function, as soon as your function exits, your thread will end and the form will disappear.</p>
18,881
<p>I just wonder what options there are to properly measure/profile/optimize ASP.net 2.0 Web Parts, especially the ones for Sharepoint 2007?</p> <p>As Web Parts are a layer on another layer of technology, getting resource usage, open handles and stuff only for the web part seems to be a bit difficult.</p> <p>Does anyone know some good tools or practices for profiling and optimizing web parts?</p>
<p>Back when we started with SP2003, we used to worry about not closing connection in apps or web parts. We used the following query to check if the base number of connections (not counting the initial spike) would increase as the app is used on the development server:</p> <p>SELECT hostname, sysdatabases.name , sysprocesses.status, last_batch from sysprocesses, sysdatabases where sysprocesses.dbid = sysdatabases.dbid and nt_username = '<strong>SP Service Account</strong>' and (hostname='<strong>WFE1</strong>' or hostname='<strong>WFE2</strong>') and sysprocesses.dbid = <strong>10</strong> order by last_batch desc</p> <p>(replace the bolded values with those appropriate for your environment)</p> <p>We haven't tried this since the upgrade to MOSS though.</p>
<p>I have found seperating out all the business logic in to a seperate DLL that is easily unit testable has been the easiest method for me. But to be honest there is really no good way that I have found, besides what I have just mentioned. The same has been true for me with Facebook applications recently. I think this is common for any application that runs inside of another platform. Especially when performance and testing where never a goal when the platform developers started to build the system.</p>
4,020
<p>Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks</p>
<p>You mention that :</p> <blockquote> <p>but both .net and php web applications are on different servers</p> </blockquote> <p>Are both applications running under the same domain name? (ie: www.mydomain.com) or are they on different domains?</p> <p>If they're on the same domain, then you can do what you're trying to do in PHP by using the $_COOKIE variable. Just get the cookie's value by </p> <pre><code>$myCookie = $_COOKIE["cookie_name"]; </code></pre> <p>Then you can do whatever you want with the value of $myCookie. </p> <p>But if they're on different domains (ie: foo.mydomain.com and bar.mydomain.com), you cannot access the cookie from both sites. The web browser will only send a cookie to pages on the domain that set the cookie. However, if you originally set the cookie with only the top-level domain (mydomain.com), then sub-domains (anything.mydomain.com) should be able to read the cookie.</p>
<p>any cookie given to a browser will be readable by server processing the request --- they're language agnostic.</p> <p>try $_COOKIE in PHP </p>
11,342
<p>A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.</p>
<p>I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using:</p> <pre><code>p4 changes -s submitted -m1 </code></pre> <p>then sync to that change and record it in the revision info. The reason is as follows. Although <a href="https://portal.perforce.com/s/article/3458" rel="nofollow noreferrer">Perforce recommends the following</a> to determine the changelist to which the workspace is synced:</p> <pre><code>p4 changes -m1 @clientname </code></pre> <p>they note a few gotchas:</p> <ul> <li>This only works if you have not submitted anything from the workspace in question.</li> <li>It is also possible that a client workspace is not synced to any specific changelist.</li> </ul> <p>and there's an additional gotcha they don't mention:</p> <ul> <li>If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files).</li> </ul> <p>If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed:</p> <pre><code>p4 sync -n @changelist_number </code></pre>
<p>I am not sure if you got the answer you needed but I had a similar problem. The goal was to write in our logger the specific version of the project. The problem was that while we are making our own makefile, the overall build system is controlled by our configuration management. This means that all the solutions which say "sync to something then do something" don't really work and I didn't want to manually change the version whenever we commit (a sure source for errors). The solution (which is actually hinted in some of the answers above) is this: in our makefile, I do p4 changes -m1 "./...#have" The result for this is Change change_number on date by user@client 'msg' I simply create the message into a string which is printed by the logger (the change number is the important element but the other is also useful to quickly decide if a certain version contains changes you know you made yourself without going to perforce to check). Hope this helps.</p>
6,920
<p>Problem:<br/></p> <ol> <li>html file on local server (inside our organization) with link to an exe on the same server.</li> <li>clicking the link runs the exe on the client. Instead I want it to offer downloading it.</li> </ol> <p>Tried so far:<br/></p> <ol> <li>Changed permissions on the exe's virtual directory to be read and script.</li> <li>Added Content-disposition header on the exe's directory.</li> <li>I can't change settings in the browser. It's intended for a lot of people to consume.</li> </ol>
<p>You need to set <code>content-disposition</code> in the HTTP header.</p> <p><a href="http://support.microsoft.com/kb/260519" rel="nofollow noreferrer">This Microsoft Knowledge Base entry</a> has more detail on how to do this.</p>
<p>Whether a file is downloaded or opened automatically is a browser, not a server, side setting.</p> <p>The other way of doing it would be to change the MIME type for the file to something like application/octet-stream or similar to try and force your browser to download it.</p>
10,791
<p>Sorry if this is a little off-topic for regular stackoverflow questions, but we're tearing our hair out on this one. We've got a batch of about 3500 3-page PDFs to print (all ok so far) the problem we've got is that it's vital they print in a specific order (ascending by filename). Our spooler seems to randomize the printrun. Any ideas on a way to either solve this the old fashioned way or point me in the right direction to fix this programatically?</p> <p>TIA</p>
<p>Thanks all, I some advice over a techrepublic with regards to a printer setting called 'Print spooled documents first' unticking the box seems to have honoured the order the files were sent.</p>
<p>You should be able to use a PDF library and some simple-ish scripting to turn them into one unholy document. One PDF to rule them all, one PDF to find them, one PDF to bring them all, and in the darkness bind them... so to speak.</p> <p>Edit: As an easier option, you can get software that will do your evil bidding for you. The simplest/cheapest method I've seen so far is through <a href="http://www.pdfsam.org/?page_id=32" rel="nofollow noreferrer">PDFSam</a>. And if you give the developer a Euro (or more, your prerogative) you get a better version. Not sure what's in it apart from encryption though.</p>
48,030
<p>I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:</p> <pre><code>var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) { var td = document.createElement('td'); var select = document.createElement('select'); select.setAttribute("...", "..."); select.onchange = function() { onStatusChanged(select, callid, anotherid); }; td.appendChild(select); } </code></pre> <p>When the <code>onchange</code> event is fired for a <code>&lt;select&gt;</code> element however, it seems like the same values are being passed to the <code>onStatusChanged()</code> method for every <code>&lt;select&gt;</code> in the table (I've verified that in each iteration of the loop, <code>callid</code> and <code>anotherid</code> are being given new, distinct values). </p> <p>I suspect this is occuring because of the nature of how I am setting the event handler, with the <code>select.onchange = function()</code> syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by <code>callid</code> and <code>anotherid</code> is the value set in the last iteration, not the value set at the individual iteration.</p> <p>Is there a way that I can copy the value of the parameters I am passing to <code>onStatusChanged()</code>?</p> <p><em>I've changed the title to better reflect the question and the accepted answer.</em></p>
<p>You do, indeed, need to implement a closure here. This <em>should</em> work (let me know - I didn't test it)</p> <pre><code>var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) { var td = document.createElement('td'); var select = document.createElement('select'); select.setAttribute("...", "..."); select.onchange = function(s,c,a) { return function() { onStatusChanged(s,c,a); } }(select, callid, anotherid); td.appendChild(select); } </code></pre>
<p>Just change the &quot;var&quot; in the for loop to &quot;let&quot; and it works like a charm.</p> <p>reference: <a href="https://softauthor.com/javascript-for-loop-click-event-issues-solutions/" rel="nofollow noreferrer">JavaScript For Loop Click Event Solution #4</a></p>
44,418
<p>For obvious productivity reasons, I make an effort of learning and using as many of the keyboard shortcuts for the various Re# commands. </p> <p>However, it seems that the unit test runner does not have any associated shortcut keys. I want to be able to select certain tests and be able to run or debug them without resorting to grabbing the mouse each time. Is using the mouse my only option?</p>
<p>ReSharper adds items to Visual Studio's keyboard settings dialog box.</p> <p>Go to: </p> <blockquote> <p>Tools -> Options, Environment -> Keyboard</p> </blockquote> <p>In the search bar, type "resharper" and see the vast options that you can control with the keyboard.</p> <p>Specifically, there is one to launch the unit test explorer window, and there's a couple called</p> <ul> <li>ReSharper.ReSharper_UnitTest_RunSolution</li> <li>ReSharper.ReSharper_UnitTest_RunContext</li> </ul> <p>that are likely what you need.</p>
<p>It writes shortcuts in itself or website. Run Unit Tests: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>R</kbd><br> Debug Unit Tests: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>D</kbd><br> Run All Tests From Solution: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>Ctrl</kbd>+<kbd>L</kbd><br> Run Current Session: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>Y</kbd><br> Repeat Previous Run: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>T</kbd><br> Append Tests To Session: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>Ctrl</kbd>+<kbd>A</kbd><br> Create New Session: <kbd>Ctrl</kbd>+<kbd>T</kbd>, <kbd>N</kbd><br> Unit Tests: <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd><br> Unit Tests Session: <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>R</kbd><br> <a href="https://www.jetbrains.com/help/resharper/Reference__Keyboard_Shortcuts.html#unit_testing" rel="nofollow noreferrer">https://www.jetbrains.com/help/resharper/Reference__Keyboard_Shortcuts.html#unit_testing</a></p> <p><a href="https://i.stack.imgur.com/kT8e4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kT8e4.png" alt="enter image description here" /></a></p>
21,115
<p>Can we achieve 100% decoupling between components of a system or different systems that communicate with each other? I don't think its possible. If two systems communicate with each other then there should be some degree of coupling between them. Am I right?</p>
<p>If components are 100% decoupled, it means that they don't communicate with each other.</p> <p>Actually there are <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" rel="nofollow noreferrer">different types of coupling</a>. But the general idea is that objects are not coupled if they don't depend on each other.</p>
<p>You can achieve that. Think of two components that communicate with each other through network. One component can run on Windows while other on Unix. Isn't that 100% decoupling?</p>
9,586
<p>What's the best way to implement user controls that require AJAX callbacks? </p> <p>I want to accomplish a few things:</p> <ul> <li>Have events done in the browser (eg, drag and drop) trigger an AJAX notification that can raise a control event, which causes code on the page using the control to do whatever it needs to do (eg, change a value in a database). </li> <li>Have partial updates (NOT using an updatepanel) that can do things like populate an auto-complete dropdown underneath a textbox. </li> <li>Implement a single user control that is generic enough to be reused on several pages</li> <li>Avoid having to implement logic on the page itself that passes events back to the control, because that is repetitive and hard to maintain </li> </ul> <p>I'm using jQuery for most of the client side stuff, but for the actual AJAX calls I don't really care if it's jQuery or the ASP AJAX libraries. </p> <p>Effectively what would be perfect is PageMethods on the user control, that would be easily callable from client-side script. Unfortunately, as far as I'm aware, pagemethods do not work on user controls.</p> <hr> <p>I'll use an autocomplete control as an example: </p> <p>I should be able to put the autocomplete control on the page, and then in the page code, have eg:</p> <pre><code>Public Sub HandleLookup(ByVal input As String, ByRef list As List(Of String) Handles MyControl.LookupEntries list = New List(Of String) ' Query database for list of items.. For Each item as String in FullItemList If item.StartsWith(input) then list.Add(item) Next Return list End Sub </code></pre> <p>And do nothing else .. the rest of the code should be in the usercontrol. </p> <hr> <p>Note, the controls I'm trying to make are much more specific than eg, autocomplete. They do not exist in any 3rd party libraries and I really need to be able to make them myself.</p>
<p>Look into implementing ICallbackEventHandler in your Page -- it's a simple way to make a call back to a page function from JavaScript.</p> <p>Here's a good tutorial:</p> <p><a href="http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119" rel="nofollow noreferrer">http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119</a></p>
<p>You might want to check out; <a href="http://ra-ajax.org/samples/Combining.aspx" rel="nofollow noreferrer">Ra-Ajax UserControl Sample</a> and combine that knowledge with <a href="http://ra-ajax.org/samples/Behaviors.aspx" rel="nofollow noreferrer">Ra-Ajax Drag and Drop</a></p> <p>Click the "Show code" C# icon to the left to see the usage of the code...</p>
25,941
<p>Environment: Rails 2.2.2, Oracle 10g</p> <p>Most of the columns declared "date" in my ActiveRecord models are exactly that: dates: they don't care about time at all.</p> <p>So with a model declared thus:#</p> <pre><code>class MyDateOnlyModel &lt; ActiveRecord::Migration def self.up create_table :my_date_only_model do |t| t.date :effective_date t.timestamps end end end </code></pre> <p>writing a test like this:</p> <pre><code>test_date = Date.new(2008,12,05) MyDateOnlyModel.create!(:effective_date =&gt; test_date) assert_equal test_date, MyDateOnlyModel.find(:first).effective_date </code></pre> <p>should pass, shouldn't it? (Assuming I didn't mess anything up transcribing the above, of course)</p> <p>But it doesn't - not quite. I get this:</p> <pre><code>&lt;Fri, 05 Dec 2008&gt; expected but was &lt;Fri, 05 Dec 2008 00:00:00 UTC +00:00&gt;. </code></pre> <p>So I put a date into the database and got ... well what <em>did</em> I get?</p> <pre><code>puts MyDateOnlyModel.find(:first).eff_date.class </code></pre> <p>tells me I actually got a <code>ActiveSupport::TimeWithZone</code>. Which wasn't what I wanted at all.</p> <p>Is there a simple way to tell ActiveRecord that some (not all) columns are <code>Date</code>s and only <code>Date</code>s?</p> <p>UPDATE: more complaining...</p> <p>Yes, I could use to_date:</p> <pre><code>assert_equal test_date, MyDateOnlyModel.find(:first).effective_date.to_date </code></pre> <p>works fine. But that's what I'm trying to avoid. I asked AR to make me a date, I want a date back.</p> <p>And I could add a method to my class, effective_date_as_date - that works too. But surely it's not impossible to just get a date, dagnabbit.</p> <p><strong>PRE-ACCEPTANCE UPDATE</strong></p> <p>Eventually I realised why this was a particular problem with Oracle: there is no distinction between DATE and DATETIME, so ActiveRecord can't figure out unaided whether a time of zero means midnight (possibly with time zone corrections) or just the date. Bah. Stupid Oracle. So I'm going to have either to go down the plugin route, change my database (tempting, so very tempting) or continue with the to_date/to_time mess I have at present.</p>
<p>The answer is now to create a <code>@ClassRule</code> within your suite. The rule will be invoked before or after (depending on how you implement it) each test class is run. There are a few different base classes you can extend/implement. What is nice about class rules is that if you do not implement them as anonymous classes then you can reuse the code!</p> <p>Here is an article about them: <a href="http://java.dzone.com/articles/junit-49-class-and-suite-level-rules">http://java.dzone.com/articles/junit-49-class-and-suite-level-rules</a> </p> <p>Here is some sample code to illustrate their use. Yes, it is trivial, but it should illustrate the life-cycle well enough for you to get started. </p> <p>First the suite definition:</p> <pre><code>import org.junit.*; import org.junit.rules.ExternalResource; import org.junit.runners.Suite; import org.junit.runner.RunWith; @RunWith( Suite.class ) @Suite.SuiteClasses( { RuleTest.class, } ) public class RuleSuite{ private static int bCount = 0; private static int aCount = 0; @ClassRule public static ExternalResource testRule = new ExternalResource(){ @Override protected void before() throws Throwable{ System.err.println( "before test class: " + ++bCount ); sss = "asdf"; }; @Override protected void after(){ System.err.println( "after test class: " + ++aCount ); }; }; public static String sss; } </code></pre> <p>And now the test class definition:</p> <pre><code>import static org.junit.Assert.*; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; public class RuleTest { @Test public void asdf1(){ assertNotNull( "A value should've been set by a rule.", RuleSuite.sss ); } @Test public void asdf2(){ assertEquals( "This value should be set by the rule.", "asdf", RuleSuite.sss ); } } </code></pre>
<p>As an aside, it's a bad idea to have unit tests actually calling external resources like webservices, databases, etc.</p> <p>Unit tests should be super-quick to run and a delay of 'a couple of minutes' for each run of the suite will mean it won't be run as much as it should.</p> <p>My advice:</p> <p>Look at mocking external dependencies in unit tests with something like EasyMock (<a href="http://www.easymock.org/" rel="nofollow noreferrer">http://www.easymock.org/</a>).</p> <p>Build a seperate suite of integration tests with something like Fitnesse (<a href="http://fitnesse.org/" rel="nofollow noreferrer">http://fitnesse.org/</a>) or a homegrown solution that runs against a test environment and which is continually up.</p>
45,520
<p>We are looking for a free solution to compress our SQL Server backups for SQL Server 2005. I am aware of SQL Safe freeware edition, but I was wondering what others thought of storing backup files in compressed folders to achieve the desired result. This would allow us to use the native SQL backup tasks and native windows compression, thereby eliminating the need for third-party products.</p> <p>I have not used compressed folders for anything in the past. Is this a viable idea? Are there any foreseeable issues with the integrity of the backups in a compressed folder?</p>
<p>Quick hint from google: <a href="http://clay.lenharts.net/blog/2008/01/28/backing-up-to-a-ntfs-compressed-folder/" rel="nofollow noreferrer">backing-up-to-a-ntfs-compressed-folder</a>. Seems that database size may create problems.</p> <p>What about freeware solutions then you can run 7zip in scheduled batch after backup, should handle big files correctly. You should move backups <em>outta</em> production server anyway :)</p>
<p>I use <a href="http://www.2brightsparks.com/downloads.html#freeware" rel="nofollow noreferrer">Syncback Freeware</a> to automatically copy and compress the files to another folder. You save tons of space this way. I have been doing this for several years and it has worked perfectly.</p>
38,970
<p>I would like to be able to spawn a linux process that would only have access to stdin, stdout, and stderr (nothing more and nothing less). Can I do this at the process level itself? I am also implicitly stating (oxymoron) that I don't want the spawned process to be able to change the "thing" that the other end of the stream points to. </p> <p>Metaphorically:</p> <ul> <li>the process has a input pipe that comes from somewhere, it cannot change where the pipe starts from, so it cannot control where input comes from.</li> <li>the process has output and error pipes that go somewhere, it cannot change where the other end of the output pipes point to, so it cannot control where output goes to.</li> <li>it cannot create any new pipes.</li> </ul> <p>I am also currently looking at SElinux. Would this allow me to create a process that only had access to these three streams? Thank you.</p>
<p>As stated in another answer SELinux does have various permissions that help lock down any process.</p> <p>The kernel manages access to certain objects (with associated set of permissions) for example a file is an object, a directory is an object, a unix datagram socket is an object and many more.</p> <p>probably the easiest thing to do is write a little policy. Luckily SELinux is deny by default so run your program and look at the logs for SELinux denials and only allow your program to do what you want. In other words you would avoid adding permission that involve object classes like msg (messages in a systemV message queue), msgq (SystemV message queue itself), sem (semaphores), shm (shared memory) and probably others depending on what it does. </p> <p>I suggest the first time you do it have SELinux on but in permissive (see setenforce 0)</p> <p>I would also suggest tools to help you build some policy, it can be a bit overwhelming to write basically raw M4</p>
<p>If you're root, you can chroot to a directory, drop privileges so that you no longer have filesystem write access, then exec. That will prevent a program from creating new files. But there's no way to prevent a program from creating pipes and sockets (well, no-sockets is possible with SELinux), and there's no way to prevent a program from rearranging and closing its file descriptors.</p> <p>Well, I suppose you could use <code>ptrace</code> to trap all syscalls, and only allow the ones that you approve of, so when I say "there's no way" I mean "there's no easy way". This incurs a noticable overhead, but if you're careful enough you can make it secure. The <a href="http://sourceforge.net/projects/strace/" rel="nofollow noreferrer"><code>strace</code></a> or <a href="http://wiki.virtualsquare.org/index.php/UMview" rel="nofollow noreferrer">UMview</a> projects may be good starting points if you decide to go down this path.</p>
22,381
<p>I needed to re-install my computer but I didn't think about exporting the data from mysql 5. </p> <p>How do I get the data from the old installation into the new installation, is this just copying the data directory or do I have to take other steps to get to the data?</p>
<p>For MyISAM tables you can generally get away with copying them across. (Whilst the server's stopped, obviously.) For InnoDB, it can work, but you'll have to have the same basic block size settings. If you can use the same major version of MySQL and the same my.cnf you stand a good chance of having it work.</p> <p>Afterwards it's a good idea to ensure the tables are rebuilt (eg. using ALTER TABLE), and make a note to mysqldump properly next time because none of this is supported or guaranteed to work!</p>
<p>I would export your data as a sql file from mysql (ie: with phpmyadmin) and then import it into the new installation. Your db should be built and filled with data pretty easily.</p> <p>You said that you "didn't think about exporting the data". Does that mean you don't have access to the old installation any more?</p>
31,238
<p>I have now 1gb ram at work(i hope that will change soon) and jboss takes almost half of it and that is too much, i turned off logging to file, what more can i do to reduce memory usage ?</p>
<p>You can limit the maximum memory used using the -Xmx parameter, as in any java process. Edit the $JBOSS_HOME/bin/run.conf and set this parameter to the desired maximum memory you want to allocate to JBoss.</p> <p>Also, you can remove from the deploy directory of the server configuration you are using, the services you are not using. To be sure about what files you must remove in order to remove unused services, check the <a href="http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta500/html/index.html" rel="noreferrer">documentation</a></p>
<p>You could try using the latest version of JBoss (version 6). I think it uses less memory, though I could be wrong.</p>
31,558
<p>I have several databases, one of which contains utility functions called from the other databases. Is there a way in the utility functions to determine which database a function is being called from?</p>
<p>Did you try: SELECT db_name() ?</p>
<p>You'd run a trace in SQL Profiler, but that might not give you complete list. So, you also should query the information_schema.routines &amp; information_schema.tables views in each database to see which tables and view use that function and could call it and compare the list to the trace. </p>
40,862
<p>I'm the leader of a small web development team, and I have a feeling that we will have a couple telecommuters joining the team pretty soon (either new employees, or existing employees that will begin telecommuting). Any idea how to effectively manage and collaborate with developers working remotely?</p> <p>Most of the work we do is client-driven. We're doing agile development (or our version of it, anyway), but since it's mostly client work, we can't really assign a feature to a developer and set them lose for a week or two like we might be able to with a desktop app or something like that. The biggest problem we have when people occasionally work from home is collaborating - it's tough to work together without the benefit of a whiteboard and hand-waving.</p> <p>It seems like software development is perfect for telecommuting, but I haven't been able to find many good resources about the practical aspects of working remotely within a development team. Has anyone else had any experience with this?</p>
<p>I freelance a lot and in doing so work remotely a lot of the time. These are the things that make my life as easy as possible (so might be things you want to "suggest"). I think they're mostly common-sense, but you never know...</p> <ol> <li><p>[Everyone] Communicate well. When you're having a conversation face-to-face, you can be verbose and explain things in a round-a-bout way. When you're limited to email, IM and phone, all parties need to explain themselves fully but succinctly. I find that summarising long emails into request/action points goes a long way towards getting things done well.</p></li> <li><p>[Everyone] Have a online project tracking space. Most tend to use a ticket system or some description, where action points can be assigned to members. It wouldn't hurt to use this same space for tracking emails and sharing whiteboard ideas. Most online project apps allow for that by default.</p></li> <li><p>[Management] Don't pester devs. If you need something urgently, set the status of the ticket, give them a call and chase them up later on in the day. <strong>Half-hourly emails asking "is it done yet?" does more harm than good!</strong></p></li> <li><p>[Management] Make sure messages get passed along. If a dev says "somebody needs to do something", it's your job to make sure the message is passed along to the right person. There are few things more annoying than passing a message to a project manager for them to accidentally sit on it. I don't want to have to chase up things like that because it's, frankly, not what I'm being paid for.</p></li> <li><p>[Management] Make sure people have something to do. If you send them home with nothing on their task list that they can immediately action, they're not going to put in the effort. It's a damned sight harder to keep yourself productive at home than it is in the office when you've little or nothing that you can do. You might have to juggle tasks if there's a blocker.</p></li> </ol>
<p>I've generally used some time of community based software such as a wiki, blog, or forum to handle the documentation areas. We also have a Cisco phone system and use some capabilities of the system. I'd also recommend live meeting or webex to do frequent team meetings. Skype and IM clients such as Live Messenger are also good tools. For the short status updates, twitter does the trick.</p>
15,051
<p>I am working in a company that develops computing kernels. Their design is simple : it's a library in c++ which only has one function available to compute results out of available data. </p> <p>There are essentially four steps in every one of these kernels :</p> <ul> <li><p>retrieve xml content (format has been defined in an XSD file) and store into objects</p></li> <li><p>define a mathematical problem using the above objects</p></li> <li><p>use a solver to find a solution (or the optimal solution)</p></li> <li><p>export results into a new xml file</p></li> </ul> <p>Currently, our resources are very much model-oriented in terms of capabilities and interests (and not so much into programming). Obviously we want to make the environment as friendly and efficient as possible. We are evaluating the use of c# using LinQ and <a href="http://code.msdn.microsoft.com/solverfoundation" rel="nofollow noreferrer">Microsoft Solver Foundation</a> as a replacement for c++ and home-made tools.</p> <p>My questions are :</p> <ul> <li><p>Can LinQ and Solver Foundation do all that ? How easy would it be to use ?</p></li> <li><p>What would be the gains/losses of changing the environment for our resources (time to learn and rewrite, efficiency, etc.) ?</p></li> <li><p>Are there other interesting options that i should consider ?</p></li> </ul>
<p>You would get huge benefits by switching to C#/LINQ in terms of working with the XML and even with a lot of the math. There would be a slight learning curve (so that's a con), but in just a couple of weeks, I'm sure you'll be laughing at how much easier coding C#3/LINQ is.</p> <p>I say this from experience... and I specifically mentioned "C#3" (as opposed to just C#), because when I convinced my fellow C#2 colleagues to move to 3/LINQ, they experienced the above :)</p>
<p>I say that any C++ application developer should take a good look at C#. In my opinion, many of the problems that you solve in C++ can be solved much quicker in C#. It is not a hard language to learn coming from C++ at all. I would say, before you decide, check out C# for a week or so and see how much <em>you</em> like it.</p> <p>Good luck :)</p>
32,020
<p>I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.</p> <p>I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.</p> <pre><code>TableA Column1, Column2, Column3 </code></pre> <p>SQL Statement to ruturn</p> <pre><code>ResultA Value of Column1 Value of Column2 Value of Column3 </code></pre> <hr> <p><strong>@Kevin:</strong> I've had a google search on the topic but alot of the example where overly complex for my example, <strong>are you able to help further?</strong></p> <p>@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3</p>
<p>You should take a look at the UNPIVOT clause.</p> <p><strong>Update1</strong>: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure.</p> <p><strong>Update2</strong>: Found it: <a href="http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx" rel="nofollow noreferrer">http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms180026.aspx" rel="nofollow noreferrer">UNION</a> should be your friend:</p> <pre><code>SELECT Column1 FROM table WHERE idColumn = 1 UNION ALL SELECT Column2 FROM table WHERE idColumn = 1 UNION ALL SELECT Column3 FROM table WHERE idColumn = 1 </code></pre> <p>but it can <a href="http://blog.falafel.com/2006/01/20/TSQLTipAvoidUNION.aspx" rel="nofollow noreferrer">also be your foe</a> on large result sets.</p>
2,559
<p>What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?</p> <pre><code>$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = ???($row['my_timestamp']); echo $formatted_date; </code></pre>
<p>You could use MySQL to do this for you,</p> <pre><code>$result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = $row['my_timestamp']; echo $formatted_date; </code></pre> <p>Or use PHP,</p> <pre><code>$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = strftime('%B %d, %y', $row['my_timestamp']); echo $formatted_date; </code></pre>
<p>I use: </p> <p>date("F j, Y", strtotime($row['my_timestamp']))</p> <p>or you can change the SELECT to: DATE_FORMAT(field,'%d %M, %Y') as datetime</p>
29,450
<p>Please let me know how can I remove default banner of web server from response - Apache http1.1 coyote</p>
<p>If you're talking about the generated line at the bottom of apache generated pages, you have to update your httpd.conf with this command:</p> <pre><code>ServerSignature Off </code></pre> <p>See <a href="http://httpd.apache.org/docs/2.2/mod/core.html#serversignature" rel="nofollow noreferrer">http://httpd.apache.org/docs/2.2/mod/core.html#serversignature</a></p> <p>Be careful, theses informations are also sent through HTTP headers. You can alter them via this <a href="http://httpd.apache.org/docs/2.2/mod/core.html#servertokens" rel="nofollow noreferrer">directive</a></p> <p>About Coyote, AFAIK there is no key to hide these info.</p>
<p>In server.xml there will be a <code>&lt;Connector&gt;</code> element. Add a <code>server</code> attribute to it. For example:</p> <pre><code>&lt;Connector executor="tomcatThreadPool" port="80" protocol="HTTP/1.1" server=" " ... /&gt; </code></pre> <p>Unfortunately, setting the <code>server</code> attribute to an empty string doesn't cause any change in behavior. Setting <code>server</code> to a string with a single space results in a header like:</p> <pre><code>Server: </code></pre> <p>While not optimal, it's progress.</p>
41,836
<p>I have a lot of spare intel linux servers laying around (hundreds) and want to use them for a distributed file system in a web hosting and file sharing environment. This isn't for a HPC application, so high performance isn't critical. The main requirement is high availability, if one server goes offline, the data stored on it's hard drives is still available from other nodes. It must run over TCP/IP and provide standard POSIX file permissions.</p> <p>I've looked at the following:</p> <ul> <li><p>Lustre (<a href="http://wiki.lustre.org/index.php?title=Main_Page" rel="noreferrer">http://wiki.lustre.org/index.php?title=Main_Page</a>): Comes <em>really</em> close, but it doesn't provide redundancy for data on a node. You must make the data HA using RAID or DRBD. Supported by Sun and Open Source, so it should be around for a while</p></li> <li><p>gfarm (<a href="http://datafarm.apgrid.org/" rel="noreferrer">http://datafarm.apgrid.org/</a>): Looks like it provides the redundancy but at the cost of complexity and maintainability. Not as well supported as Lustre.</p></li> </ul> <p>Does anyone have any experience with these or any other systems that might work?</p>
<p>check also <a href="http://www.gluster.org/" rel="noreferrer">GlusterFS</a></p> <p><strong>Edit (Aug-2012):</strong> <a href="http://ceph.com/" rel="noreferrer">Ceph</a> is finally getting ready. Recently the authors formed <a href="http://www.inktank.com/" rel="noreferrer">Inktank</a>, an independent company to sell commercial support for it. According to some presentaions, the mountable POSIX-compliant filesystem is the uppermost layer and not really tested yet, but the lower layers are being used in production for some time now. </p> <p>The interesting part is the RADOS layer, which presents an object-based storage with both a 'native' access via the <code>librados</code> library (available for several languages) and an Amazon S3-compatible RESP API. Either one makes it more than adequate for adding massive storage to a web service.</p> <p><a href="https://www.youtube.com/watch?v=UXcZ2bnnGZg" rel="noreferrer">This video</a> is a good description of the philosophy, architecture, capabilities and current status.</p>
<p><a href="http://ceph.newdream.net/" rel="nofollow noreferrer">Ceph</a> looks to be a promising new-ish entry into the arena. The site claims it's not ready for production use yet though. </p>
33,804
<p>Is there a way to implement a singleton object in C++ that is:</p> <ol> <li>Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once).</li> <li>Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables).</li> </ol> <p>(I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..)</p> <hr> <p>Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being <strong>the answer</strong>). There appears to be two broad solutions:</p> <ol> <li>Use static initialisation (as opposed to dynamic initialisation) of a POD static variable, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already.</li> <li>Use some other library function like <a href="http://opengroup.org/onlinepubs/007908799/xsh/pthread_once.html" rel="noreferrer">pthread_once</a> or <a href="http://www.boost.org/doc/libs/1_33_1/doc/html/call_once.html" rel="noreferrer">boost::call_once</a>. These I certainly didn't know about - and am very grateful for the answers posted.</li> </ol>
<p>Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization.</p> <p>As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is executed. This makes it possible to use a statically-initialized mutex to synchronize creation of the singleton.</p> <p>From the 2003 revision of the C++ standard:</p> <blockquote> <p>Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.</p> </blockquote> <p>If you <em>know</em> that you will be using this singleton during the initialization of other static objects, I think you'll find that synchronization is a non-issue. To the best of my knowledge, all major compilers initialize static objects in a single thread, so thread-safety during static initialization. You can declare your singleton pointer to be NULL, and then check to see if it's been initialized before you use it.</p> <p>However, this assumes that you <em>know</em> that you'll use this singleton during static initialization. This is also not guaranteed by the standard, so if you want to be completely safe, use a statically-initialized mutex.</p> <p>Edit: Chris's suggestion to use an atomic compare-and-swap would certainly work. If portability is not an issue (and creating additional temporary singletons is not a problem), then it is a slightly lower overhead solution.</p>
<p>I suppose saying don't do this because it's not safe and will probably break more often than just initializing this stuff in <code>main()</code> isn't going to be that popular.</p> <p>(And yes, I know that suggesting that means you shouldn't attempt to do interesting stuff in constructors of global objects. That's the point.)</p>
2,860
<p>I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?</p>
<p><code>List&lt;T&gt;</code> was introduced with generics in .NET 2.0:</p> <pre><code>using System.Collections.Generic; var list = new List&lt;int&gt;(); list.Add(1); list.Add("string"); //compile-time error! int i = list[0]; </code></pre>
<p>If you have to use ArrayList and can't start using List, and you know the type of every element in that ArrayList you can do:</p> <pre><code> string[] stringArray = myArrayList.ToArray(typeof(string)) as string[]; </code></pre> <p>If something in myArrayList wasn't a string, in this case, you would get an InvalidCastException.</p> <p>If you can, I would start using List as OregonGhost mentioned.</p>
17,434
<p>I have an external stylesheet that has specific IE-hacks. Every so often my site will fail to build due to these hacks (it is the hash-hack; for example <strong><code>#margin-top:-2px;</code></strong>). This is the error:</p> <blockquote> <p>Unexpected character sequence. Expected a property name for the " : " declaration</p> </blockquote> <p>I haven't found out a concrete way to get the errors to stop, VS2008 just seems to stop caring after a while. I found <a href="http://www.carlj.ca/2008/01/05/adding-css-colors-to-visual-studio-2005/" rel="nofollow noreferrer">this article</a>, but I am unsure of how to edit the files properly so this "error" (since it is legal syntax) will not pop up again.</p>
<p>I'm not sure about 2008, but in 2005 (IIRC), you can go to:</p> <pre><code> Tools | Options | Text Editor | CSS | CSS Specific </code></pre> <p>and then untick <strong>Detect Errors</strong></p> <p>I remember having exactly the same problem on 100% valid CSS which MS didn't recognise (big shock), flicked this switch and forgot about the problem forever more.</p>
<p>The easiest thing is to close the file in the editor and it should stop complaining. </p>
42,893
<p>I am attempting to write a basic slicer for some objects I am working with. I need to write a custom slicer as the objects are not polygonal based (they are implicit objects) and therefore cannot be plugged into slic3r. I can easily obtain the perimeter/shell of the objects I am working with and have a few successful prints. What I am having trouble with is how to add infill. I think the biggest hurdle is simply my inability to frame the question properly. How do current software tackle this problem?</p> <p>I don't know of my current approach is feasible but if I have a collection of vectors that represent the path around the outside of the object and a collection of vectors that represent an arbitrarily large infill pattern is there a way to union the two paths together to from an outer path (the object shell) and an inner path that is the infill pattern cut out in the shape of the object?</p> <p>EDIT:</p> <p>Sorry for the lack of clarification. So lets say I cut out the infill pattern to match the inside of the object. How do I then intelligently connect all the broken infill segments together to form an efficient path that doesn't cross gaps or mess the object up in any way? </p>
<p>The answer to this is pretty much basic algebra: The software tackles the problem by using a set of functions that generate the infill pattern for ALL the build volume, then discard anything outside the shells. Which is determined by algebra:</p> <h1>Basics</h1> <h3>Outline Function</h3> <p>Assume the outline of the body is a function <span class="math-container">$O(l)$</span> that has a parameter <span class="math-container">$l$</span> for its length. This function can be calculated into XY coordinates, giving us <span class="math-container">$y\mapsto O^{xy}(x)$</span>, that is parameterized after <span class="math-container">$x$</span>, and should give us the values of <span class="math-container">$y$</span> for a closed function <span class="math-container">$O(l)$</span>.</p> <h3>Infill Functions</h3> <p>Now, let's generate a function for infill pattern. Let's make it easy for us and use a diagonals pattern: <span class="math-container">$I_n(x)=x+n\times d$</span> where <span class="math-container">$d$</span> is a fixed parameter for &quot;distance to last line&quot; and <span class="math-container">$n\in\mathbb Z$</span> is the number of the line with 0 passing the origin.</p> <h3>Comparation: Outline=Infill</h3> <p>Now basic algebra! Let the computer solve for each <span class="math-container">$n$</span> the term <span class="math-container">$O(x)=I_n(x)$</span>. The result should be (in the best case) paired points, all on the linear function <span class="math-container">$I_n(x)$</span>. Sort these points by their correlating <span class="math-container">$n$</span> value first, then the <span class="math-container">$x$</span> values.</p> <h1>Dealing with the results</h1> <p>Let's assume we have some banana shape and our solutions for n=0 are like this: <span class="math-container">$P_{i=1 \to 4}=\{\{1,1\},\{2,2\},\{3,3\},\{4,4\}\}$</span></p> <h2>Modeling starter</h2> <p>On the most simple cases, we hope to only have paired results - the outline is closed and thus each line passing it has to <em>cut</em> it in multiples of two. Because we don't allow geometry to be below <span class="math-container">$\{0,0\}$</span>, the line in this example will pass into the body at the first solution of these points and pass out of it at the second and so on. Generally: It moves in at odd and exits at even i. So our infill lines in the example need to connect <span class="math-container">$\{1,1\} \to \{2,2\}$</span> and <span class="math-container">$\{3,3\} \to \{4,4\}$</span>.</p> <h1>Enhancing the Modeling</h1> <h2>checking for tangents</h2> <p>Now, we might have an odd number of points that solve O(x)=I<sub>n</sub>(x) for a given n. Let's assume <span class="math-container">$P_{i=1 \to 5}=\{1,1\},\{2,2\},\{3,3\},\{4,4\},\{5,5\}$</span>.</p> <p>Now we need to be careful as one of these points is guaranteed to be a point in which <span class="math-container">$I_n(x)$</span> is a tangent at of <span class="math-container">$O(x)$</span>. So, we need to know the first differential of <span class="math-container">$O(x)$</span> in the points, which is the tangent at <span class="math-container">$O(x)$</span>. But we don't need to solve <em>all</em> the points: We know the first should enter and the last exit the body, so we need (for most cases) to only solve this for the points <span class="math-container">$P_i$</span> with <span class="math-container">$i=2 \to i_{max-1}$</span>. When <span class="math-container">$O'(x)=I_n(x)$</span>, we got a tangent and remove this point from the list of points to connect with infill lines.</p> <p>Because we could have several tangents in a set of points, this check has to be done for all sets of points to eliminate these points.</p> <p>Also, I used the &quot;usually&quot; there by intent: there are cases where the first or last point is a tangent, and because it is easier to cose, we should run the elimination process over all <span class="math-container">$P_1 \to P_{max}$</span>!</p> <p>The new, reduced set of points will be a paired list: <span class="math-container">$Q_{i=1 \to 4}=\{1,1\},\{2,2\},\{4,4\},\{5,5\}$</span>. The Infil connects <span class="math-container">$Q_1 \to Q_2$</span> and <span class="math-container">$Q_3\to Q_4$</span>.</p> <h2>Turning Points into vectors</h2> <p>Now, we have our points <span class="math-container">$Q_1$</span> and <span class="math-container">$Q_2$</span> (or any other pair of <span class="math-container">$n \land n+1$</span>, where n is an element of the odd numbers), both on <span class="math-container">$I_{n=0}(x)$</span>. How to connect? Easy! <span class="math-container">$I{n=0}$</span> is a function, most likely a linear one. Along this line has to be our connecting line from <span class="math-container">$Q_1\to Q_2$</span>, so the movement we have to plot is the function of our pattern between the points. For a simple, linear pattern this would be:</p> <p><span class="math-container">$L_1=\frac{I(x)}{|I(x)|} \times |\vec{Q_2}-\vec{Q_1}|+\vec{Q1}$</span></p> <h1>Optimisation</h1> <h2>Sorting properly</h2> <p>Now, we have a set of Lines <span class="math-container">$L_n$</span>, where, as established in the last paragraph, n is an odd number declaring it has the lower-end <span class="math-container">$Q_n$</span>, and the upper-end <span class="math-container">$Q_{n+1}$</span>. How do we sort these lines smartly so we have the least movement? Let's take a look at our lists:</p> <ul> <li>The list of P<sub>i</sub>, which contains all tangential points and end points. Not very helpful.</li> <li>The reduced list of <span class="math-container">$Q_{n}$</span>, which contains all the start and end points; it is <em>sorted</em> in a way that odd numbers are starts, and even ends.</li> <li>The list of <span class="math-container">$L_n$</span> with i always being an odd number, that contains the movement paths (=lines) from each <span class="math-container">$Q_{n}$</span> to its corresponding <span class="math-container">$Q_{n+1}$</span></li> </ul> <h3>Shortest movement between prints?</h3> <p>Now, let's do some math again: What is the closest <span class="math-container">$Q_{a}$</span> to the <span class="math-container">$Q_{n+1}$</span> we did end at after doing the <span class="math-container">$L_n$</span> movement? Well, first of all, we need to make sure we don't get back to already moved paths so let's make a new list <span class="math-container">$R_{i}$</span>, which contains all the <span class="math-container">$Q_{i}$</span> we have not yet moved to.</p> <p>So what is the closest <span class="math-container">$R_{i}$</span> to the end point of the path <span class="math-container">$L_e$</span> we just moved? Well, easy! Solve <span class="math-container">$min|R_i-L_e|$</span> with i being all the odd numbers in the list of <span class="math-container">$R_{i}$</span> and <span class="math-container">$L_e$</span> the point where the printhead was sent to at the end of the last movement</p> <h3>fewest direction changes?</h3> <p>Always moving just the shortest distance might create a large number of direction changes. So it might be a good idea to keep the point-lists sorted by the parameter n of the function <span class="math-container">$l_n(x)$</span> that created the points in the first place, and run down that list from minimum n that generated points (which can be below 0) to the maximum n that generated points.</p> <h3>optimizing direction changes &amp; movement paths</h3> <p>Now, we have 2 approaches that pretty much only follow the pattern. However, we might make our average movement paths more efficient by using a simple trick:</p> <p>Up to now, all our line functions <span class="math-container">$l_n(x)$</span> had the same vector and just a different starting point to one another. So all the starts were on one side of the body, all the ends on the opposite. With a very simple trick on the infill function we can generate a group of functions that alternate the sides of the end-points between each line, jsut by adding an inverse element:</p> <p><span class="math-container">$L_n(x)=-1^n\times l_n(x)$</span></p> <p>Now, after all the movements with the same <span class="math-container">$n$</span> are done, check for the closest starting point (which should be on the same side, but is not necessary the neighboring line), and go down that line fully, eradicating these points from the list of remaining points <span class="math-container">$R_{i}$</span>. Once back on the side we <em>started</em> first at, we look for the closest unused point again, run down that line, rinse and repeat.</p>
<p>simple answer is math but you know that for sure</p> <p>more descriptive answer (but still simple and with no math) is more or less as follows</p> <ul> <li>slice an object with a plane to form (calculate) outline perimeter</li> <li>create a grid of infill according to your needs (ie: lines, grids or honeycombs)</li> <li>calculate where outline cuts your grid of infill</li> <li>abandon all what is outside</li> <li>sort cut points in some order ("some" is definitely the hardest task)</li> <li>join points according to your sort</li> </ul> <p>and voila ;)</p> <p>of course there is many details not mentioned in such description as distance between perimeter and infill, layer thickness and many others this is just very naive and silly description but it's just to direct you where to go further</p> <p>generally there is great library which you could give a try</p> <p><a href="https://sourceforge.net/projects/jsclipper/" rel="nofollow noreferrer">https://sourceforge.net/projects/jsclipper/</a></p> <p><strong>edit</strong></p> <p>simple sort (counter)clockwise could be like this</p> <ul> <li>set center point of the object (perimeter)</li> <li>start from 1200 hour and calculate module and angle of each cut-point</li> <li>sort them by angle</li> </ul> <p>it's still very simple and it's working only for convex set</p>
1,029
<p>What's the easiest way to truncate a C++ <code>float</code> variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?</p>
<p>First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable. </p> <p>But here are a couple of solutions to the problem that will probably meet your need:</p> <p>Probably the better method but less efficient:</p> <pre><code>char sz[64]; double lf = 0.600000002; sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000 double lf2 = atof(sz); //lf == 0.600000002; //lf2 == 0.6000 printf("%.4lf", lf2); //print 0.6000 </code></pre> <p>The more efficient way, but probably less precise:</p> <pre><code>double lf = 0.600000002; int iSigned = lf &gt; 0? 1: -1; unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate lf = (((double)uiTemp)/pow(10,4) * iSigned); </code></pre>
<p>Here is a function using the advice in other answers and an example of its use:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; static void Truncate(double&amp; d, unsigned int numberOfDecimalsToKeep); int main(int, char*[]) { double a = 1.23456789; unsigned int numDigits = 3; std::cout &lt;&lt; a &lt;&lt; std::endl; Truncate(a,3); std::cout &lt;&lt; a &lt;&lt; std::endl; return 0; } void Truncate(double&amp; d, unsigned int numberOfDecimalsToKeep) { d = roundf(d * powf(10, numberOfDecimalsToKeep)) / powf(10, numberOfDecimalsToKeep); } </code></pre>
39,062
<p>What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?</p>
<h2>From Perl</h2> <p><a href="http://search.cpan.org/perldoc?Inline::C" rel="nofollow noreferrer">Inline::C</a><br> <a href="http://search.cpan.org/perldoc?Inline::CPP" rel="nofollow noreferrer">Inline::CPP</a><br> <a href="http://search.cpan.org/perldoc?Inline::Java" rel="nofollow noreferrer">Inline::Java</a><br> <a href="http://search.cpan.org/perldoc?Inline::Python" rel="nofollow noreferrer">Inline::Python</a><br> <a href="http://search.cpan.org/perldoc?Inline::Lua" rel="nofollow noreferrer">Inline::Lua</a></p> <p>excerpt from <a href="http://search.cpan.org/dist/Inline/C/C-Cookbook.pod" rel="nofollow noreferrer">Inline::C-Cookbook</a>:</p> <pre><code>use Inline C =&gt; &lt;&lt;'END_C'; void greet() { printf(&quot;Hello, world\n&quot;); } END_C greet; </code></pre>
<p>Use Swig, it allows you to generate code for multiple languages that calls any C/C++ functions. <a href="http://www.swig.org/" rel="nofollow noreferrer">http://www.swig.org/</a></p>
34,642
<p>In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?</p>
<p>I don't understand your question (what are files?, what's your table structure?), but here goes a simple sample:</p> <pre><code>&gt;&gt;&gt; import MySQLdb &gt;&gt;&gt; conn = MySQLdb.connect(host="localhost", user="root", password="merlin", db="files") &gt;&gt;&gt; cursor = conn.cursor() &gt;&gt;&gt; cursor.execute("SELECT * FROM files") 5L &gt;&gt;&gt; rows = cursor.fetchall() &gt;&gt;&gt; cursor.execute("CREATE TABLE destination (file varchar(255))") 0L &gt;&gt;&gt; for row in rows: ... cursor.execute("INSERT INTO destination VALUES (%s)" % row[0]) ... 1L 1L 1L 1L 1L </code></pre>
<p>Here is an example, assuming you have created the table you want to move to, with descriptive names:</p> <pre><code>&gt;&gt;&gt; import MySQLdb &gt;&gt;&gt; conn = MySQLdb.connect(user='username', db='dbname') &gt;&gt;&gt; cur = conn.cursor() &gt;&gt;&gt; cur.execute('select files from old_table where conditions=met') &gt;&gt;&gt; a = cur.fetchall() &gt;&gt;&gt; for item in a: ... cur.execute('update new_table set new_field = %s' % item) # `item` should be tuple with one value, else use "(item,)" with comma </code></pre>
27,783
<p>Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)</p> <p>I basically have a <code>StyledWindow</code> control, which is essentially a glorified <code>Panel</code> with ability to do other bits (like add borders etc).</p> <p>Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:</p> <pre><code> protected override void CreateChildControls() { _panel = new Panel(); if (_editable != null) _editable.InstantiateIn(_panel); _regions = new List&lt;IAttributeAccessor&gt;(); _regions.Add(_panel); } </code></pre> <p>The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the <code>RegisterClientScriptBlock</code> is the only reason I need the page ref).</p> <p>Now, this was causing &quot;object null&quot; errors, but I localized this down to the render method, which was of course trying to call the method against the [null] <code>Page</code> object.</p> <p>What's confusing me is that the control works fine as a standalone, but when placed in the <code>StyledWindow</code> it all goes horribly wrong!</p> <p><strong>So, it looks like I am missing something in either my <code>StyledWindow</code> or <code>ChildControl</code>. Any ideas?</strong></p> <h2>Update</h2> <p>As <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824">Brad Wilson</a> quite rightly pointed out, you do not see the controls being added to the <code>Controls</code> collection. This is what the <code>_panel</code> is for, this was there to handle that for me, basically then override <code>Controls</code> (I got this from a guide somewhere):</p> <pre><code> Panel _panel; // Sub-Control to store the &quot;Content&quot;. public override ControlCollection Controls { get { EnsureChildControls(); return _panel.Controls; } } </code></pre> <p>I hope that helps clarify things. Apologies.</p> <h2>Update Following <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299">Longhorn213's Answer</a></h2> <p>Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.</p> <p>The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's <code>OnLoad</code> event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D</p> <p>Thanks for your help guys, appreciated :)</p>
<p>I don't see you adding your controls to the Controls collection anywhere, which would explain why they can't access the Page (since they've never been officially placed on the page).</p>
<p>Right, I got playing and I figured that there was something wrong with my control instantiation, since Longhorn was right, I should be able to create script references at <code>OnLoad</code> (and I couldn't), and Brad was right in that I need to ensure my <code>Controls</code> hierarchy was maintained by adding to the <code>Controls</code> collection of the composite.</p> <p>So, I had two things here:</p> <ol> <li>I had overriden the <code>Controls</code> property accessor for the composite to return this <code>Panel</code>'s Controls collection since I dont want to have to go <code>ctl.Controls[0].Controls[0]</code> to get to the actual control I want. <strong>I have removed this, but I need to get this sorted.</strong></li> <li>I had not added the <code>Panel</code> to the <code>Controls</code> collection, <strong>I have now done this.</strong></li> </ol> <p>So, it now works, however, <strong>how do I get the <code>Controls</code> property for the composite to return the items in the <code>Panel</code>, rather than the <code>Panel</code> itself?</strong></p>
15,555
<p>How to set internationalization to a <code>DateTimepicker</code> or <code>Calendar WinForm</code> control in .Net when the desire culture is different to the one installed in the PC?</p>
<p>It doesn't seem to be possible to change the culture. See this <a href="http://support.microsoft.com/Default.aspx?scid=kb%3ben-us%3b889834&amp;x=18&amp;y=19" rel="noreferrer">KB article</a>. </p>
<p>I think there is detour.</p> <ol> <li>set event handler "ValueChanged"</li> <li><p>code</p> <pre><code>dateTimePicker.Format = DateTimePickerFormat.Custom; string[] formats = dateTimePicker.Value.GetDateTimeFormats(Application.CurrentCulture); dateTimePicker.CustomFormat = formats[0]; </code></pre></li> </ol>
29,953
<p>I'm a Linux guy and I'm used to copying directory trees with <code>cp -a</code>. OS X doesn't have <code>-a</code> option on <code>cp</code>... but it does have the <code>ditto</code> command. I'm reading the man on <code>ditto</code> now, but is there anything I should specifically be looking out for?</p>
<p>According to the <strong>cp</strong> man page <strong>cp -a</strong> is the same as <strong>cp -dpR</strong> which is</p> <pre><code>-p = preserve mode,ownership,timestamps -R = recursive -d = no dereference and preserve links </code></pre> <p>The OS X equivalent would be</p> <p><strong>cp -pPR</strong></p> <pre><code>-p = preserve -R = recursive -P = no symbolic links are followed -- can be added but this is the default behavior </code></pre> <p>The only thing missing is <strong>-d</strong> which I think is the default behavior but I'm not positive.</p> <p>I've never messed with <strong>ditto</strong></p> <p>Edit -- @SoloBold</p> <p><strong>-L</strong> follows symbolic links. <strong>-p</strong> does NOT follow symbolic links. OS X (10.4 at least) has no <strong>-d</strong> option.</p> <p>that is a huge difference.</p>
<p>As j04t pointed out that should be <code>cp -pR</code></p> <p><strike>On OS X, you would do</p> <pre><code>cp -dRL src target </code></pre> <p></strike> cp preserves resources in newer version of OS X (was it 10.3 when that happened?)</p> <p>Hey d is kinda like an upsidedown p, right ;)</p>
19,372
<p>Let's say you have a text file like this one: <a href="http://www.gutenberg.org/files/17921/17921-8.txt" rel="noreferrer">http://www.gutenberg.org/files/17921/17921-8.txt</a></p> <p>Does anyone has a good algorithm, or open-source code, to extract words from a text file? How to get all the words, while avoiding special characters, and keeping things like "it's", etc...</p> <p>I'm working in Java. Thanks</p>
<p>This sounds like the right job for regular expressions. Here is some Java code to give you an idea, in case you don't know how to start:</p> <pre><code>String input = "Input text, with words, punctuation, etc. Well, it's rather short."; Pattern p = Pattern.compile("[\\w']+"); Matcher m = p.matcher(input); while ( m.find() ) { System.out.println(input.substring(m.start(), m.end())); } </code></pre> <p>The pattern <code>[\w']+</code> matches all word characters, and the apostrophe, multiple times. The example string would be printed word-by-word. Have a look at the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html" rel="noreferrer">Java Pattern class documentation</a> to read more.</p>
<p>You could try regex, using a pattern you've made, and run a count the number of times that pattern has been found.</p>
34,873
<p>I'm embedding an IE control into my C++ application. The problem is that although system-wide, ClearType is disabled, IE7 has its own separate setting, and unless I specifically disable that too, text inside the IE control will be antialiased while the rest of the app will not.</p> <p>The same goes for IE7's font size setting.</p> <p>It wouldn't be a problem for me to set up IE7 accordingly, but it would affect the experience of users of my app. Can the IE control's cleartype usage and font size be programmatically controlled?</p>
<p>It would be quite trivial to do this yourself.</p> <ol> <li><p>Create a webform where the user can type in their email address. You could protect it with a captcha to prevent bots from hitting it.</p></li> <li><p>On submission, save the email address to a database along with a GUID, DateTime timestamp and IsActivated bit. The GUID uniquely identifies this subscription. The timestamp states an expiry time that the email address must be confirmed by.</p></li> <li><p>Send an email to the email address with a URL in it like.</p> <p><a href="http://www.example.com/validate.aspx?g=GUID-GOES-HERE" rel="nofollow noreferrer">http://www.example.com/validate.aspx?g=GUID-GOES-HERE</a></p></li> <li><p>If user receives the email in their inbox &amp; clicks the validation link before the timestamp for that GUID/Email expires, then you activate their account.</p></li> <li><p>At regular intervals you could have a job remove rows from the table that have never been activated where the activation window has expired.</p></li> </ol>
<p>There are several levels of email validation and I've got source to do them all. However, I despise your line of business and would never share them with you...</p> <p>Just to clarify - I don't despise you, Jeff... Just your line of business.</p>
36,202
<p>I am trying to create an XML schema representing an 'order' for a shopping cart</p> <p>I want this to completely abstract away my shopping cart's implementation -- and eventually support partners sending us orders using this schema. (yes i'm planning on integrating this schema into our existing cart)</p> <p>It will have original order items, repeat shipping items and domain specific things. I'm quite capable of building this, but i was wondering if there are many things out there like this that I could at least base mine upon. </p> <p>I know there are standards out there for certain schema elements like this, but I've lost track of which are the best/standard and how you might extend them etc.</p> <p>obviously if i want a partner to send me an 'order' i'd like to use a standard if one exists.</p>
<p>UBL (Universal Business Language) defines schemas for business documents (purchase orders, invoices, etc.). It is an OASIS standard, see:</p> <p><a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=ubl" rel="nofollow noreferrer">http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=ubl</a></p>
<p>If you are looking for ideas about how to structure the shopping cart:<br /> <a href="https://stackoverflow.com/questions/360959/database-table-structure-for-shopping-cart">Database Table Structure for Shopping Cart</a></p>
48,815
<p>I have a MySQL (v 5, MyISAM) query that returns different rows depending on date string format.</p> <pre><code>(1) IFNULL(date1, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008-10-31 23:59:59' (2) IFNULL(date1, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008/10/31 23:59:59' (3) date1 &gt; '2008-10-31 23:59:59' (4) date1 &gt; '2008/10/31 23:59:59' </code></pre> <p>'/' vs '-' on RHS of '>' comparisson operator.</p> <pre><code>(1) 75,098 rows *expected* (2) 0 rows *DIFFERENCE* (3) 199 rows *simple case as expected* (4) 199 rows *simple case as expected* </code></pre> <p>Question - Why ?</p>
<p>Short answer: Use <code>CAST(... AS DATE)</code></p> <p>Long answer:</p> <p>From <a href="http://dev.mysql.com/doc/refman/5.0/en/datetime.html" rel="nofollow noreferrer">MySQL DATE type</a>:</p> <blockquote> <p>A “relaxed” syntax is allowed: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '98-12-31 11:30:45', '98.12.31 11+30+45', '98/12/31 11*30*45', and '98@12@31 11^30^45' are equivalent.</p> </blockquote> <p>In your examples 1 and 2 you're using ADDDATE... this will always return a date with a '-' separator, no matter what the input format:</p> <pre><code>+-----------------------------------------------+ | ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY) | +-----------------------------------------------+ | 2008-11-01 23:59:59 | +-----------------------------------------------+ </code></pre> <p>You're also using IFNULL, which loses the type information, so when you compare this it's comparing as strings.</p> <p>What you can do is cast this back to a date:</p> <pre><code>mysql&gt; SELECT IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008/10/31 23:59:59'; +-------------------------------------------------------------------------------------+ | IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008/10/31 23:59:59' | +-------------------------------------------------------------------------------------+ | 0 | +-------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql&gt; SELECT CAST(IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) AS DATE) &gt; '2008/10/31 23:59:59'; +---------------------------------------------------------------------------------------------------+ | CAST(IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) AS DATE) &gt; '2008/10/31 23:59:59' | +---------------------------------------------------------------------------------------------------+ | 1 | +---------------------------------------------------------------------------------------------------+ </code></pre>
<p>I don't know much about mysql but is it possible that the "/"-based date is interpreted as "YYYY/DD/MM" and so is just completely invalid? In SQL Server I would expect an exception in that case, but if mysql substitutes some kind of "invalid date"-value that could maybe explain the difference.</p> <p>YYYY-MM-DD is official ISO format. YYYY/MM/DD I have never heard of.</p>
36,457
<p>I'm trying to serialize a Type object in the following way:</p> <pre><code>Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); </code></pre> <p>When I do this, the call to Serialize throws the following exception: </p> <blockquote> <p>"The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."</p> </blockquote> <p>Is there a way for me to serialize the <code>Type</code> object? Note that I am not trying to serialize the <code>StringBuilder</code> itself, but the <code>Type</code> object containing the metadata about the <code>StringBuilder</code> class.</p>
<p>I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:</p> <pre><code>string typeName = typeof (StringBuilder).FullName; </code></pre> <p>You can then persist this string however needed, then reconstruct the type like this:</p> <pre><code>Type t = Type.GetType(typeName); </code></pre> <p>If you need to create an instance of the type, you can do this:</p> <pre><code>object o = Activator.CreateInstance(t); </code></pre> <p>If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.</p>
<p>Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may have to convert it to a custom class that is marked as such.</p> <pre><code>public abstract class Type : System.Reflection.MemberInfo Member of System Summary: Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types. Attributes: [System.Runtime.InteropServices.ClassInterfaceAttribute(0), System.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type), System.Runtime.InteropServices.ComVisibleAttribute(true)] </code></pre>
3,336
<p>In all of my other .net apps my build process (a mixture of nant and custom tasks) automatically updates the [AssemblyVersionAttribute] AssemblyInfo.cs with the current build number before the call to msbuild, stamping in the build number in the version number.</p> <p>I'm now working on my first BizTalk project and I'd like to do the same thing with the version numbers of the BizTalk assemblies, but I've run into trouble!</p> <p>First of all the aseembly version numbers are stored in the btproj files, so I did some googling and found www.codeplex.com/biztalk which looked like the answer to my problem, but there is a deeper problem!</p> <p>I have a project for my schemas and another for my pipelines, the pipelines project references my schemas project as I have a flat file dis/assemblers. The problem comes when I update the version numbers, as updating them even from within visual studio does not update the pipeline components references to the schemas.</p> <p>So if I update all the version numbers manually in the VS IDE from 1.0.0.0 to 1.1.0.0, the build fails as the pipeline components flat file dis/assemblers still reference the old 1.0.0.0 version of the schemas! They don't automatically update!</p> <p>Is this really a manual process of updating the version numbers of the BizTalk projects in the property pages, then building the projects and manually updating the references to them in the properties of all the pipeline components that reference them?</p> <p>This means that I can't have my build process control the build number part of my version numbers!</p> <p>Or is there a better method of managing the version numbers of the BizTalk assemblies?</p>
<p>I'm sorry to disappoint you but I've been down the exact some road I had to give up. I guess it could be possible to achieve it but it would require a lot of changes to both the binding files and other XML files (as you mentioned and even more if you have published services etc).</p> <p>Maybe it could be possible to wrap all these necessary changes in a build step (a MSBuild step or similar in other build frameworks) - that would be <strong><em>useful!</em></strong></p>
<p>Gutted, thought that might be the case. Maybe BizTalk 2009 projects will play more nicely when updating references when changing version numbers.</p> <p>I started to go through and automate it manually, and when I realised what needed to be done, I took a biiig step back when I realised just how many places I'd have to modify to get it working. Thank god for Undo Checkout.</p> <p>I do have a standard C# class library included in my project (various helper functions), which i am able to update the version number of during my build process, so I'm basically using that one assembly to version the whole application. If anyone wants to know what version is in any environment, check out the version number of that one assembly.</p> <p>Not ideal, but it's working.</p>
33,690
<p>As far as I know resin trays have a Teflon coat that allows prints to stick to the build plate easier than the resin tray but this Teflon coat wears over time. </p> <p>I am new to the SLA scene and am currently troubleshooting a Draken Facture and trying to hone in my setting but my print keep sticking to the bottom of the resin vat. </p> <p>How often should these trays be swapped out to allow for smooth printing?</p>
<p>It depends on tray and resin type you are using.</p> <p><strong>PDMS</strong></p> <p>If you are using PDMS (eg. sylgard 184) coating for your tray. (B9 and similar printers using this type of tray). </p> <p>Life of tray PDMS coating depends mainly on:</p> <ul> <li>How long you print without breathing floor.</li> <li>How reactive is your resin.</li> </ul> <p>You could get 2 3 prints up to 15 20 prints.</p> <p>It is suitable for printing delicate pieces.</p> <p><strong>FEP</strong></p> <p>Large number of manufacturers using FEP.</p> <p>Life of tray largely depends on.</p> <ul> <li>Thickness of FEP</li> <li>Piece sizes and movement speed during early layers.</li> </ul> <p>Usually you could use same tray for couple of hundreds of prints. Optical quality is not comparable to other alternatives but without human error factor you could get almost unlimited prints. Delicate pieces require tough resin.</p> <p><strong>Teflon</strong></p> <p>It is halfway between PDMS and FEP.</p> <p>There are other tray alternatives:</p> <ul> <li>Envision uses special glass you could print on average 50 prints.</li> <li>Carbon 3D uses super expensive oxygen-permeable window.</li> </ul>
<p>I did some research and the life of the resin and resin tray appears to be dependent on how you use it. For example, regarding the resin, 3dfacture states <a href="http://3dfacture.com/faq/" rel="nofollow noreferrer">"We see almost unlimited shelf life of the resin as long as it is kept out of light"</a>.</p> <p>I know you asked about the tray and not the resin; but, the two are inter-coupled to the same fundamental issue. Their lifespan is highly operational dependent. If your printer operates in an environment that have very low ambient UV, the tray will have to be cleaned less because of less resin buildup and replacement and thus less wear. Other factors come into play as well regarding cleaning procedures, usage amount, etc.</p> <p>I think if you want a number you are going to have to run your own experiment in your own environment.</p>
640
<p>I'm just trying to do simple scripting with F#, and Math.PI seems to have 'disappeared'. I've referenced FSharp.PowerPack.dll, but still can't find it.</p>
<p>The constant pi is System.Math.PI, if you want to use, Math.PI just open System, in your fsharp file:</p> <pre><code>open System Math.PI </code></pre>
<p>You know, you could just do this:</p> <pre><code>let PI = 3.141592653589 </code></pre>
45,842
<p>OK, first for context look at the Windows desktop; You can take items (folders, files) on the desktop and drag them around to different places and they "stay" where you dragged them. This seems to be a pretty useful feature to offer users so as to allow them to create their own "groupings" of items.</p> <p>My question is thus: Is there a control in .NET that approximates this behavior with a collection of items?</p> <p>I'm thinking something like a listview in "LargeIcon" mode, but it allows you to drag the icons around to different places inside the control.</p>
<p>You can do this with a standard ListView control by implementing drag-and-drop. Here's a sample control that does this:</p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; public class MyListView : ListView { private Point mItemStartPos; private Point mMouseStartPos; public MyListView() { this.AllowDrop = true; this.View = View.LargeIcon; this.AutoArrange = false; this.DoubleBuffered = true; } protected override void OnDragEnter(DragEventArgs e) { if (e.Data.GetData(typeof(ListViewItem)) != null) e.Effect = DragDropEffects.Move; } protected override void OnItemDrag(ItemDragEventArgs e) { // Start dragging ListViewItem item = e.Item as ListViewItem; mItemStartPos = item.Position; mMouseStartPos = Control.MousePosition; this.DoDragDrop(item, DragDropEffects.Move); } protected override void OnDragOver(DragEventArgs e) { // Move icon ListViewItem item = e.Data.GetData(typeof(ListViewItem)) as ListViewItem; if (item != null) { Point mousePos = Control.MousePosition; item.Position = new Point(mItemStartPos.X + mousePos.X - mMouseStartPos.X, mItemStartPos.Y + mousePos.Y - mMouseStartPos.Y); } } } </code></pre>
<p>Windows uses <code>ListView32</code>, an internal control with drag n' drop placeholder features, custom borders...</p> <p>The icon location can be stored in a XML file, or in the application settings (by putting the XML as string and converting it to file when needed).</p> <p>You can do, for example:</p> <pre><code>&lt;icons&gt; &lt;icon1&gt; &lt;name&gt;Icon1&lt;/name&gt; &lt;text&gt;My PC&lt;/text&gt; &lt;imageIndex&gt;16&lt;/imageIndex&gt; &lt;/icon1&gt; &lt;icon2&gt; ..... &lt;/icon2&gt; ..... &lt;/icons&gt; </code></pre> <p>Lorenzo</p>
28,463
<p>I need to retrieve the browser and OS through php coding.</p> <p>I had used <code>$_SERVER['HTTP_USER_AGENT']</code>, but its shows the following </p> <pre><code>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; IEMB3) </code></pre> <p>How can I separate the browser and OS from the above received value?</p> <p>Please guide me..</p> <p>Thanks in advance.</p>
<p>You could use the <a href="http://code.google.com/p/phpbrowscap/" rel="nofollow noreferrer">Google code Browscap class</a>. It essentially does the same thing as PHP's get_browser(), but you don't have to worry about keeping your browscap.ini up to date.</p> <p>This worked for me:</p> <pre><code>require('Browscap.php'); $browscap = new Browscap('/path/to/cache'); var_dump($browscap-&gt;getBrowser()); </code></pre>
<p>you can use simple explode();</p> <pre><code>&lt;?php $ex=explode(' ',$_SERVER['HTTP_USER_AGENT']); echo 'OS: '.$ex[4].' '.$ex[5].' '.$ex[6].'/n'; echo 'Browser: '.$ex[0]; ?&gt; </code></pre>
44,603
<p>In C#, is it possible to extend a class that has no constructors?</p> <p>Maybe I'm thinking about this incorrectly and just need a kick in the crotch. I have a Silverlight class that extends System.Windows.Media.Transform, With the official release of Silverlight 2, Transform now has no constructor. So, when I compile my class, I get an error saying that 'The type '...Transform' has no constructors defined.'</p> <p>Is it still possible to extend this class in a useful way? If not, I'm going to be drawing an awful lot of sad faces.</p>
<p>The sole constructor to Transform is internal, so you can't derive from it yourself.</p>
<p>Hiding all public constructors is a technique used to prevent subclassing and force developers to use the class as intended. It may be the implementor wants you to use an Adapter or Facade or even a Proxy at the time of extension.</p> <p>There may be important lifecycle details in the constructor that require the use as the original implementor intended, or it may be an oversight by the developer.</p> <p>I've seen attempts at conversion to the Factory pattern where this is done in a manner that prevents subclassing. I.e. there is no protected constructor made available to subclasses. Sometimes advanced object patterns can strain the in-built capabilities of a language.</p>
27,039
<p>I'm using Eclipse as an IDE for Ruby/Rails development (using Aptana plugin). I have one very, very large file that encompasses an initial data load of several thousand rows of data. When this file is open, everything grinds to a halt (on both Windows and Linux), presumably because Eclipse is tied up trying to parse and format/syntax-check the file. Typing in a single word takes upwards of a minute to complete.</p> <p>Is there a way for me flag this file in such a way that Eclipse will skip it for format/syntax checking?</p>
<p>I'm not exactly sure what you are trying to achieve here, but I think what you want is:</p> <pre><code>// query... $records = array(); while($r = mysql_fetch_array($result)) { $records[] = $r; } return $records; </code></pre>
<p>By default <a href="http://it.php.net/mysql_fetch_array" rel="nofollow noreferrer">mysql_fetch_array</a> returns both normal and associative arrays, so you can access the values by position ($result[0]) or by name ($result['user_name'])':</p> <pre><code>array mysql_fetch_array ( resource $result [, int $result_type ] ) </code></pre> <blockquote> <p>result_type: The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH.</p> </blockquote>
45,636
<p>How can I know if a device is supported on a running Linux and if so, which device driver controls it? For instance, <code>lspci</code> on a server (PowerEdge 2900) gives:</p> <pre class="lang-none prettyprint-override"><code>00:00.0 Host bridge: Intel Corporation 5000X Chipset Memory Controller Hub (rev 12) 00:02.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 2 (rev 12) 00:03.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 3 (rev 12) 00:04.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 4 (rev 12) 00:05.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 5 (rev 12) 00:06.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x8 Port 6-7 (rev 12) 00:07.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 7 (rev 12) 00:08.0 System peripheral: Intel Corporation 5000 Series Chipset DMA Engine (rev 12) 00:10.0 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.1 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.2 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:11.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:13.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:15.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:16.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:1c.0 PCI bridge: Intel Corporation 631xESB/632xESB/3100 Chipset PCI Express Root Port 1 (rev 09) 00:1d.0 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #1 (rev 09) 00:1d.1 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09) 00:1d.2 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09) 00:1d.3 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #4 (rev 09) 00:1d.7 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset EHCI USB2 Controller (rev 09) 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev d9) 00:1f.0 ISA bridge: Intel Corporation 631xESB/632xESB/3100 Chipset LPC Interface Controller (rev 09) 00:1f.1 IDE interface: Intel Corporation 631xESB/632xESB IDE Controller (rev 09) 00:1f.2 IDE interface: Intel Corporation 631xESB/632xESB/3100 Chipset SATA IDE Controller (rev 09) 01:00.0 PCI bridge: Intel Corporation 80333 Segment-A PCI Express-to-PCI Express Bridge 01:00.2 PCI bridge: Intel Corporation 80333 Segment-B PCI Express-to-PCI Express Bridge 02:0e.0 RAID bus controller: Dell PowerEdge Expandable RAID controller 5 04:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 05:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 06:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Upstream Port (rev 01) 06:00.3 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express to PCI-X Bridge (rev 01) 07:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01) 07:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01) 08:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 09:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 0b:02.0 Multimedia audio controller: Creative Labs SB Audigy (rev 03) 0b:02.1 Input device controller: Creative Labs SB Audigy Game Port (rev 03) 0b:02.2 FireWire (IEEE 1394): Creative Labs SB Audigy FireWire Port 10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02) </code></pre> <p>How can I find:</p> <ol> <li>which device driver (kernel module) controls each device?</li> <li>which device is controlled by a device driver compiled <em>in</em> the kernel (and not as a module)</li> <li>which device doesn't have a device driver (compiled in or as a module)?</li> </ol> <p>This script (adapted from another in "Linux Kernel in a Nutshell") partially resolves #1:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash for i in $(find /sys/ -name modalias); do echo "----------------------------------" modalias=$(cat $i) echo "$(dirname $i) --&gt; $modalias" /sbin/modprobe --config /dev/null --show-depends $(cat $i) 2&gt;&amp;1 done </code></pre> <p>But there are some problems with it:</p> <ol> <li><p>I don't know of an <em>automated way</em> to convert <code>/sys/devices/pci0000:00/0000:00:1e.0/0000:10:0d.0 --&gt; pci:v00001002d0000515Esv00001028sd000001B1bc03sc00i00</code> to <code>10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)</code></p></li> <li><p>In some cases the devices are internal to the MB and I don't even know a way to find the real name of the device. For example:</p></li> </ol> <pre class="lang-none prettyprint-override"><code>/sys/devices/platform/dcdbas --&gt; platform:dcdbas /sys/devices/platform/iTCO_wdt --&gt; platform:iTCO_wdt /sys/devices/LNXSYSTM:00 --&gt; acpi:LNXSYSTM: /sys/devices/LNXSYSTM:00/device:00/PNP0C33:00 --&gt; acpi:PNP0C33:PNP0C01: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00 --&gt; acpi:PNP0A08:PNP0A03: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0d/PNP0200:00 --&gt; acpi:PNP0200: </code></pre> <p>and many others.</p> <ol start="3"> <li>When the device driver is <em>compiled in</em> (or doesn't exist) the response is <code>FATAL: Module _XXXX_ not found.</code> Indicating there is no module for the device.</li> </ol> <p>In some cases the driver is compiled in (e.g.)</p> <pre><code>/sys/devices/platform/serial8250 --&gt; platform:serial8250 FATAL: Module platform:serial8250 not found. /sys/devices/platform/i8042 --&gt; platform:i8042 FATAL: Module platform:i8042 not found. </code></pre> <p>In other cases, the driver just doesn't exist. But I don't know a way to tell the difference.</p> <p>Does anyone know?</p>
<p>I don't think you can get a 100% clear-cut answer that you can get in Windows device manager.</p> <ul> <li>A device may be controlled by several kernel modules (say <code>nvidia</code> + <code>agpgart</code>).</li> <li>A kernel module may control more than one device (<code>usbhid</code>).</li> <li>You can also have many-to-many relationship (<code>usbcore</code> + <code>usbhid</code>).</li> </ul>
<p>The following script will tell you which dynamically loaded drivers are running, although I would also like an automated way of figuring out which compiled in modules are actually in use also so I could de-bloat my kernel some more.</p> <pre><code>#!/bin/bash /sbin/lsmod | tail -n+2 | cut -d" " -f1 | xargs /sbin/modinfo -n | sort ; </code></pre> <p>I'm not sure how relevent the rest of this is to your question but thought you or others might find it useful. </p> <p>The following code will figure out which .config options control each of the dynamically loaded kernel modules, although I haven't figured out a way to do the same for dynamic modules in the ubuntu lum package yet ( this script is still a work in progress ):</p> <pre><code>#!/usr/bin/perl -w use strict; use Getopt::Long; my ($kernConfigIn, $kernConfigOut, $kernSourceDir, $lumSourceDir, $lumConfigIn, $lumConfigOut, $help); GetOptions( 'ksd=s' =&gt; \$kernSourceDir, 'lsd=s' =&gt; \$lumSourceDir, 'kci=s' =&gt; \$kernConfigIn, 'lci=s' =&gt; \$lumConfigIn, 'kco=s' =&gt; \$kernConfigOut, 'lco=s' =&gt; \$lumConfigOut, 'help' =&gt; \$help); if ($help || !$kernSourceDir || !$lumSourceDir ) { Usage($0); } sub Usage { print "usage error\n"; exit; }; my @modules = `/sbin/lsmod | tail -n+2 | cut -d" " -f1 | xargs /sbin/modinfo -n | sort ;`; my @kconfig; foreach my $module (@modules) { my ($package, $path, $modName) = ( $module =~ m/\/((?:kernel)|(?:ubuntu))\/(.*)\/(.*)\.ko/) ; $package eq 'kernel' ? push @kconfig, kernel($package, $path, $modName) : ubuntu($package, $path, $modName); } # kernel package sub kernel { my ($package, $path, $modName) = @_; my $makefile = $kernSourceDir.$path."/Makefile"; # print "$package, $path, $modName\n"; # print "$makefile\n"; my $option; chomp($option = `cat $makefile | sed -n "s/^obj-\\\$(CONFIG_\\([A-Z0-9_]*\\))\\W*+=.*"$modName"\\.o.*/CONFIG_\\1/p"`); print "$option\n"; return $option; } # deal with lum configs sub ubuntu { } </code></pre> <p>There is a script by Andreas Goelzer which with slight modification will turn off all unused kernel modules in your .config which significantly speeds up your compiles.</p> <p>You can find it here:</p> <p><a href="http://andreas.goelzer.de/kernel-config-based-on-lsmod-output" rel="nofollow noreferrer">http://andreas.goelzer.de/kernel-config-based-on-lsmod-output</a></p>
20,237
<p>What is a good way of parsing command line arguments in Java?</p>
<p>Check these out:</p> <ul> <li><a href="http://commons.apache.org/cli/" rel="noreferrer">http://commons.apache.org/cli/</a></li> <li><a href="http://www.martiansoftware.com/jsap/" rel="noreferrer">http://www.martiansoftware.com/jsap/</a></li> </ul> <p>Or roll your own:</p> <ul> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html</a></li> </ul> <hr /> <p><strong>For instance,</strong> this is how you use <a href="https://mvnrepository.com/artifact/commons-cli/commons-cli/1.3.1" rel="noreferrer"><code>commons-cli</code></a> to parse 2 string arguments:</p> <pre><code>import org.apache.commons.cli.*; public class Main { public static void main(String[] args) throws Exception { Options options = new Options(); Option input = new Option(&quot;i&quot;, &quot;input&quot;, true, &quot;input file path&quot;); input.setRequired(true); options.addOption(input); Option output = new Option(&quot;o&quot;, &quot;output&quot;, true, &quot;output file&quot;); output.setRequired(true); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null;//not a good practice, it serves it purpose try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(&quot;utility-name&quot;, options); System.exit(1); } String inputFilePath = cmd.getOptionValue(&quot;input&quot;); String outputFilePath = cmd.getOptionValue(&quot;output&quot;); System.out.println(inputFilePath); System.out.println(outputFilePath); } } </code></pre> <p>usage from command line:</p> <pre><code>$&gt; java -jar target/my-utility.jar -i asd Missing required option: o usage: utility-name -i,--input &lt;arg&gt; input file path -o,--output &lt;arg&gt; output file </code></pre>
<p>For Spring users, we should mention also <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html" rel="nofollow noreferrer">https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html</a> and his twin brother <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html" rel="nofollow noreferrer">https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html</a> (JOpt implementation of the same functionality). The advantage in Spring is that you can directly bind the command line arguments to attributes, there is an example here <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html" rel="nofollow noreferrer">https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html</a></p>
47,990
<p>I have to develop a tool for monitoring helpdesk agents. I can figure out how to capture keyboard events and mouse events; however I need to capture the control that emitted/consumed the event too. Is it possible to find that out?</p>
<p>You need windows hooks to pick up the events. These are really the province of native code. Try asking again with Win32 tag replacing the C# tag.</p>
<p>I used the code from <a href="http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx" rel="nofollow noreferrer">Stephen Toub's blog</a> to add a shortcut to my application in the system tray. The comments were quite useful as well.</p>
24,608
<p>Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.</p>
<p>Try this:</p> <pre><code> StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName (); </code></pre> <p>Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out.</p> <p><strong>Edit:</strong> Pulling in @John Meagher's comment, which is a great idea:</p> <blockquote> <p>To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the "main" Thread to determine what the main class is. This will work even if your class is not running in the main thread.</p> </blockquote>
<p>Or you could just use getClass(). You can do something like:</p> <pre><code>public class Foo { public static final String PROGNAME = new Foo().getClass().getName(); } </code></pre> <p>And then PROGNAME will be available anywhere inside Foo. If you're not in a static context, it gets easier as you could use this:</p> <pre><code>String myProgramName = this.getClass().getName(); </code></pre>
6,329