input
stringlengths
51
42.3k
output
stringlengths
18
55k
Looking for an algorithm to spit out a sequence of numbers in a (pseudo) random order <p>Suppose I have a sequence of numbers: {n, n+1, n+2, ... n + m}</p> <p>Without storing the numbers ahead of time I want to create a function f(), which given the sequence {1,2,3,...m} will spit out the original set in a random (or at least pseudo random) order.</p> <p>For example assume my sequence is {10, 11, 12, 13, 14, 15, 16, 17}</p> <pre> f(1) could yield 14 f(2) could yield 17 f(3) could yield 13 f(4) could yield 10 f(5) could yield 16 f(6) could yield 15 f(7) could yield 11 f(8) could yield 12 </pre> <p>At one point in the past a co-worker showed me a mathematical algorithm that was able to do this, but I have since forgotten almost everything about it other than it existed. I remember that you had to have the sequence in advance, and generate some constants from the sequence which were used in the function. And for those wondering, I have sadly lost contact with that co-worker.</p> <p>This <a href="http://stackoverflow.com/questions/693880/create-random-number-sequence-with-no-repeats">question's</a> answers looks close to what I want, but I am not sure if the answers allow me to constrain the output to a specific sequence ahead of time.</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>To clarify a little more I don't want to store the original sequence, or the shuffled sequence. I want to generate a function f() from the original sequence.</p> <p>What is frustrating is that I have seen this, I just cannot remember enough about it to find it again with google.</p> <p>The Fisher-Yates algorithm is great for permuting or shuffling a deck, but it is not what I am looking for.</p>
<p>There is a simple function that generates a permutation of <code>[0..m-1]</code> for a given <code>m</code>. Just pick a number <code>k</code>, relatively prime to <code>m</code> and let <code>f(i)=(k*i) mod m</code>. This always generates a permutation (no repeats on <code>0&lt;=i&lt;m</code>). It works better if <code>k</code> is larger than <code>m</code>.</p> <p>For example, m=20, let k=137 (Python code, <code>%</code> means modulo):</p> <pre><code> &gt;&gt;&gt; [(137*i) % 20 for i in range(20)] [0, 17, 14, 11, 8, 5, 2, 19, 16, 13, 10, 7, 4, 1, 18, 15, 12, 9, 6, 3] </code></pre> <p>This is a very simple PRNG, no guarantees about its statistical properties. </p>
Managing concurrent projects written in different programming languages <p>I currently have three independent projects on my plate - each requiring development in a different language.</p> <p>There's a WCF Web Services / Windows Forms project in C# .Net 3.5, a web site in PHP with generous javascript, and maintenance on a legacy Windows application written in VB 6.</p> <p>Because I'm switching so often, I frequently start writing lines of code in the wrong language without thinking. It's getting better with time, but there are always slip-ups and I'm obviously not being as productive as I could be.</p> <p>Do many other developers encounter this language-switching problem?</p> <p>If so, how do you manage or minimize productivity problems caused by having to switch your brain between languages?</p> <p><strong>Edit:</strong></p> <p>As a perfect example, look at a foreach loop for my three projects:</p> <p>C#:</p> <pre><code>foreach (Person p in myPeople) { ... } </code></pre> <p>PHP:</p> <pre><code>foreach ($myPeople as $p) { ... } </code></pre> <p>VB:</p> <pre><code>For Each p As Person in myPeople ... Next </code></pre>
<p>Definitely been there. </p> <p>While it's frustrating to sometimes get caught up in the incorrect syntax, my guess is that in the long run you'll be a much better developer for having the multi-platform exposure.</p> <p>The best thing I've found is to try to get blocks of significant time to focus on the project at hand. Ideally at least a couple of days. I usually don't even bother trying to get started programming if I don't have an hour or more to focus, because there is just too much inertia to overcome before I can even consider getting in the zone. Working on multiple disparate projects just makes it worse.</p> <p>I'd suggest trying to block off your week. Perhaps Mondays for maintenance, Tuesday and Wednesday for the forms project, and Thursday-Friday for the web project. I've found that having a routine like that makes it easier to just fall into, rather than always wondering what I should be working on.</p>
Why should we use literals in C#? <p>In some C# code I have seen staments like this:</p> <pre><code>float someFloat = 57f; </code></pre> <p>I want to know why we should use literals like <code>f</code> in the above case?. </p>
<p>Mainly so the compiler knows exactly what we mean - in particular for overload resolution:</p> <pre><code>Foo(57f); </code></pre> <p>should that call <code>Foo(int)</code> / <code>Foo(float)</code> / <code>Foo(decimal)</code> ?</p> <p>Actually, I don't like remembering things - an alternative is:</p> <pre><code>float someFloat = (float)57; </code></pre> <p>this is <strong>not</strong> a runtime cast - it is identical (at the IL level) to <code>57f</code>. The only time it is subtly different is with <code>decimal</code>s with extra precision:</p> <pre><code>decimal someDecimal = (decimal)57.0; // same as 57M, not 57.0M (scale is different) </code></pre>
Save metafile in C# <p>If I have a wmf or emf image in System.Drawing.Image, is there a way to save the metafile data with c# without rendering it as a bitmap? Calling Image.Save will render it to a bitmap and I want to keep the original data so that it would still be a valid .wmf or .emf format file.</p>
<p>Despite this MSDN page, it is possible to save a true EMF file. See this question: <a href="http://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/895204#895204">gdi-c-how-to-save-an-image-as-emf</a></p>
troublesome javascript <p>I'm trying to make a little tag list doohickey for adding and removing tags. I have a textbox where the user can enter the tags, separated by commas. and an add button. I would like it for when the user clicks the add button to add a small div to the inside of a div below the box. the small div should contain the tag and a little x for which to remove the tag later. heres what I have:</p> <pre><code>&lt;script type='text/javascript'&gt; function tagsremove(tag) { document.getElementByName('tags').value.replace('/'+tag+'\,\s/', ''); } $('#tagbutton').click(function(){ var tags = $('#tagsbox').text().split(", "); for (var tag in tags) { document.getElementByName('tags').value += tag +", "; $('#curtags').append("&lt;div class='tag'&gt;" + tag + " &lt;a href='#' onlclick='tagsremove(\'" + tag + "\');$(this).hide();'&gt;x&lt;/a&gt;&lt;/div&gt;") } }); &lt;/script&gt; &lt;div class='statbox'&gt; &lt;form method='post' action='post.php' id='writeform'&gt; &lt;p class='subtitle'&gt;Title&lt;/p&gt; &lt;input type='text' name='title' id='titlebox' /&gt;&lt;br /&gt; &lt;p class='subtitle'&gt;Body&lt;/p&gt; &lt;textarea id='postbox' name='body' rows='10'&gt;&lt;/textarea&gt;&lt;br /&gt; &lt;p class='subtitle'&gt;Tags&lt;/p&gt; &lt;input type='text' id='tagsbox' /&gt;&lt;input type='button' id='tagbutton' value='Add' /&gt; &lt;p class='subsubtitle'&gt;Seperate by commas (eg. "programming, work, job")&lt;/p&gt; &lt;div class='subsubtitle' id='curtags'&gt;Current Tags:&lt;/div&gt; &lt;input type='hidden' value='' name='tags' /&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>The problem i'm having is that when I click the add button, nothing happens. I would like to fix this.</p>
<p>Your first problem is that</p> <pre><code>$('#tagsbox').text() </code></pre> <p>should be</p> <pre><code>$('#tagsbox').val() </code></pre> <p>because #tagsbox is an input field.</p> <p>There are other issues, like splitting on "," and then trimming rather than splitting on ", " but I think your main problem is the .text() vs .val()</p>
Apache Cocoon JAR configuration - I want to use .class files ! <p>I'm using the Apache Cocoon framework, set up several eons ago for the web app I'm developing.</p> <p>I don't know if its how cocoon is set up for everyone, or its if some 'special' configuration my company has performed, but this is what happens.</p> <p>In order for cocoon to use ANY class files, they must be bundled up into a JAR and put in the tomcat(5) / common / lib directory. cocoon simply won't see the class files if we put them somewhere else.</p> <p>Even if that somewhere else is in WEB-INF/classes or java or whatever.</p> <p>Does anyone know how this configuration is set within cocoon (I'm a cocoon novice)? I want to be able to just bang my .class files in WEB-INF and away we go.</p> <p>I know I should be using an IDE, but if you saw the app structure you would understand that I'm not. We're working towards it...</p> <p>Many thanks in advance...</p> <p>Mieze</p>
<p>I know nothing about Cocoon, but if you can put jars in tomcat/common/lib, then classes should work in tomcat/common/classes (NOT WEB-INF/classes).</p> <p>Placing stuff into tomcat/common (instead of inside the webapp itself) is kind of weird, but you probably need to change some Cocoon settings (or the place where Cocoon is installed) to avoid that. Is Cocoon part of the webapp or also "tomcat common"?</p>
When to override GetHashCode()? <p>When should we override the <strong>GetHashCode</strong>() method provided by '<strong>Object</strong>' class in '<strong>System</strong>' namespace?</p>
<p>When you override <code>Equals</code>, basically. When you want to provide a different idea of equality than simple reference equality.</p> <p>String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. The hash code reflects this, such that if two strings are equal they will have the same hash code. (The reverse isn't necessarily true - two unequal strings <em>can</em> have the same hash code, but it's unlikely.)</p> <p>(Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but <code>String.Equals</code> just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)</p>
AS3 access dynamic textfield on stage from a class <p>I have this dynamic textfield on stage, and I want to access it from my xmlloader class, so it can display text from my xml file. I just can't figure out a way to do it.</p>
<p>I found the answer:</p> <pre><code>MovieClip(root).thetextfieldonstage.text = "yep"; </code></pre> <p>can call the textfield from class.</p>
Zend Framework: Some email users get errors when trying to open PDF attachments? <p>I'm having a strange problem and not sure how to troubleshoot it. I have created a script in one of my Zend Framework controllers that allows an administrator to log in, upload a PDF, and send as an attachment to everyone subscribed to the mailing list. The problem is that some users report that they are unable to open the PDF attachment, that the file is corrupt. I think this is only happening to AOL users, but I'm not positive. Have you encountered this problem before? Or maybe it is not a problem with AOL, but something wrong with my code?</p> <p>Here's the code that does the work:</p> <p>Also, I'm using ZF version 1.6.0. Not sure if that is relevant.</p> <pre><code>//assuming the form is valid: $table = new Subscribers(); $rowset = $table-&gt;fetchAll(); foreach ($rowset as $row) { $mail = new Zend_Mail(); $mail-&gt;setBodyText($form-&gt;getElement('body')-&gt;getValue()) -&gt;setFrom('weekly-update@email.com', 'Weekly Update') -&gt;addTo($row-&gt;email) -&gt;setSubject($form-&gt;getElement('subject')-&gt;getValue()); $fileLocation = $form-&gt;getElement('attachment')-&gt;getValue(); $fileContents = file_get_contents($fileLocation); $attachment = $mail-&gt;createAttachment($fileContents); $attachment-&gt;filename = str_replace(Zend_Registry::get('config')-&gt;downloadsLocation . '/', '', $fileLocation); $mail-&gt;send(); } </code></pre>
<p>It appears (to me) that in this line of code:</p> <pre><code>$attachment = $mail-&gt;createAttachment($fileContents); </code></pre> <p>you likely need to add the additional header information available in the createAttachment method of the Zend_Mail framework::</p> <pre><code>$attachment = $mail-&gt;createAttachment($fileContents, Zend_Mime::DISPOSITION_INLINE); </code></pre> <p>Many larger email providers are sticklers for strict adherence to good email policy (I've found).</p> <p>Play around with this and I'm sure you'll get it to work.</p>
How to exclude one value from a grouping sum, based on a value of another field? <p>How do I exclude one value from a grouping sum, based on a value of another field?</p> <p>ie I open Report=> Report Properties=>Code and insert my Custom Code, but how would I change the below code to exclude a numeric value of another field for the below case?</p> <pre><code>Public Function ChangeWord(ByVal s As String) As String Dim strBuilder As New System.Text.StringBuilder(s) If s.Contains("Others") Then strBuilder.Replace("Others", "Other NOT INCL") Return strBuilder.ToString() Else : Return s End If End Function </code></pre>
<p>I'm assuming you want to exclude a numeric value from a sum where the string value of a cell on the same row includes "Others", and that the function you've supplied is used as the grouping criteria for a table in the report. Apologies if this isn't correct.</p> <p>It's not going to be possible to do this without using a second piece of logic, either a function or an <code>Iif</code> condition. I don't have SSRS available to test this at the moment, but (assuming your value column is an integer, the code will look something like:</p> <pre><code>Public Function ExcludeOthers(rowDesc As String, rowVal as integer) if ChangeWord(rowDesc) = "Other NOT INCL" Return 0 else Return rowVal end if End Function </code></pre> <p>Then, in the cell where you want the conditional sum to appear:</p> <pre><code>=Sum(ExcludeOthers(Fields!desc.Value,Fields!val.Value)) </code></pre> <p>Alternatively, you could do this without the function by using <code>Iif</code> in the cell where the conditional sum will appear:</p> <pre><code>=Sum(Iif(ChangeWord(Fields!desc.Value) = "Other NOT INCL",0,Fields!desc.Value)) </code></pre> <p>Depending on the nature of your source data, you could also do this by adding calculated columns to the report's source query.</p> <p>I would favour the second or third option - custom code seems like overkill for this purpose.</p>
"No default module defined" error in Zend Framework app <p>I am in process of making my bootstrap.php file more organized, but after I put everything into separate static methods, I cannot load any page beyond index controller. E.g. if I try to open </p> <p><code>http://localhost/zftutorial/login/index</code></p> <p>I get</p> <pre><code> Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller class ("Login_IndexController")' in C:\Program Files\VertrigoServ\www\library\Zend\library\Zend\Controller\Dispatcher\Standard.php:341 Stack trace: #0 C:\Program Files\VertrigoServ\www\library\Zend\library\Zend\Controller\Dispatcher\Standard.php(255): Zend_Controller_Dispatcher_Standard-&gt;loadClass('IndexController') #1 C:\Program Files\VertrigoServ\www\library\Zend\library\Zend\Controller\Front.php(934): Zend_Controller_Dispatcher_Standard-&gt;dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #2 C:\Program Files\VertrigoServ\www\zftutorial\public\index.php(18): Zend_Controller_Front-&gt;dispatch() #3 C:\Program Files\VertrigoServ\www\zftutorial\public\index.php(138): Bootstrap::run() #4 {main} thrown in C:\Program Files\VertrigoServ\www\library\Zend\library\Zend\Controller\Dispatcher\Standard.php on line 341 </code></pre> <p>and in my bootstrap file I seem to have defined where controllers chould be found:</p> <pre><code>public static function setupFrontController() { self::$frontController = Zend_Controller_Front::getInstance(); self::$frontController-&gt;throwExceptions(true); self::$frontController-&gt;returnResponse(true); self::$frontController-&gt;setBaseUrl('/zftutorial'); self::$frontController-&gt;setControllerDirectory( array( 'default' =&gt; self::$root . '../application/controllers', 'admin' =&gt; self::$root . '../application/controllers', 'index' =&gt; self::$root . '../application/controllers', 'login' =&gt; self::$root . '../application/controllers', 'user' =&gt; self::$root . '../application/controllers' ) ); self::$frontController-&gt;setParam('registry', self::$registry); } </code></pre> <p>Perhaps it has to do something with routing, but my app worked fine with implicit routing before, e.g. other controllers worked well too. WHat is the source of above error? How can I test/find/fix it?</p>
<p>Looking at your stack trace the error is *Invalid controller class ("Login_IndexController")*</p> <p>This suggests that the class Login_IndexController doesn't exist.</p> <p>You should have a file called IndexController.php in the login module's controller directory. The structure you have at the moment won't work because two modules can't have a controller with the same name. Change the structure to </p> <pre><code>self::$frontController-&gt;setControllerDirectory( array( 'default' =&gt; self::$root . '../application/modules/default/controllers', 'admin' =&gt; self::$root . '../application/modules/admin/controllers', 'index' =&gt; self::$root . '../application/modules/index/controllers', 'login' =&gt; self::$root . '../application/modules/login/controllers', 'user' =&gt; self::$root . '../application/modules/user/controllers' ) ); </code></pre> <p>Create the IndexController.php in self::$root . '../application/modules/login/controllers and make sure the class is called Login_IndexController</p>
Generics Sub List <p>Check the code.</p> <pre><code>class DynamicObj : BaseObj {} class BaseObj {} class clientCode { List&lt;DynamicObj&gt; GetFilteredObjs(List&lt;BaseObj&gt; baseList) { // I want to return the sublist of baseList which only have DynamicObj. List&lt;DynamicObj&gt; dList = baseList.FindAll( delegate(BaseObj bo){ // Del1 return bo is DynamicObj; }).ConvertAll&lt;DynamicObj&gt;( delegate(BaseObj bo){ // Del2 return bo as DynamicObj; }); } } </code></pre> <p>Now it might be a silly question, But my code will have to loop objects 2 times,once for Del1 loop and once for Del2 loop.</p> <p>Is there any straight way? C# 2.0 only.</p>
<p>The easiest way is probably to use an iterator block:</p> <pre><code>public IEnumerable&lt;TTarget&gt; FilteredCast&lt;TSource,TTarget&gt; (IEnumerable&lt;TSource&gt; source) where TSource : class where TTarget : class, TSource { foreach (TSource element in source) { TTarget converted = element as TTarget; if (converted != null) { yield return converted; } } } </code></pre> <p>(This is basically the <code>Enumerable.OfType</code> method in LINQ to Objects, btw. I've restricted it to reference types for convenience, but it's still generic so you can reuse it more easily.)</p> <p>Then just write:</p> <pre><code>List&lt;DynamicObj&gt; GetFilteredObjs(List&lt;BaseObj&gt; baseList) { return new List&lt;DynamicObj&gt;(FilteredCast&lt;BaseObj,DynamicObj&gt;(baseList); } </code></pre> <p>Note that this won't return nulls. If you want nulls to be included, you'd need to cater for that explicitly.</p>
Good text editor for Windows? <p>I'm looking for a text editor, much like TextMate (<a href="http://www.macromates.com" rel="nofollow">www.macromates.com</a>) on Mac, but I want it to have a built-in compiler. </p> <p>For example, I do not want an IDE like Visual Studio or Eclipse. I'm looking for an editor where I can click "Run" and it will compile my code and show me the results in a terminal. </p> <p>I know of a text editor, which is TextMate's sister application for Windows, but it does not have a built-in compiler. I also do not want to install Cygwin for g++/gcc.</p>
<p><strong><a href="http://notepad-plus.sourceforge.net/de/site.htm">Notepad++</a></strong></p> <p>It is based on Scintilla and is available under GPL.</p> <p>Additionally I recommend downloading the <a href="http://www.mingw.org/wiki/HOWTO%5FInstall%5Fthe%5FMinGW%5FGCC%5FCompiler%5FSuite">MinGW port of GCC</a>.</p>
Compare different ways to remove selected items from System.Windows.Forms.ListBox <p>So far I've found 2 ways to delete selected items from a listbox (winform):</p> <p>1.</p> <pre><code>ListBox.SelectedObjectCollection tempCollection = new ListBox.SelectedObjectCollection(myListBox); for (int i = tempCollection.Count - 1; i &gt;= 0; i--) { myListBox.Items.Remove(tempCollection[i]); } </code></pre> <p>2.</p> <pre><code>while (myListBox.SelectedItems.Count &gt; 0) { myListBox.Items.Remove(myListBox.SelectedItem); // or //myListBox.Items.Remove(myListBox.SelectedItems[0]); } </code></pre> <p>The 2nd way is easy to understand, but the 1st one is strange for me. They're both work for me, I just want to know the difference?</p>
<p>The first way is written really strangely. It looks strange because it goes backwards. This is so that it doesn't upset the collection of selected items. The selected items collection isn't fully created, it's an Enumerable collection, and items come off it only when you ask for them. You can't use a foreach, because the collection of selected items keeps changing as you remove items.</p> <p>I actually prefer the second way. Besides, whatever reads easier is easier to maintain. The first one reads: get the selected items, go through them backwards, removing each from the list.</p> <p>The second one reads: while there are selected items, remove the first available selected item.</p> <p>Much better the second way.</p>
How do I loop backwards from SiteMap.CurrentNode to SiteMap.RootNode <p>I have a simple Sitemap like this from asp:SiteMapDataSource:</p> <p>Page 1 > Page 2 > Page 3</p> <p>I would like to create foreach loop in C# that generates it instead for using asp:SiteMapPath because I need to add some exceptions to it. Now I cannot figure out how do I loop backwards from SiteMap.CurrentNode to SiteMap.RootNode?</p>
<p>The property you are looking for is <a href="http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.parentnode.aspx" rel="nofollow">SiteMapNode.ParentNode</a></p> <pre><code>SiteMapNode currentNode = SiteMap.CurrentNode; SiteMapNode rootNode = SiteMap.RootNode; Stack&lt;SiteMapNode&gt; nodeStack = new Stack&lt;SiteMapNode&gt;(); while (currentNode != rootNode) { nodeStack.Push(currentNode); currentNode = currentNode.ParentNode; } // If you want to include RootNode in your list nodeStack.Push(rootNode); SiteMapNode[] breadCrumbs = nodeStack.ToArray(); </code></pre>
Query interceptor to return true if the entity is in a list of items in ado.net data services <p>I'm using ado.net data services and want to implement row level security in the query interceptor to limit the data to only return data that the user is allowed to see. The complexity comes in in that the user name for the the user is on another table. So I thought I could retrieve a list of events that the user can see according to the entry in the OnlineSubscription table for that user and then return whether the current event matches any entries that are returned as follows:</p> <pre><code>[QueryInterceptor("Events")] public Expression&lt;Func&lt;Events, bool&gt;&gt; QueryEvents() { var allowedEventList = (from os in context.OnlineSubscription from e in os.Events where os.UserName == HttpContext.Current.User.Identity.Name select e; return e =&gt; events.Intersect(new List&lt;Events&gt; { e }).Any(); } </code></pre> <p>However this throws a "Not implemented" exception. So my question is: Is there a right way to compare the current entity to a list of entities in the query interceptor? </p> <p>EDIT: I've also tried:</p> <pre><code>return e =&gt; events.Any(evnt =&gt; evnt.Event_Key == e.Event_Key); </code></pre> <p>without any success (once again getting the "Not implemented" exception).</p>
<p>Apparently this fails because by using the lambda expression events.Any... it's already querying in the initial context (ie. querying on Events straight) and then when you add the events.Any clause it also tries to query on the new context (ie. the nested "from" of Events within OnlineSubscription) so it understandably throws an exception.</p> <p>I then used:</p> <pre><code>[QueryInterceptor("Events")] public Expression&lt;Func&lt;Events, bool&gt;&gt; QueryEvents() { return e =&gt; e.OnlineSubscription.Any(os =&gt; os.UserName == HttpContext.Current.User.Identity.Name); } </code></pre> <p>Which works since this is just querying in the same context as the initial query and merely traverses through relationships.</p>
Why do we not have a virtual constructor in C++? <p>Why does C++ not have a virtual constructor?</p>
<p>Hear it from the horse's mouth:). </p> <p>From Bjarne Stroustrup's C++ Style and Technique FAQ <a href="http://www.stroustrup.com/bs_faq2.html#virtual-ctor">Why don't we have virtual constructors?</a></p> <blockquote> <p>A virtual call is a mechanism to get work done given partial information. In particular, "virtual" allows us to call a function knowing only any interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the exact type of what you want to create. Consequently, a "call to a constructor" cannot be virtual.</p> </blockquote> <p>The FAQ entry goes on to give the code for a way to achieve this end without a virtual constructor.</p>
How to use css within a javascript function <p>I am using jQuery monthly calender, in which every day is a cell, onClick in the cell, I am able to print the alert, but I also want to change the background color of the cell, on which I clicked. But I am not getting the way to call CSS using Javascript. Please help me out.</p>
<p>In jQuery, you may use the <a href="http://docs.jquery.com/CSS/css#namevalue" rel="nofollow">css method</a> to change the background-color of the cell:</p> <pre><code>// let's say this is in a loop $(this).css('background-color', '#f00'); </code></pre>
Visual C++: How to get the CPU time? <p>How can I programatically find the CPU time which is displayed in <code>System Idle Process</code> (in Task Manager) using Visual C++?</p>
<p>What you want is something like this...</p> <pre><code>NTSTATUS hStatus; SYSTEM_PERFORMANCE_INFORMATION stSysPerfInfo; hStatus = NtQuerySystemInformation(SystemPerformanceInformation, &amp;stSysPerfInfo, sizeof(stSysPerfInfo), NULL); if (hStatus != NO_ERROR) { // Do work.... } </code></pre> <p>Or take a look at this "TaskManager"</p> <p><a href="http://reactos.freedoors.org/Reactos%200.3.8/ReactOS-0.3.8-REL-src/base/applications/taskmgr/" rel="nofollow">http://reactos.freedoors.org/Reactos%200.3.8/ReactOS-0.3.8-REL-src/base/applications/taskmgr/</a></p>
How to display only parts of several urls into one html file? <p>In the past I was using iframe but it displayed all the webpage urls contents in full.</p> <p>For example: I have saved the following code in a file named "trial.html" :</p> <pre><code>&lt;iframe src="http://stackoverflow.com/unanswered" width=1100 height=1500&gt;&lt;/iframe&gt; &lt;iframe src="http://stackoverflow.com/questions" width=1100 height=1500&gt;&lt;/iframe&gt; </code></pre> <p><strong>When I load my file "trial.html" in firefox it shows the two urls properly. ;)</strong> </p> <p><hr /></p> <p>But, for instance, I would like that my webpage <strong>show me only the top right "vote" part (gray color) for the first url</strong>. I notice that it has the following code :</p> <pre><code>&lt;div class="module"&gt; &lt;div class="summarycount" style="text-align: left;"&gt;11,308&lt;/div&gt; &lt;p&gt;questions with &lt;b style="color: maroon;"&gt;no upvoted answers&lt;/b&gt;&lt;/p&gt; &lt;p&gt;The highest voted unanswered questions appear first, then the most recent ones. &lt;/p&gt; &lt;/div&gt; </code></pre> <p><hr /></p> <p><strong>Is it possible to display only the part <em><code>&lt;div class="summarycount"</code></em> or the <em><code>&lt;div class="module"&gt;</code></em> part?</strong></p> <p>Thanks in advance ;)</p>
<p>Frames are just another viewport, same as your basic browser window, and all a viewport does is provide a place to display documents. Whole documents.</p> <p>If you want to parse a document, or indeed many documents, to pick and choose sections of them and merge into another document, you'll have to engage a server-side language to load those documents up and do the surgery for you. As always, I recommend XSLT for this where the documents are well formed, but every language is capable of doing this.</p> <p>If you really <em>really</em> wanted a guerilla option, IF you have control over the documents AND you don't have x-domain worries, you could do some JS DOM manipulation to read from iframe loaded documents and copy the important nodes into the parent document, deleting the iframe as you go, but it's nothing like as clean or reliable.</p>
Renaming the created_at, updated_at columns of ActiveRecord/Rails <p>I want to rename the timestamp columns defined in timestamp.rb . Can the methods of timestamp.rb be overwritten? And what has to be done in the application that the module with the overwritten methods is used.</p>
<p>This can be done via just over writing the ActiveRecord::Timestamp module methods. Not actually overwriting the entire module. I need to to accomplish this same goal as I am working with a legacy database. I am on rails 3 and I have started following a methodology of how to monkey patch my code with over writing rails functionality.</p> <p>I first create the base project that I am working with and create a file called that in the initializers. In this case I created active_record.rb. And within the file I put code to override two methods that controlled the timestamp. Below is the sample of my code:</p> <pre><code>module ActiveRecord module Timestamp private def timestamp_attributes_for_update #:nodoc: [:updated_at, :updated_on, :modified_at] end def timestamp_attributes_for_create #:nodoc: [:created_at, :created_on] end end end </code></pre> <p><strong>NOTE:</strong> I would also like to mention that this sort of monkey patching to get things to work is frowned upon and may break on upgrades so be careful and be fully aware of what it is that you want to do.</p>
Select Most Recent States From History Table <p>I have inherited a table with a structure something like this:</p> <pre><code>ID Name Timestamp Data ---------------------------- 1 A 40 ... 2 A 30 ... 3 A 20 ... 4 B 40 ... 5 B 20 ... 6 C 30 ... 7 C 20 ... 8 C 10 ... </code></pre> <p><code>ID</code> is an identity field and the primary key and there are non-unique indexes on the <code>Name</code> and <code>Timestamp</code> fields.</p> <p>What is the most efficient way to get the most recent record for each item name, i.e. in the table above rows <strong>1</strong>,<strong>4</strong> and <strong>6</strong> should be returned as they are the most up-to-date entries for items <strong>A</strong>,<strong>B</strong> and <strong>C</strong> respectively.</p>
<p>SQL Server 2005 (onwards):</p> <pre><code>WITH MostRecentRows AS ( SELECT ID, Name, Data, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY TimeStamp DESC) AS 'RowNumber' FROM MySchema.MyTable ) SELECT * FROM MostRecentRows WHERE RowNumber = 1 </code></pre>
Transaction across basicHttpBinding <p>we currently have an asmx webservice which exposes a single method to make various updates to a Sql database, wrapped internally in a SqlTransaction.</p> <p>I am re-writing this service in WCF and we would like to split up the existing method into sub-calls accessed through various different WCF services. There is a restriction to use basicHttpBinding on the services, which rules out all the built-in WCF transaction features. Is it possible to go with this architecture and maintain a transaction across multiple service calls? WS-TRANS has been suggested as a possible solution but I'm not familiar with it, would this work?</p>
<p>It's very rare that you get something for nothing. The chief difference between <strong>basic</strong>HttpBinding and <strong>ws</strong>HttpBinding is that the latter supports the <strong>WS-*</strong> protocols.</p> <p>basicHttpBinding gives you what you had with ASMX, more or less. "transactions" would be <em>much</em> more than you had with ASMX.</p>
How to handle serialization changes in .NET 2.0 <p>.NET 2.0 introduced VTS (Version Tolerant Serialization, <a href="http://msdn.microsoft.com/en-us/library/ms229752" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms229752</a>(VS.80).aspx )</p> <p>A simple test project reveals that the default behavior in 2.0 is to not throw a serialization exception if a field is added to a class, then an attempt is made to deserialize an instance of that class from a binary serialization of a class instance that didn't have the new field.</p> <p>The default behavior in 1.1 is to throw a serialization exception if a field present in the class is missing in the binary serialized bits.</p> <p>Besides breaking backwards compatibility (code relying on the exceptions being thrown doesn't work anymore), there's a bigger problem: there is no obvious way to emulate the 1.1 behaviour in 2.0.</p> <p>How do I emulate the 'throw exception on missing/extra fields' 1.1 behavior in 2.0?</p> <p>Many thanks, Miron</p>
<p>In general, people want to be able to at least deserialize old data, regardless of changes to the class design. Unfortunately, BinaryFormatter (being field based) is very brittle here - even switching to automatically implemented properties <a href="http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html" rel="nofollow">can break things</a>.</p> <p>Personally, I would be designing around data-contracts or similar structures that are <em>not</em> implementation specific, and <em>are</em> extensible. For binary, <a href="http://code.google.com/p/protobuf-net/" rel="nofollow">protobuf-net</a> has a lot of uses in this area.</p> <p>If you really want to emulate the 1.1 behaviour - implement <code>ISerializable</code> by hand and throw the exception (or not) yourself.</p>
What is the key difference between a 'Debug' and a 'Release' build in .NET? <p><strong>Duplicate of:</strong> <a href="http://stackoverflow.com/questions/90871/debug-vs-release-in-net">Debug VS Release in .net</a></p> <p>Why there are 'Debug' and 'Release' modes on build in dot net application?</p> <p>What is the major technical difference between them?</p>
<p>A short answer is that code built in 'Release' mode will be optimised for speed or size and also will have all the information used for debugging removed</p>
How Delphi 2009 converts Delphi 7 projects re build configurations <p>I'm moving frequently between D7 and D2009 with library code that works with both.</p> <p>For ease of going both ways, I'm routinely deleting all the D2009 additional files that get created, eg: *.dproj etc, such that on entry to D2009 I'm only ever taking D7 files.<br> This is nice because D2009 automatically makes a *.dproj, *.dgroup etc and apart from a notification on entry to D2009 that each project has been upgraded you can build immediately.</p> <p>I have two identical machines, each with D2009 on them.</p> <p>The 'good' one does what I've listed above, creating an upgraded project with the default build configurations 'base', 'debug' and 'release'. Looking in these, I can see my options copied from the Delphi 7 *.dof file (eg compilier options and output directory etc).</p> <p>On the 'bad' machine with identical D7 projects supplied to it, although it 'upgrades' the projects it does not import the compiler options and output directory settings.<br> I've not fiddled with build configurations at all.<br> I can manually import a set of options saved on the good machine, but this is tedious and I'd like to find out why the 'bad' machine behaves in a different way.</p> <p>Is there a 'master' build configuration that might now have a time/date that makes D2009 think I want that instead on a default upgrade?</p>
<p>I've just come across this exact problem.</p> <p>In my <a href="http://melander.dk/delphi/dragdrop" rel="nofollow" title="Drag and Drop Component Suite">Drag/Drop components</a>, although I support Delphi 5 through Delphi 2010, I only distribute the dof files. I do this to avoid having to keep the dof and dproj files in sync. Now all of a sudden the search path setting from the dof files are not being exported to the dproj files.</p> <p>The solution I've found is to strip the dof file of everything I don't need:</p> <pre><code>[FileVersion] Version=7.0 [Directories] OutputDir=. UnitOutputDir=. SearchPath=..\..\Source </code></pre> <p>With this change the dof file is imported correctly.</p> <p>I haven't had time (nor reason or motivation) to investigate precisely which entry in the dof file that is preventing the SearchPath from being exported.</p>
MySQL vs SQL Server 2005/2008 performance <p>I intend to start developing an ASP.NET application and I am wondering which database to use. Performance is very important and the database should be able to handle without issues a database of about 50GB. I am wondering however, if a SQL Server license is worth paying for. I have looked for performance and scalability comparisons between MSSQL Server (2005/2008) and MySQL but I can't seem to find any good tests. Can you point me to some extensive benchmarks related to this subject?</p>
<p>MySQL traditionally is very fast if you are doing a lot of reads. For example in a web site there is probably a 100 to 1 read write ratio so MySQL works well. If you are planning a high transaction database then head straight to MSSQL. If money is no issue head straight to MSSQL anyway because it is a better product.</p>
Iterate over choices in CheckboxSelectMultiple <p>I have a CheckboxSelectMultiple field, why can't I iterate over the single choices?</p> <p>This doesn't work:</p> <pre><code> {%for choice in form.travels.choices%} {{choice}} {%endfor%} </code></pre> <p>Even specifying <code>{{choice.0}}</code> doesn't help, how could i do this?</p> <p>Thanks</p>
<p>Inside the template, the <code>travels</code> field as actually an instance of <code>BoundField</code> (which is a Django object that binds together the field and its value for rendering). This means the properties are somewhat different.</p> <p>To iterate over the choices as a tuple:</p> <pre><code>{% for choice in form.travels.field.choices %} {{ choice }} - {% endfor %} Produces: (1, 'One') - (2, 'Two') - </code></pre> <p>To iterate over the elements in the choice tuples separately:</p> <pre><code>{% for choice_id, choice_label in form.travels.field.choices %} {{ choice_id }} = {{ choice_label }} &lt;br/&gt; {% endfor %} Produces: 1 = One 2 = Two </code></pre> <p>Hope that helps. Having said that, though, I'm not sure of the context in which you're needing to do this; on the surface, it doesn't seem very django-like. You may find that using a custom form field or a custom template tag gives you a more portable, re-usable implementation that better maintains django's intended separation between view code and template code. Of course, YMMV and it could well be that the direct iteration approach is appropriate for you in this case.</p>
Force garbage collection/compaction with malloc() <p>I have a C++ program that benchmarks various algorithms on input arrays of different length. It looks more or less like this:</p> <pre><code># (1) for k in range(4..20): # (2) input = generate 2**k random points for variant in variants: benchmark the following call run variant on input array # (3) </code></pre> <p>Is it possible to reset the whole heap management at (2) to the state it had at (1)? All memory allocated on the heap that was allocated during the program is guaranteed to be freed at (3).</p> <p>I am using g++ 4.3 on Linux.</p> <p>Edit: I understand that there is no real garbage collection in C/C++. I want to force the memory allocation to join adjacent empty chunks of memory it has in its free list at (2).</p>
<p>If you want the test runs to start in the same heap states, you can run them in their own processes created by fork().</p>
How do I do a search on my website <p>I wanted to add a search feature on a website that would allow users to search the whole website. </p> <p>The site has around 20 tables and i wanted the search to search through all 20 tables. </p> <p>Any one can point me into what sort of mysql queries I need to build?</p>
<p>First of all, what about adding <a href="http://www.google.com/services/custom.html" rel="nofollow">custom Google websearch</a> to your site?</p> <p>The hard way: You should propably do a query for each of your tables and <code>LIMIT</code> (with <code>LIKE</code> on text columns or use full text indexing if your database software supports this) the result to X (e.g. ten) results. In your code, somehow rate these results and display the X best results.</p> <p>You could also try to use a <code>UNION</code> of multiple queries but then the resulting tuples all have to same structure (if I remember correctly).</p>
indicating libgloss machine when building newlib for bespoke platform <p>I'm compiling newlib for a bespoke PowerPC platform with no OS. Reading information on the net I realise I need to implement stub functions in a <code>&lt;newplatform&gt;</code> subdirectory of libgloss.</p> <p>My confusion is to how this is going to be picked up when I compile newlib. Is it the last part of the <code>--target</code> argument to configure e.g. <code>powerpc-ibm-&lt;newplatform&gt;</code> ?</p> <p>If this is the case, then I guess I should use the same <code>--target</code> when compiling binutils and gcc?</p> <p>Thank you</p>
<p>I ported newlib and GCC myself too. And i remember i didn't have to do much stuff to make newlib work (porting GCC, gas and libbfd was most of the work). </p> <p>Just had to tweak some files about floating point numbers, turn off some POSIX/SomeOtherStandard flags that made it not use some more sophisticated functions and write support code for <code>longjmp</code> / <code>setjmp</code> that load and store register state into the jump buffers. But you certainly have to tell it the target using <code>--target</code> so it uses the right machine sub-directory and whatnot. I remember i had to add small code to <code>configure.sub</code> to make it know about my target and print out the complete configuration trible (cpu-manufacturer-os or similar). Just found i had to edit a file called <code>configure.host</code> too, which sets some options for your target (for example, whether an operation systems handles signals risen by <code>raise</code>, or whether newlib itself should simulate handling). </p> <p>I used <a href="http://spindazzle.org/ggx/" rel="nofollow">this blog</a> of Anthony Green as a guideline, where he describes porting of GCC, newlib and binutils. I think it's a great source when you have to do it yourself. A fun read anyway. It took a total of 2 months to compile and run some fun C programs that only need free-standing C (with dummy read/write functions that wrote into the simulator's terminal).</p> <p>So i think the amount of work is certainly manageable. The one that made me nearly crazy was <code>libgloss</code>'s build scripts. I certainly was lost in those autoconf magics :) Anyway, i wish you good luck! :)</p>
Persistent data structures in Java <p>Does anyone know a library or some at least some research on creating and using persistent data structures in Java? I don't refer to persistence as long term storage but persistence in terms of immutability (see <a href="http://en.wikipedia.org/wiki/Persistent%5Fdata%5Fstructure">Wikipedia entry</a>).</p> <p>I'm currently exploring different ways to model an api for persistent structures. Using builders seems to be a interesting solution:</p> <pre><code>// create persistent instance Person p = Builder.create(Person.class) .withName("Joe") .withAddress(Builder.create(Address.class) .withCity("paris") .build()) .build(); // change persistent instance, i.e. create a new one Person p2 = Builder.update(p).withName("Jack"); Person p3 = Builder.update(p) .withAddress(Builder.update(p.address()) .withCity("Berlin") .build) .build(); </code></pre> <p>But this still feels somewhat boilerplated. Any ideas?</p>
<p>Builders will make your code too verbose to be usable. In practice, almost all immutable data structures I've seen pass in state through the constructor. For what its worth, here are a nice series of posts describing immutable data structures in C# (which should convert readily into Java):</p> <ul> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx">Part 1: Kinds of Immutability</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx">Part 2: Simple Immutable Stack</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/06/immutability-in-c-part-three-a-covariant-immutable-stack.aspx">Part 3: Covariant Immutable Stack</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/10/immutability-in-c-part-four-an-immutable-queue.aspx">Part 4: Immutable Queue</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/13/immutability-in-c-part-five-lolz.aspx">Part 5: Lolz!</a> (included for completeness)</li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/18/immutability-in-c-part-six-a-simple-binary-tree.aspx">Part 6: Simple Binary Tree</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2007/12/19/immutability-in-c-part-seven-more-on-binary-trees.aspx">Part 7: More on Binary Trees</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/01/18/immutability-in-c-part-eight-even-more-on-binary-trees.aspx">Part 8: Even More on Binary Trees</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/01/21/immutability-in-c-part-nine-academic-plus-my-avl-tree-implementation.aspx">Part 9: AVL Tree Implementation</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/01/22/immutability-in-c-part-10-a-double-ended-queue.aspx">Part 10: Double-ended Queue</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx">Part 11: Working Double-ended Queue Implementation</a></li> </ul> <p>C# and Java are extremely verbose, so the code in these articles is quite scary. I recommend learning OCaml, F#, or Scala and familiarizing yourself with immutability with those languages. Once you master the technique, you'll be able to apply the same coding style to Java much more easily.</p>
C# crash when loading C++ dll <p>My program is written in C# NET 2.0,it's using external functions from a dll written in C++ using Microsoft Visual Studio 2008 SP1. If I remove the dll from the directory the program is placed,the program crashes at the moment it should use the dll.That's normal.</p> <p>But the users that are using my program get the same error at the same place without moving the dll.They all have C++ Redistributable 2008 from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&amp;displaylang=en" rel="nofollow">>here&lt;</a></p> <p>Does it happen because I made the program in .NET 2.0 instead of NET 3.5 or it happens ,because the redistributable should be an older version?</p> <p>Edit:Note for me,the program runs fine.</p> <p><a href="http://stackoverflow.com/questions/735346/cannot-load-c-dll-in-c">>>new thread&lt;&lt;</a></p>
<p>Its most likely the wrong runtime. Make sure you are distributing the correct one. These will always work on your dev box because the runtimes are in the path. For testing software, I use a windows xp virtual machine. I set up the virtual machine as a completely fresh install, install the components I know that I need (.NET framework, etc.), then run my installer. You will run into a surprising number of setup issues doing this.</p>
Trim first two characters from year of GETDATE() <p>I am trying to create a WHERE clause that says </p> <pre><code>WHERE column_1 = TRIM(LEADING '20' FROM(DATEPART(year, GETDATE()))) </code></pre> <p>Basically <code>column_1</code> contains the fiscal year but the fiscal year is in the database as 8 or 9 not 2008 or 2009.</p> <p>So I need to figure a way to trim off at least the <code>'20'</code> so that the query will run correctly... The more dynamic the better because I need to set this up to run in an SSIS pkg and the less hard coding the better.</p> <p>Any suggestions? Thanks in advance! Jon</p>
<p>Rather than trim, use modulus:</p> <pre><code>... WHERE column_1 = (YEAR(GETDATE()) % 100) </code></pre>
Do I need to change anything programmatically to leverage the integrated pipeline in IIS7? <p>Do I need to change anything programmatically to leverage the integrated pipeline in IIS7? </p> <p>If so, what's the best way to degrade gracefully and remain functional on IIS6?</p> <p>Thanks!</p>
<p>No, the setting is in IIS when selecting application pool (integrated mode). I recently upgraded from IIs 6.0 to IIS 7.0. The application runs fine on both IIS 6.0 and 7.0. </p>
Is there a standard definition of what constitutes a version(revision) change <p>I am currently in bureaucratic hell at my company and need to define what constitutes the different levels of software change to our test programs. We have a rough practice that we follow internally, but I am looking for a standard (if it exists) to reference in our Quality system. I recognize that systems may vary greatly between developers, but ultimately I am looking for a "best practice" guide to what constitutes a major change, a minor change etc. I would like to reference a published doc in my submission to our quality system for ISO purposes if possible.</p> <p>To clarify the software developed at my company is used internally for test automation of Semi-Conductors. We are not selling this code and versioning is really for record keeping only. We are using the x.y.z changes to effect the level of sign-off and approval needed for release.</p>
<p>A good practice is to use 3 level revision numbers:</p> <p>x.y.z</p> <p>x is the major y is the minor z are bug fixes</p> <p>The important thing is that two different software versions with the same x should have binary compatibility. A software version with a y greater than another, but the same x may add features, but not remove any. This ensures portability within the same major number. And finally z should not change any functional behavior except for bug fixes.</p> <p><hr /></p> <p>Edit: </p> <p>Here are some links to used revision-number schemes:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Software%5Fversioning" rel="nofollow">http://en.wikipedia.org/wiki/Software_versioning</a></li> <li><a href="http://apr.apache.org/versioning.html" rel="nofollow">http://apr.apache.org/versioning.html</a></li> <li><a href="http://www.advogato.org/article/40.html" rel="nofollow">http://www.advogato.org/article/40.html</a></li> </ul>
Passing the "enter key" event to flash player in an ATL Window? <p>I have a Flash player (flash9.ocx) embedded in an ATL window and have coded functionality into the swf to respond to the return/enter key being pressed. Works fine from the standalone swf player but as soon as its played from within my embedded player it doesn't execute. It's as if my window is getting in the way somehow? Is there any way to pass the keypress through to the player?</p> <p>FYI, there isn't anything to weird in place on the form.</p> <p>Thanks!</p>
<p>I'm not VC++ developer, but I use Flash a lot.</p> <p>Though not sure, it seems that the embedded player doesn't have the focus. Make sure you've got this part covered on the Flash side of things:</p> <ul> <li>the stage exists ( you movie is properly initialized)</li> <li>you set the KeyboardEvent listener to the stage.</li> </ul> <p>You could use the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/managers/FocusManager.html" rel="nofollow">FocusManager</a> to make sure you've got the focus.</p> <p>I don't know if you can pass the focus from you app to the SWF OLE through some tabIndex or something.</p> <p>If still this doesn't work you can try using the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html" rel="nofollow">External Interface</a> to add callbacks from your app to flash player ( basically call and actionscript function from your app ).</p> <p>This was achieved through <a href="http://help.adobe.com/en%5FUS/AS3LCR/Flash%5F10.0/flash/system/package.html" rel="nofollow">fscommand</a> before, but External Interface seems to be the thing to use now.</p> <p>Good luck! </p>
java SWT: how can I draw a widget to an offscreen buffer <p>I would like to draw the contents of a StyledText widget in to an Image; this will then provide a convenient way to stick the image into a Table cell.</p> <p>Any suggestions about the best way to go about this?</p>
<p>Why do you want to create an image? </p> <p>You could just render the the StyledText-widget in the table cell. If you have a lot of items and it is a performance problem you could create a virtual table by using SWT.VIRTUAL. If you're using JFace check out <a href="http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/viewers/DelegatingStyledCellLabelProvider.IStyledLabelProvider.html" rel="nofollow">org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider</a>.</p> <p>If you're using plain SWT you should be able to use a TableEditor with a StyledText-widget as the editor. Something like this:</p> <pre><code>Table table = new Table(new Shell(new Display()), SWT.NONE); table.setHeaderVisible (true); TableColumn column = new TableColumn (table, SWT.NONE); StyledText styledText = new StyledText(table, SWT.NONE); TableItem item = new TableItem (table, SWT.NONE); TableEditor editor = new TableEditor (table); editor.grabHorizontal = true; editor.grabVertical = true; editor.setEditor (styledText, item, 0); </code></pre>
ASP.NET DataSet vs Business Objects / ORM <p>I'm thinking through data access for an ASP.NET application. Coming from a company that uses a lot of Windows applications with Client Data sets there is a natural dendancy towards a DataSet approach for dealing with data.</p> <p>I'm more keen on a Business Object approach and I don't like the idea of caching a DataSet in the session then applying an update.</p> <p>Does anyone have any experience / help to pass on about the pros and cons of both approaches?</p>
<p>You are smart to be thinking of designing a Data Layer in your app. In an ASP.NET application this will help you standardize and pretty dramatically simplify your data access. You <em>will</em> need to learn how to create and use ObjectDataSources but this is quite straightforward. </p> <p>The other advantage of a data access layer (built using a separate project/DLL) is that it makes Unit testing much simpler. I'd also encourage you to build a Business Layer to do much of the processing of data (the business layer, for example, would be responsible for pulling ObjectDataSources from the DAL to hand to the UI code). Not only does this let you encapsulate your business logic, it improves the testability of the code as well. </p> <p>You do <em>not</em> want to be caching DataSets (or DAL objects, for that matter) in the session! You will build a Web app so that record modifications work through a Unique ID (or other primary key spec) and feed changes directly to the DAL as they are made. If you were to cache everything you would <em>dramatically</em> reduce the scalability of your app.</p> <p>Update: Others on this thread are promoting the idea of using ORMs. I would be careful about adopting a full-blown ORM for reasons that I have previously outlined <a href="http://stackoverflow.com/questions/458802/doesnt-linq-to-sql-miss-the-point-arent-orm-mappers-subsonic-etc-sub-opti">here</a> and <a href="http://stackoverflow.com/questions/640004/is-linqtosql-powerful-enough-isnt-a-more-powerful-but-equally-fluent-interface">here</a>. I <em>do</em> agree, though, that it would be wise to avoid DataSets. In my own work, I make extensive use of DataReaders to fill my ObjectDataSources (which is trivial due to the design of my DAL) and find it to be very efficient.</p>
The difference between + and & for joining strings in VB.NET <p>What is the difference between <code>+</code> and <code>&amp;</code> for joining strings in VB.NET?</p>
<p>There's no difference if both operands are strings. However, if one operand is a string, and one is a number, then you run into problems, see the code below.</p> <pre><code>"abc" + "def" = "abcdef" "abc" &amp; "def" = "abcdef" "111" + "222" = "111222" "111" &amp; "222" = "111222" "111" &amp; 222 = "111222" "111" + 222 = 333 "abc" + 222 = conversion error </code></pre> <p>Therefore I recommend to always use <code>&amp;</code> when you mean to concatenate, because you might be trying to concatenate an integer, float, decimal to a string, which will cause an exception, or at best, not do what you probably want it to do.</p>
database use with ExtendScript (for Adobe Illustrator) <p>I want to refactor a VB program into ExtendScript to automate some drawing in Adobe Illustrator CS4, but have a requirement to read from a database. Is it possible to read from a database using ExtendScript? How?</p>
<p>Illustrator scripting engine doesn't provided any mechanism to read external data directly, but you have several ways to do this...</p> <ol> <li>Write an external program which connecting database to generate VB script, and use Illustrator to exec the 'generated' script, which is the old way I have done.</li> <li>The new ScriptUI since cs3 provides to open a Window, containing a flash swf as a interface to drive Illustrator JS engine. You can read xml, call webservices, Flash Remoting inside flash content. I am not sure if you are comfortable to these toolsets.</li> </ol>
OO Design - do you use public properties or private fields internally? <p>I'm working in C# 2.0, but this would apply to most object oriented languages. When I create classes with public properties that wrap private fields, I switch back &amp; forth between whether I should use the property or field internally. Of course C# 3.0 makes this easier with auto-properties, but it could still apply.</p> <p>Does it matter?</p> <pre><code>public class Person { private string _name = ""; public string Name { get { return _name; } set { _name = value; } } public Person(string name) { _name = name; //should I use the property or field here? } } </code></pre>
<p>Basically, because you can implement your validation and other logic in the property, you should access through the property unless you have a specific reason not to.</p> <p>It helps with consistency within your object, because that way you know that the values of your private fields have gone through whatever rigors you choose to put in your accessor or setter methods.</p> <p>On the other hand, the constructor can possibly be an exception to this, because you might want to set initial values. </p> <p>But in general, I'd say access through the property.</p> <p><strong>EDIT</strong></p> <p>A (trivial/contrived) example</p> <pre><code>public class Person { private string _name = ""; private List&lt;String&gt; oldnames = new ArrayList(); public string Name { get { return _name; } set { oldnames.Add(_name); _name = value; } } public Person(string name) { _name = name; //should I use the property or field here? } } </code></pre> <p>So in this case, you would want the constructor to skip the property but if you EVER use the field again you'll be causing a bug in your code because you're skipping the 'name archiving'. The reason to put validation in your property is so that you don't need to duplicate the validation code in every place that you access the field, so you shouldn't skip it even in private methods. </p>
Getting started with subversion <p><strong>Duplicate of..:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/2658/version-control-getting-started">Version Control. Getting started…</a></li> <li><a href="http://stackoverflow.com/questions/35670/how-do-I-begin-using-svn">How do I begin using SVN?</a></li> <li><a href="http://stackoverflow.com/questions/131367/svn-installation">SVN installation</a></li> <li><a href="http://stackoverflow.com/questions/48992/best-svn-tools">Best SVN Tools</a></li> <li><a href="http://stackoverflow.com/questions/453481/subversion-plugin-to-visual-studio">Subversion plugin to Visual Studio?</a></li> <li><a href="http://stackoverflow.com/questions/372687/good-visual-studio-svn-tool">Good Visual Studio SVN Tool</a></li> <li><a href="http://stackoverflow.com/questions/115493/how-do-I-convince-my-team-to-drop-sourcesafe-and-move-to-svn">How do I convince my team to drop sourcesafe and move to SVN?</a></li> </ul> <hr> <p>We are currently using SourceSafe integrated with Visual Studio and with the continuous comments about how bad SourceSafe apparently is, I've decided that we should try moving to Subversion.</p> <p>The problem is, having not used anything but SourceSafe, I need to get started somewhere and need some direction.</p> <p>What software do I need to download and install? Server? Client?</p> <p>What do I need to install the software on? Windows 2003?</p> <p>Should I have a dedicated server or is an existing file server adequate?</p> <p>How quickly will developers get up to speed? Is the integration similar enough to just carry on as normal?</p>
<p>Get your developers to read the free online <a href="http://svnbook.red-bean.com/" rel="nofollow">Red-Bean Book</a>. It's excellent, and covers all aspects of the process, including probably the best description of branching you'll find anywhere.</p>
How to crop an image using C#? <p>How can I write an application that will crop images in C#?</p>
<p>Check out this link: <a href="http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing">http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing</a></p> <pre><code>private static Image cropImage(Image img, Rectangle cropArea) { Bitmap bmpImage = new Bitmap(img); return bmpImage.Clone(cropArea, bmpImage.PixelFormat); } </code></pre>
Python: Reference to a class from a string? <p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = "abc" class AnotherSubClass(WrapperClass): var = "def" </code></pre> <p>And an obvious error message:</p> <pre> >>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File "", line 1, in File "", line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>> </pre> <p>Thanks!</p>
<blockquote> <p>How to use a string containing a class name to reference a class itself?</p> </blockquote> <p>Classes aren't special, they're just values contained in variables. If you've said:</p> <pre><code>class X(object): pass </code></pre> <p>in global scope, then the variable ‘X’ will be a reference to the class object.</p> <p>You can get the current script/module's global variables as a dictionary using ‘globals()’, so:</p> <pre><code>classobj= globals()[self.__class__.__name__] print classobj.var </code></pre> <p>(<code>locals()</code> is also available for local variables; between them you shouldn't ever need to use the awful <code>eval()</code> to access variables.)</p> <p>However as David notes, <code>self.__class__</code> is <em>already</em> the <code>classobj</code>, so there's no need to go running about fetching it from the global variables by name; <code>self.__class__.var</code> is fine. Although really:</p> <pre><code>print self.var </code></pre> <p>would be the usual simple way to do it. Class members are available as members of their instances, as long as the instance doesn't overwrite the name with something else.</p>
Delphi - Using the TApplicationEvents OnShortCut event to detect Alt+C key presses <p>I am using TApplicationEvents OnShortCut event to get application keyboard short cuts in a Delphi program.</p> <p>Using the following code:</p> <pre><code>procedure TForm1.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean) ; begin if (Msg.CharCode = VK_F9) then begin ShowMessage('F9 pressed!') ; Handled := True; end; end; </code></pre> <p>Question:</p> <p>How do I detect when 'ALT C' has been pressed ?</p>
<p>Like so:</p> <pre><code>procedure TForm1.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean); begin if (Msg.CharCode = Ord('C')) and (HiWord(Msg.KeyData) and KF_ALTDOWN &lt;&gt; 0) then begin ShowMessage('Alt+C pressed!') ; Handled := TRUE; end; end; </code></pre> <p>Please note that using Alt and some key only is a bad choice for a shortcut, as the system uses these to activate menu items or dialog controls.</p>
Does it make sense that there may be more than one class that conforms to the UIApplicationDelegate protocol in an iPhone App? <p>I think I've understood what that Delegate is supposed to do. If a class conforms to that protocol, it tells the underlying system: "Hey man, I am the UIApplication object's delegate! Tell me what's up, and I may tell you what to do!".</p> <p>What, if multiple classes implement that? Is that possible? Does that make any sense?</p>
<p>While you could implement multiple classes that conform to the UIApplicationDelegate protocol only one, the first, would receive these messages.</p> <p>Implementing a protocol to create a delegate is only one part of the equation. That delegate then has to be registered with the code that's generating the messages and these systems generally only support one delegate.</p> <p>In the case of UIApplication you can change the delegate using the 'delegate' property in the UIApplication shared class but this will replace the original delegate, not add an additional one.</p> <p>If you need to broadcast UIApplication level messages to other systems then this is functionality you should add to your existing delegate.</p>
C# LINQ to SQL: Refactoring this Generic GetByID method <p>I wrote the following method.</p> <pre><code>public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable&lt;T&gt;(); return table.ToList().SingleOrDefault(e =&gt; Convert.ToInt16(e.GetType().GetProperties().First().GetValue(e, null)) == id); } </code></pre> <p>Basically it's a method in a Generic class where <code>T</code> is a class in a DataContext.</p> <p>The method gets the table from the type of T (<code>GetTable</code>) and checks for the first property (always being the ID) to the inputted parameter.</p> <p>The problem with this is I had to convert the table of elements to a list first to execute a <code>GetType</code> on the property, but this is not very convenient because all the elements of the table have to be enumerated and converted to a <code>List</code>.</p> <p>How can I refactor this method to avoid a <code>ToList</code> on the whole table?</p> <p><strong>[Update]</strong></p> <p>The reason I can't execute the <code>Where</code> directly on the table is because I receive this exception:</p> <blockquote> <p>Method 'System.Reflection.PropertyInfo[] GetProperties()' has no supported translation to SQL.</p> </blockquote> <p>Because <code>GetProperties</code> can't be translated to SQL.</p> <p><strong>[Update]</strong></p> <p>Some people have suggested using an interface for <em>T</em>, but the problem is that the <code>T</code> parameter will be a class that is auto generated in <em>[DataContextName].designer.cs</em>, and thus I cannot make it implement an interface (and it's not feasible implementing the interfaces for all these "database classes" of LINQ; and also, the file will be regenerated once I add new tables to the DataContext, thus loosing all the written data).</p> <p>So, there has to be a better way to do this...</p> <p><strong>[Update]</strong></p> <p>I have now implemented my code like <a href="http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method/735209#735209">Neil Williams</a>' suggestion, but I'm still having problems. Here are excerpts of the code:</p> <p><em>Interface:</em></p> <pre><code>public interface IHasID { int ID { get; set; } } </code></pre> <p><em>DataContext [View Code]:</em></p> <pre><code>namespace MusicRepo_DataContext { partial class Artist : IHasID { public int ID { get { return ArtistID; } set { throw new System.NotImplementedException(); } } } } </code></pre> <p><em>Generic Method:</em></p> <pre><code>public class DBAccess&lt;T&gt; where T : class, IHasID,new() { public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable&lt;T&gt;(); return table.SingleOrDefault(e =&gt; e.ID.Equals(id)); } } </code></pre> <p>The exception is being thrown on this line: <code>return table.SingleOrDefault(e =&gt; e.ID.Equals(id));</code> and the exception is:</p> <blockquote> <p><code>System.NotSupportedException: The member 'MusicRepo_DataContext.IHasID.ID' has no supported translation to SQL.</code></p> </blockquote> <p><strong>[Update] Solution:</strong></p> <p>With the help of <a href="http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method/735888#735888">Denis Troller</a>'s posted answer and the link to the post at the <a href="http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html">Code Rant blog</a>, I finally managed to find a solution:</p> <pre><code>public static PropertyInfo GetPrimaryKey(this Type entityType) { foreach (PropertyInfo property in entityType.GetProperties()) { ColumnAttribute[] attributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), true); if (attributes.Length == 1) { ColumnAttribute columnAttribute = attributes[0]; if (columnAttribute.IsPrimaryKey) { if (property.PropertyType != typeof(int)) { throw new ApplicationException(string.Format("Primary key, '{0}', of type '{1}' is not int", property.Name, entityType)); } return property; } } } throw new ApplicationException(string.Format("No primary key defined for type {0}", entityType.Name)); } public T GetByID(int id) { var dbcontext = DB; var itemParameter = Expression.Parameter(typeof (T), "item"); var whereExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property( itemParameter, typeof (T).GetPrimaryKey().Name ), Expression.Constant(id) ), new[] {itemParameter} ); return dbcontext.GetTable&lt;T&gt;().Where(whereExpression).Single(); } </code></pre>
<p>What you need is to build an expression tree that <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL">LINQ&nbsp;to&nbsp;SQL</a> can understand. Assuming your "id" property is always named "id":</p> <pre><code>public virtual T GetById&lt;T&gt;(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property( itemParameter, "id" ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable&lt;T&gt;(); return table.Where(whereExpression).Single(); } </code></pre> <p>This should do the trick. It was shamelessly borrowed from <a href="http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html">this blog</a>. This is basically what LINQ&nbsp;to&nbsp;SQL does when you write a query like</p> <pre><code>var Q = from t in Context.GetTable&lt;T)() where t.id == id select t; </code></pre> <p>You just do the work for LTS because the compiler cannot create that for you, since nothing can enforce that T has an "id" property, and you cannot map an arbitrary "id" property from an interface to the database.</p> <p>==== UPDATE ====</p> <p>OK, here's a simple implementation for finding the primary key name, assuming there is only one (not a composite primary key), and assuming all is well type-wise (that is, your primary key is compatible with the "short" type you use in the GetById function):</p> <pre><code>public virtual T GetById&lt;T&gt;(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property( itemParameter, GetPrimaryKeyName&lt;T&gt;() ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable&lt;T&gt;(); return table.Where(whereExpression).Single(); } public string GetPrimaryKeyName&lt;T&gt;() { var type = Mapping.GetMetaType(typeof(T)); var PK = (from m in type.DataMembers where m.IsPrimaryKey select m).Single(); return PK.Name; } </code></pre>
Can the "Application Error" dialog box be disabled? <p>I am using Hudson as a continuous integration server to test C/C++ code. Unfortunatly, I have a bug somewhere that causes memory corruption, so on some Windows machines I will sometimes get a "Application Error" dialog box explaining that an instruction referenced memory that could not be read. This dialog box pops up and basically hangs the test run, as it requires manual intervention. </p> <p>Is there a way to prevent this dialog box from appearing, so that the test run simply fails and is reported as such in Hudson? </p> <p>Is it possible to automatically generate a minidump instead of showing the dialog? </p>
<ol> <li>Use "Disable error reporting", as Mr. Gently suggests. See also <a href="http://www.pcworld.com/article/108734/window%5Ftips%5Fxp%5Ferror%5Fmessagesyou%5Fdecide%5Fwhat%5Fto%5Freport.html">this PC World article</a>.</li> <li>If you happen to have MS Visual Studio on your build machine, it will catch Application Errors and pop up a dialog box. To disable these dialogs (and also the Just-In-Time Debugging feature of Visual Studio), run the command <code>drwtsn32.exe -i</code> to set Dr. Watson as the default system debugger. Dr. Watson will generate a core dump and silently exit. (See this Microsoft Knowledge Base article: <a href="http://support.microsoft.com/kb/q121434/">http://support.microsoft.com/kb/q121434/</a>.) </li> </ol>
Java reflection - access protected field <p>How can I access an inherited protected field from an object by reflection?</p>
<p>Two issues you may be having issues with - the field might not be accessible normally (private), and it's not in the class you are looking at, but somewhere up the hierarchy.</p> <p>Something like this would work even with those issues:</p> <pre><code>public class SomeExample { public static void main(String[] args) throws Exception{ Object myObj = new SomeDerivedClass(1234); Class myClass = myObj.getClass(); Field myField = getField(myClass, "value"); myField.setAccessible(true); //required if field is not normally accessible System.out.println("value: " + myField.get(myObj)); } private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } } class SomeBaseClass { private Integer value; SomeBaseClass(Integer value) { this.value = value; } } class SomeDerivedClass extends SomeBaseClass { SomeDerivedClass(Integer value) { super(value); } } </code></pre>
How do I programmatically tell if a client machine has the Microsoft.Jet.OLEDB.4.0 as a valid provider? <p>I need to export data into an Access database. My code works, but it works with the assumption the client machine has the Microsoft.Jet.OLEDB.4.0 as a valid provider.</p> <p>I want to test to see if this is true or not, in code. My problem is that I don't have the location of an existing access database and I don't want to create a new .mdb that I'd use to verify the connection and then delete it.</p> <p>Is there any way to tell which providers are installed?</p>
<p>You could simply check for the existence of</p> <pre><code>HKEY_CLASSES_ROOT\CLSID\{dee35070-506b-11cf-b1aa-00aa00b8de95} </code></pre> <p>which is the CLSID of Microsoft.Jet.OLEDB.4.0.</p>
How to get a user's client IP address in ASP.NET? <p>We have <code>Request.UserHostAddress</code> to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can I get the real IP Address?</p> <p>For example, in a Stack Overflow user profile it is: <strong>"Last account activity: 4 hours ago from 86.123.127.8"</strong>, but my machine IP address is a bit different. How does Stack Overflow get this address? </p> <p>In some web systems there is an IP address check for some purposes. For example, with a certain IP address, for every 24 hours can the user just have only 5 clicks on download links? This IP address should be unique, not for an ISP that has a huge range of clients or Internet users.</p> <p>Did I understand well?</p>
<p>Often you will want to know the IP address of someone visiting your website. While ASP.NET has several ways to do this one of the best ways we've seen is by using the "HTTP_X_FORWARDED_FOR" of the ServerVariables collection.</p> <p>Here's why...</p> <p>Sometimes your visitors are behind either a proxy server or a router and the standard <code>Request.UserHostAddress</code> only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").</p> <p>So what we want to do is first check "HTTP_X_FORWARDED_FOR" and if that is empty we then simply return <code>ServerVariables("REMOTE_ADDR")</code>.</p> <p>While this method is not foolproof, it can lead to better results. Below is the ASP.NET code in VB.NET, taken from <a href="http://www.jamescrowley.co.uk/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/">James Crowley's blog post "Gotcha: HTTP_X_FORWARDED_FOR returns multiple IP addresses"</a></p> <p><strong>C#</strong> </p> <pre><code>protected string GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return context.Request.ServerVariables["REMOTE_ADDR"]; } </code></pre> <p><strong>VB.NET</strong></p> <pre><code>Public Shared Function GetIPAddress() As String Dim context As System.Web.HttpContext = System.Web.HttpContext.Current Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR") If String.IsNullOrEmpty(sIPAddress) Then Return context.Request.ServerVariables("REMOTE_ADDR") Else Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c}) Return ipArray(0) End If End Function </code></pre>
Another Safari width issue with CSS <p>I am making this web site <a href="http://www.christopherbier.com/gbg/locations.html" rel="nofollow">http://www.christopherbier.com/gbg/locations.html</a></p> <p>In safari on mac the content div is larger in width than it is in other browsers. It overlaps the right side bar bit. I am not sure how to fix this. Here is my css:</p> <pre><code>#mainwrap { width:1000px; margin-right:auto; margin-left:auto; background-color:#f0f0f0; min-height:200px; } body{ background-color:#4c7094; background-image: url(images/bg.gif); background-repeat:repeat-x; font-size:.9em; color:#FFF; margin-top:0px; font-family: Tahoma, Geneva, sans-serif; } a{ color:#335b83; } #nav { float:left; padding: 0px 0px 0px 3px; margin: 0px 0px 0px 0px; list-style:none; border:0px solid #000; background-color:#FFF; } #nav li { float:left; margin: 3px 3px 0px 0px; font-family:Tahoma, Geneva, sans-serif; background-color:#e7ebf0; border:3px double; display: inline; border-color:#99aabb; } #nav a { float:left; display: block; color:#1d4c7b; padding: 5px 15px 5px 15px; font-size: .8em; vertical-align:middle; text-decoration:none; font-family: Georgia, "Times New Roman", Times, serif; } #nav a:hover { float:left; display: block; color:#FFF; padding: 5px 15px 5px 15px; font-size: .8em; background-color:#5b7290; vertical-align:middle; text-decoration:none; font-family: Georgia, "Times New Roman", Times, serif; } h2 { font-size:2em; margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; display: inline; font-family:Georgia, "Times New Roman", Times, serif; } h3 { font-size:1.5em; margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; display: inline; color:#335b83; font-family:Georgia, "Times New Roman", Times, serif; border-bottom: 1px; border-bottom-color: #497caf; border-bottom-style: dotted; border-width: 80%; } h4 { font-size:1.2em; margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; display: inline; color:#999; font-family:Georgia, "Times New Roman", Times, serif; } #phonebar{ padding: 0px 6px 9px 6px; background-image: url(images/phonebg.gif); background-repeat: repeat-x; background-color:#335b83; color:#FFF; float:left; border:0px solid #000; width:120px; text-align:center; } #asseenbar{ padding: 0px 9px 9px 6px; margin-right: 0px; background-image: url(images/phonebg.gif); background-repeat: repeat-x; background-color:#335b83; color:#FFF; float:left; border:0px solid #000; width:188px; text-align:center; } #footer { clear:both; margin-right:auto; margin-left:auto; } #footerpre{ background-image: url(images/footerpre.jpg); background-repeat:repeat-x; width: 1000px; height:73px; border: 0px solid #000; margin-top:0px; margin-bottom:0px; margin-right:auto; margin-left:auto; } #footerfin{ background-image: url(images/footerfin.jpg); background-repeat:repeat-x; width: 1000px; margin-top:0px; margin-right:auto; margin-left:auto; } #phone { font-size:1em; margin: 0px 0px 0px 0px; padding: 8px 0px 0px 0px; font-family:"Times New Roman", Times, serif; } #asseen { font-size:.8em; margin: 0px 0px 0px 0px; padding: 9px 0px 0px 5px; text-align:left; font-family:"Times New Roman", Times, serif; } #menubar{ clear:left; margin-bottom:0px; width:1000px; margin-left:auto; margin-right:auto; background-color:#FFF; background-image:url(images/phonebg.gif); background-repeat:repeat-x; height:38px; } #content{ margin-right:auto; margin-left:auto; background-color:#FFF; width:772px; min-height:400px; float:left; margin-bottom: 0px; padding: 20px 5px 5px 20px; border:0px solid #000; color:#333; } #gpbar { float:right; width:188px; padding: 0px 9px 9px 6px; min-height:400px; background-color:#f0f0f0; } </code></pre> <p>and my HTML:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Georgia Buying Group&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="mainwrap"&gt; &lt;center&gt; &lt;img src="images/banner.jpg" width="1000" height="72" /&gt;&lt;/center&gt; &lt;div id="menubar"&gt; &lt;div id="phonebar"&gt; &lt;p id="phone"&gt;888-325-1924&lt;/p&gt; &lt;/div&gt; &lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="index.html"&gt;HOME&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="webuy.html"&gt;WHAT WE BUY&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="goldparty.html"&gt;GOLD PARTIES&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="aboutus.html"&gt;ABOUT US&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="locations.html"&gt;LOCATIONS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="contact.html"&gt;CONTACT US&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="asseenbar"&gt; &lt;p id="asseen"&gt;Call or Stop By Today!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;h3&gt;Our Locations &lt;/h3&gt;&lt;br /&gt;&lt;br /&gt; &lt;h2&gt;Acworth &lt;/h2&gt; &lt;h4&gt; Cobb County&lt;/h4&gt; &lt;br /&gt;3451 Cobb Parkway Suite 7 Acworth, GA, 30101 &lt;a href="http://www.google.com/maps?f=q&amp;amp;source=embed&amp;amp;hl=en&amp;amp;geocode=&amp;amp;q=3451+Cobb+Parkway+Suite+7+Acworth,+GA,+30101+&amp;amp;sll=37.0625,-95.677068&amp;amp;sspn=33.710275,79.101563&amp;amp;ie=UTF8&amp;amp;ll=34.04889,-84.686136&amp;amp;spn=0.008606,0.019312&amp;amp;z=14&amp;amp;iwloc=A"&gt;View Larger Map&lt;/a&gt; &lt;table cellpadding="5px"&gt;&lt;tr&gt; &lt;td valign="top" width="325"&gt;&lt;iframe width="325" align="left" height="225" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&amp;amp;source=s_q&amp;amp;hl=en&amp;amp;geocode=&amp;amp;q=3451+Cobb+Parkway+Suite+7+Acworth,+GA,+30101+&amp;amp;sll=37.0625,-95.677068&amp;amp;sspn=33.710275,79.101563&amp;amp;ie=UTF8&amp;amp;ll=34.04889,-84.686136&amp;amp;spn=0.008606,0.019312&amp;amp;z=14&amp;amp;iwloc=A&amp;amp;output=embed"&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;img src="images/store.jpg" /&gt;&lt;/td&gt;&lt;td width="317" valign="top"&gt; &lt;u&gt;&lt;b&gt;Store Hours:&lt;/b&gt;&lt;/u&gt;&lt;br /&gt; &lt;table&gt;&lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Sunday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Monday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Tuesday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Wednesday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Thursday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Friday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td bgcolor="#EBEBEB"&gt;&lt;strong&gt;Saturday&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;10a - 6p&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&lt;br /&gt; &lt;u&gt;&lt;b&gt;Phone:&lt;/b&gt;&lt;/u&gt; &lt;h2&gt;888-325-1924&lt;/h2&gt; &lt;br /&gt; &lt;br /&gt; &lt;u&gt;&lt;b&gt;Servicing:&lt;/b&gt;&lt;/u&gt; &lt;br /&gt;&lt;h4&gt; Acworth, Woodstock, Cartersville,&lt;br /&gt; Marietta, Kennesaw, Roswell,&lt;/h4&gt;&lt;br /&gt;Alpharetta, Canton, Powder Springs, Smyrna, Sandy Springs, Atlanta, Rome, Ludyville, Rockmart, Lathentown, Sugar Valley&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/div&gt; &lt;div id="gpbar"&gt;&lt;/div&gt; &lt;div id="footer"&gt;&lt;p id="footerpre"&gt;&lt;/p&gt;&lt;/div&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>I don't have a mac so can't see, but a few points:</p> <blockquote> <blockquote> <p>your xhtml is not valid. center> doesn't exist anyomre (and by the looks of things isn't actually needed in the design anyway), also you shoudl specify the dimensions of any the header image in px.</p> <p>don't know why you're using margin auto on anything other than the mainwrap. Try margin:0; instead</p> <p>try adding * {margin:0; padding:0} to the top of your stylesheet, and then adding in any extra padding and margin you need later - this will more or less set all browsers to the same starting point when it comes to layout.</p> <p>if you don't want a border use {border:none} (if you say border: 0px solid; some browsers will still try and draw something)</p> </blockquote> </blockquote> <p>This might not fix the problem, but it will be step in the right direction as the more <a href="http://validator.w3.org/" rel="nofollow">valid</a> your markup is the easier browsers find it to render. </p>
ASP.NET MaskedEditExtender & TextBox: Cannot enter zero, workarounds? Solutions? <p>I'm trying to enter a 0 into a Textbox hooked into a MaskedEditExtender. My mask is set for a NUMBER(13,2) with 9999999999999.99 as my Decimal mask.</p> <p>The problem is that the user HAS to enter a number. The value can be 0. I've tested multiple times trying to try 0 in, and it won't work when entering RightToLeft.</p> <p>Any workarounds? Solutions?</p> <p>I tried to OnBlur the Textbox inside my UserControl when the value = my mask, but it won't change my textbox to 0.00. It doesn't do anything.</p>
<p>Generally use this property, if its 0 then user shud not even need to enter anything</p> <blockquote> <p>AutoCompleteValue - Default character to use when AutoComplete is enabled</p> </blockquote>
How to save a Java FloatBuffer (or any Buffer) to a file <p>I have a FloatBuffer of known size and just want to dump the data to a file (in binary) for inspection outside my app. What's the easiest way to do this?</p>
<p>UPDATE FOR BINARY OUTPUT:</p> <pre><code>// There are dependencies on how you create your floatbuffer for this to work // I suggest starting with a byte buffer and using asFloatBuffer() when // you need it as floats. // ByteBuffer b = ByteBuffer.allocate(somesize); // FloatBuffer fb = b.asFloatBuffer(); // There will also be endiance issues when you write binary since // java is big-endian. You can adjust this with Buffer.order(...) // b.order(ByteOrder.LITTLE_ENDIAN) // If you're using a hex-editor you'll probably want little endian output // since most consumer machines (unless you've got a sparc / old mac) are little FileOutputStream fos = new FileOutputStream("some_binary_output_file_name"); FileChannel channel = fos.getChannel(); channel.write(byteBufferBackingYourFloatBuffer); fos.close(); </code></pre> <p>TEXT OUTPUT: Since you want this to be viewable I assume you want a text file. You'll want to use a PrintStream.</p> <pre><code>// Try-catch omitted for simplicity PrintStream ps = new PrintStream("some_output_file.txt"); for(int i = 0; i &lt; yourFloatBuffer.capacity(); i++) { // put each float on one line // use printf to get fancy (decimal places, etc) ps.println(yourFloagBuffer.get(i)); } ps.close(); </code></pre> <p>Didn't have time to post a full raw/binary (non-text) version of this. If you want to do that use a <a href="http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html" rel="nofollow">FileOutputStream</a>, get the <a href="http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html" rel="nofollow">FileChannel</a>, and directly write the <a href="http://java.sun.com/javase/6/docs/api/java/nio/FloatBuffer.html" rel="nofollow">FloatBuffer</a> (since it's a <a href="http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html" rel="nofollow">ByteBuffer</a>)</p>
Using StructureMap to cache a named instance <p>I'm having difficulty figuring out how to have StructureMap cache a non-default instance. I can cache the default instance with code like this</p> <pre><code>ForRequestedType&lt;ISession&gt;() .CacheBy(InstanceScope.HttpContext) .TheDefault.Is.ConstructedBy(() =&gt; ObjectFactory.GetInstance&lt;ISessionFactory&gt;().OpenSession()); </code></pre> <p>which works as expected. And I can create a named instance fine</p> <pre><code>InstanceOf&lt;User&gt;().Is.ConstructedBy(() =&gt; someAwesomeConstructor()).WithName("CurrentUser"); </code></pre> <p>But I'd really like to cache "CurrentUser" by session, but .CacheBy() only exists in CreatePluginFamilyExpression&lt;> and the only way I can tell to get from CreatePluginFamilyExpression&lt;> to IsExpression&lt;> is by the property TheDefault, which forces me to create a default, which I don't want.</p>
<p>this was as close as I was able to get quickly</p> <pre><code>ForRequestedType&lt;IInterface&gt;() .AddInstances(x =&gt; x .OfConcreteType&lt;Implementation&gt;() .WithName("foo")) .CacheBy(InstanceScope.HttpContext); </code></pre>
WCF on PocketPC, not connecting to host machine <p>I'm working with a PocketPC vm for development over here.</p> <p>I can get the virtual device to connect to the internet, but I can't get it to connect to a web service on my local (host) machine.</p> <p>I've tried the machine name and my IP address, different ports, but no luck.</p> <p>Anyone else have this issue?</p> <p>EDIT: I have an actual device at my machine as well. When docked I don't have this problem with the real device, just the emulated one.</p>
<p>I have not had the specific issue. But, the best way I've found to deal with these issues when using WCF is to <a href="http://msdn.microsoft.com/en-us/library/ms733025.aspx" rel="nofollow">enable tracing</a> and see what the error messages are.</p>
Unit testing against large databases <p>I would like to ask about your suggestions concerning unit testing against large databases.</p> <p>I want to write unit tests for an application which is mostly implemented in T-SQL so mocking the database is not an option. The database is quite large (approx. 10GB) so restoring the database after a test run is also practically impossible.</p> <p>The application's purpose is to manage the handling of applications for credit agreements. There are users in specific roles that change the state of <code>agreement</code> objects and my job is to test part of this process.</p> <p>I'm considering two approaches:</p> <h3>First Approach</h3> <p>Create agreements that meet specific conditions and then test changes of agreement state (eg. transition from waiting in some office to handled in this specific office). The agreements will be created in application itself and they will be my test cases. All the tests will be in transactions that would be rolled back after performing these tests. </p> Advantages <p>The advantage of this approach is quite straightforward test. Expected data could be easily described because I exactly know how the object should look like after the transition. </p> Disadvantages <p>The disadvantage is that the database cannot change in a way that will break the test. Users and agreements used in test cases must always look the same and if there will be a need to change the database the preparation process will have to be repeated.</p> <p><hr /></p> <h3>Second Approach</h3> <p>Create agreements in unit tests. Programatically create agreements that would meet specific conditions. The data used for creating agreement will be chosen randomly. Also the users that will change agreement state will be created randomly. </p> Advantages <p>The advantage of this approach is ease of making changes to objects and ability to run tests on databases with different data.</p> Disadvantages <p>Both objects (agreement and user) have lots of fields and related data and I'm afraid it would take some time to implement creation of these objects (I'm also afraid that these objects may contain some errors because the creation method will be quite hard to implement without errors).</p> <p><hr /></p> <p>What do you think about these two approaches? </p> <p>Do any Stack Overflow readers think it is worth the effort create objects as described in second approach?</p> <p>Does anyone here have any experience creating such tests?</p>
<p>I'm not sure I entirely agree with your assumption that you cannot restore the database after a test run. While I definitely agree that some tests should be run on a full-size, multi-TB database, I don't see why you can't run most of your tests on a much, much smaller test database. Are there constraints that need to be tested like "Cannot be more than a billion identical rows?"</p> <p>My recommendation would actually be to use a smaller test database for most of your functional specs, and to create-drop all of its tables with each test, with as little sample data as is necessary to test your functionality.</p>
SQL Query: How do you combine count function result into a select query? <pre><code>select distinct Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, AccountCancellation_Process.Store_Num FROM FranchiseData INNER JOIN AccountCancellation_Process on FranchiseData.StoreNo = AccountCancellation_Process.Store_Num select count(*) from AccountCancellation_Process where Store_Num = '1234' select count(*) from AccountCancellation_Process where Store_Num = '1234' and Progress is not null </code></pre> <p>I want to combine the count(*) from AccountCancellation_Process into the above inner join statement so the query will give me the result of FranchiseName, Initials, StoreNo from Franchise table and Store_Num from the AccountCancellation_Process with the total records and total record with Progress column not null.</p> <p>how do you combine the query result with count function result?</p> <p>thank.</p>
<p>Like this I think is what you want. I created two table value correlated subqueries to get the data based on the stored number in the inner join table. Then I join them based on the store number. That way the distinct will work. But you might also be able to do the counts in the select part with using just correlated subqueries. I was worried the distinct might not work though.</p> <pre><code>SELECT DISTINCT Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, acp.Store_Num, total_count.Total_Count, progress_count.Progress_Count FROM FranchiseData INNER JOIN AccountCancellation_Process AS acp ON (FranchiseData.StoreNo = acp.Store_Num) INNER JOIN (SELECT Store_Num, COUNT(*) AS Total_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num) AS total_count ON (acp.Store_Num = total_count.Store_Num) INNER JOIN (SELECT Store_Num, COUNT(*) AS Progress_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num AND Progress IS NOT NULL) AS progress_count ON (acp.Store_Num = progress_count.Store_Num) </code></pre>
jQuery Selectors <p>I'm finding it difficult to find examples of using jQuery, so my bad for asking such a simple question. I've got this ul:</p> <pre><code>&lt;ul id="navLinks"&gt; &lt;li class="selected" id="homeNavLink"&gt;&lt;/li&gt; &lt;li id="aboutNavLink"&gt;&lt;/li&gt; &lt;li id="contactNavLink"&gt;&lt;/li&gt; ... &lt;/ul&gt; </code></pre> <p>I'd like to write a function to change which li has the "selected" class. Here's my attempt:</p> <pre><code>function changeNavLink(selectedId) { $("#navLinks li").each(function() { $(this).removeClass("selected"); }); $("#" + selectedId).addClass("selected"); } </code></pre> <p>What am I doing wrong?</p>
<p>You don't have to do <code>.each</code> - functions like <a href="http://docs.jquery.com/Removeclass" rel="nofollow"><code>removeClass</code></a> can work on a set of elements just fine.</p> <pre><code>function changeNavLink(selectedId) { $("#navLinks li").removeClass('selected') .filter('#' + selectedId) .addClass('selected'); } </code></pre> <p>Should work. What it is doing is selecting all the <code>li</code> elements, removing the class <code>selected</code> from all of them, <a href="http://docs.jquery.com/Traversing/filter#expr" rel="nofollow">filtering them out</a> to just the one with the ID passed, and adding the class <code>selected</code> to that one.</p> <p><a href="http://jsbin.com/ekanu" rel="nofollow">Here is a working link</a> showing the code above at work.</p>
spymemcached (Java Memcached Client) <p>Is there a way to collect the memcached stats using this API (<strong>spymemcached</strong>)?</p> <p>I know there are tools like cacti to collect information on Memcached Server. But I would like to collect, say, memory usage by each item I have put into the server--the total no. of items in the same category, etc... <strong><em>more importantly, the bytes used by individual pieces.</em></strong></p>
<p><a href="http://dustin.github.com/java-memcached-client/apidocs/net/spy/memcached/MemcachedClient.html#getStats%28%29" rel="nofollow">getStats()</a></p>
File from SOAP, how to save? <p>I am working with a client on getting a gzip from their webservice. I am able to get a response with my following call:</p> <pre><code>$response = $client-&gt;call('branchzipdata', $param); $filename = "test.gzip"; if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $response) === FALSE) { echo "Cannot write to file ($filename)"; exit; } </code></pre> <p>Now when I attempt to write that a file, such as 'test.gzip', I am unable to open it afterwards... most likely because I am doing something horrible wrong. Any insight would be appreciated.</p> <p>EDIT:</p> <p>For some reason I was saving the file as '.gzip' instead of '.gz'... So in order to have it work I now have:</p> <pre><code>$response = $client-&gt;call('call', $param); $content = base64_decode($response); $filename = "output_zip.gz"; if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $content) === FALSE) { echo "Cannot write to file ($filename)"; exit; } fclose($handle); echo system("gzip -d $filename"); </code></pre>
<p>(Edited based on the comments)</p> <p>If the return value is base64-encoded, you need to base64-decode it before you write it to the file. Alternatively you could write it out to a file which you then base64-decode to <em>another</em> file before trying to open it, but that seems a bit pointless compared with just decoding it when you first get it.</p>
Expanding this Regular Expressions to remove all special characters <p>How can I expand this to remove any special characters e.g. <code>:</code> <code>;</code> <code>,</code> etc. but still do what it does now which is remove <code>&lt;div&gt;</code> tags:</p> <pre><code>string BBCSplit = Regex.Replace(BBC, @"&lt;(.|\n)*?&gt;", string.Empty); </code></pre>
<pre><code>string BBCSplit = Regex.Replace(BBC, @"&lt;(.|\n)*?&gt;|[:;]", string.Empty); </code></pre> <p>By careful if the "special" characters you want to remove include '"", ']', etc.--you'll need to put a '\' before them.</p>
How to load an image server-side in ASP.NET? <p>I'm trying to load an image that is in the root dir of my project:</p> <pre><code>Dim b As Bitmap = New Bitmap("img.bmp") </code></pre> <p>but it doesn't seem to find the file.</p> <p>I've tried various combinations like ~img.gif, /img.gif, \img.gif, ~/img.gif etc, but none seems to work. How to access the "current directory on server" in ASP.NET?</p> <p>Thanks</p>
<p>Have you tried:</p> <pre><code>Dim b As Bitmap = New Bitmap(HttpContext.Current.Server.MapPath("~/img.bmp")) </code></pre>
Why are methods in Ruby documentation preceded by a hash sign? <p>This is something that has been bugging me for a while. When I see any Ruby method printed in text, it usually appears as:</p> <pre><code>Class#method </code></pre> <p>or </p> <pre><code>#method </code></pre> <p>Now, I would use:</p> <pre><code>Class.method </code></pre> <p>Why are all Ruby methods preceded by a pound sign? Is there any reason for it? Just curious.</p>
<p>Note that the convention is:</p> <pre><code>Class#method </code></pre> <p>rather than</p> <pre><code>object#method </code></pre> <p>In code you would have <code>object.method</code>, if <code>object</code> was an instance of <code>class</code>. The <code>#</code> convention is not used in code.</p> <p>From <a href="http://ruby-doc.org/documentation-guidelines.html">the RDoc documentation</a>:</p> <blockquote> <p>Use :: for describing class methods, # for describing instance methods, and use . for example code.</p> </blockquote>
If I have a direct reference to a google app engine Property object, how do I get() or set() upon it? <p>Assume I have a Model class called Bird and a instance of Bird called pigeon. I know I can get all the Properties of Pigeon (or bird) using</p> <pre><code>properties = pigeon.properties() #Note, Bird.properties() would also work </code></pre> <p>This returns me a dictionary where the keys are strings that match the name I gave said properties in birds, and the value are actual Property objects. My question is, how do I get or set the value using said property objects. I wish to do this because I want to allow a client to dynamically specify as strings:</p> <p>1) the key to a Model object </p> <p>2) a property of said Model object</p> <p>3) and a value that the afformentioned Property of said Model object might take on</p> <p>So clearly, I need to first get the Model object, then determine whether said Property exist, and finally get or set it somehow? Is this possible? Thank you.</p>
<p>I played around with <a href="http://con.appspot.com" rel="nofollow">App Engine Console</a>, which is great for testing and experimenting. It looks to me like you want to use <code>__set__</code>, with the first argument being your model instance, and the second being the new value. Next you need to <code>put()</code> the instance as usual.</p> <p>Here is the console session to make it clearer. (Have I mentioned how App Engine Console is awesome?)</p> <pre><code>&gt;&gt;&gt; from google.appengine.ext import db &gt;&gt;&gt; class Bird(db.Model): ... name = db.StringProperty() ... can_fly = db.BooleanProperty() ... &gt;&gt;&gt; def summarize(): ... for name in ('Pesto', 'Bobby'): ... count = Bird.all().filter('name =', name).count() ... print 'I found %d birds named %s' % (count, name) ... &gt;&gt;&gt; summarize() I found 0 birds named Pesto I found 0 birds named Bobby &gt;&gt;&gt; pigeon = Bird(name='Pesto', can_fly=True) &gt;&gt;&gt; pigeon.put() datastore_types.Key.from_path('Bird', 41015L, _app=u'con') &gt;&gt;&gt; summarize() I found 1 birds named Pesto I found 0 birds named Bobby &gt;&gt;&gt; props = pigeon.properties() &gt;&gt;&gt; props {'can_fly': &lt;google.appengine.ext.db.BooleanProperty object at 0x46ddd1cc3ddb2268&gt;, 'name': &lt;google.appengine.ext.db.StringProperty object at 0x46ddd1cc3ddb2fe8&gt;} &gt;&gt;&gt; prop = props['name'] &gt;&gt;&gt; prop &lt;google.appengine.ext.db.StringProperty object at 0x46ddd1cc3ddb2a68&gt; &gt;&gt;&gt; prop.__set__(pigeon, 'Bobby') &gt;&gt;&gt; pigeon.name 'Bobby' &gt;&gt;&gt; pigeon.put() datastore_types.Key.from_path('Bird', 41015L, _app=u'con') &gt;&gt;&gt; summarize() I found 0 birds named Pesto I found 1 birds named Bobby &gt;&gt;&gt; bobby = Bird.all().filter('name =', 'Bobby').fetch(1)[0] &gt;&gt;&gt; bobby.name u'Bobby' </code></pre> <p>If you try the online console demo yourself, be sure to delete my old instances first, as we all share the same data store.</p>
Interface exposes type A, but implementation requires type B (subclass of A) <p>I have a system which I've been wrestling with for a while. Essentially, it uses a lot of abstraction to deal with the fact that later extension is not just expected, but necessary. One place this is required is data access. The system generally deals with managing objects encapsulating some observation (in the sense of an observed value or set of values) and using them. To this end, I have something to the effect of:</p> <pre><code>public interface Observation { /** UniqueKey is used to access/identify an observation */ UniqueKey Key { get; } } public interface ObservationDataSource { /** * Retrieves an Observation from the actual data source. * performs any necessary operations to encapsulate values in object */ Observation GetObservationByUniqueKey(UniqueKey key); } </code></pre> <p>The problem arises for specific implementations of these interfaces. Eventually, the <code>Observation</code> and <code>ObservationDataSource</code> class are implemented with specific runtime classes. However, <code>UniqueKey</code> may also be extended to deal with whatever the uniquely identifying set of values are for an observation in the data source (maybe an id, maybe a time, etc). So any implementation of <code>GetObservationByUniqueKey</code> will expose a <code>UniqueKey</code> argument, but expect a specific subclass. I expect the <code>UniqueKey</code> to be casted to a specific type once passed in. </p> <p>This seems like a poor design choice, since the implementation is lying about the argument requirements -- but I can't see another way of doing this. I expect other people to be using these interfaces, so I can't just say that I'll remember this convention.</p> <p>Any ideas to fix it or handle it more elegantly?</p>
<p>I'm not sure if this is what you want, but it seems to me you could try doing it with generics:</p> <pre><code>public interface Observation&lt;T&gt; where T : UniqueKey { T Key { get; } } public interface ObservationDataSource&lt;T&gt; where T : UniqueKey { Observation&lt;T&gt; GetObservationByUniqueKey(T key); } </code></pre> <p>Now the interface is strongly typed with the specific subclass of UniqueKey that your class requires. </p>
How do I export Readonly variables with mod_perl? <p>I'm trying to make it easier to follow some <a href="http://oreilly.com/catalog/9780596001735/" rel="nofollow">Perl Best Practices</a> by creating a <code>Constants</code> module that exports several of the scalars used throughout the book. One in particular, <code>$EMPTY_STRING</code>, I can use in just about every Perl script I write. What I'd like is to automatically export these scalars so I can use them without defining them explicitly in each script.</p> <pre><code>#!perl package Example::Constants; use Exporter qw( import ); use Readonly; Readonly my $EMPTY_STRING =&gt; q{}; our @EXPORT = qw( $EMPTY_STRING ); </code></pre> <p>An example usage:</p> <pre><code>#!perl use Example::Constants; print $EMPTY_STRING . 'foo' . $EMPTY_STRING; </code></pre> <p>Using the above code produces an error:</p> <pre><code>Global symbol "$EMPTY_STRING" requires explicit package name </code></pre> <p>If I change the <code>Readonly</code> declaration to:</p> <pre><code>Readonly our $EMPTY_STRING =&gt; q{}; # 'our' instead of 'my' </code></pre> <p>The error becomes:</p> <pre><code>Attempt to reassign a readonly scalar </code></pre> <p>Is this just not possible with mod_perl?</p>
<p>I'm the author of the Readonly module. The next version of Readonly will provide support for mod_perl, specifically because of this problem.</p> <p>I know this doesn't solve your problem <em>now</em>, but... well, I'm working on it :-)</p> <p>-- Eric</p>
strange problem with java.net.URL and java.net.URLConnection <p>I'm trying to download an image from a url. The process I wrote works for everyone except for ONE content provider that we're dealing with.</p> <p>When I access their JPGs via Firefox, everything looks kosher (happy Passover, btw). However, when I use my process I either:</p> <p>A) get a 404 or</p> <p>B) in the debugger when I set a break point at the URL line (URL url = new URL(str);) then after the connection I DO get a file but it's not a .jpg, but rather some HTML that they're producing with generic links and stuff. I don't see a redirect code, though! It comes back as 200. </p> <p>Here's my code...</p> <pre><code>URL url = new URL(urlString); URLConnection uc = url.openConnection(); String val = uc.getHeaderField(0); System.out.println("FOUND OBJECT OF TYPE:" + contType); if(!val.contains("200")){ //problem } else{ is = uc.getInputStream(); } </code></pre> <p>Has anyone seen anything of this nature? I'm thinking maybe it's some mime type issue, but that's just a total guess... I'm completely stumped.</p>
<p>Maybe the site is just using some kind of protection to prevent others from hotlinking their images or to disallow mass downloads.</p> <p>They usually check either the HTTP referrer (it must be from their own domain), or the user agent (must be a browser, not a download manager). Set both and try it again.</p>
ThreadA and ThreadB both call WaitOne() in that order on the same AutoResetEvent - when the event is set, why does ThreadB get released instead of ThreadA? <p>I ran a test to find out what happens when you set an AutoResetEvent on which mutiple threads are waiting:</p> <pre><code> private static void Test() { // two threads - waiting for the same autoreset event // start it unset i.e. closed i.e. anything calling WaitOne() will block AutoResetEvent autoEvent = new AutoResetEvent(false); Thread thread1 = new Thread(new ThreadStart(WriteSomeMessageToTheConsole)); thread1.Start(); // this will now block until we set the event Thread thread2 = new Thread(new ThreadStart(WriteSomeOtherMessageToTheConsole)); thread2.Start(); // this will now also block until we set the event // simulate some other stuff Console.WriteLine("Doing stuff..."); Thread.Sleep(5000); Console.WriteLine("Stuff done."); // set the event - I thought this would mean both waiting threads are allowed to continue // BUT thread2 runs and thread1 stays blocked indefinitely // So I guess I was wrong and that Set only releases one thread in WaitOne()? // And why thread2 first? autoEvent1.Set(); } </code></pre> <p>The code is of course not useful; it's just a mickey mouse example. And this is not important/urgent. But I'd be interested to know more anyway...</p>
<p>IIRC, which thread is released by an auto-reset event is unspecified. As everyone else mentioned, you want a manual reset event if you want to broadcast a condition. If you want to release an exact number (say exactly 3 of n), then you probably want to use a semaphore.</p> <p>If you really want to dig into why the order might be different than you would expect, take a look at "Windows Internals" or anything that Mark Russinovich has written. Chances are that he explains the wait order on executive resources somewhere.</p>
How Do You Dynamically Graph/Chart Interval Data w/ OpenOffice Calc? <p>I'm interested in creating one or more spreadsheet graphs of interval metered data. The raw data is recorded as a continuously increasing value (i.e. total bytes, user logins, website hits) and date. Each sample measurement date will happen at a non-constant interval. For simplicity I would like to record the data in a spreadsheet program, such as OpenOffice Calc.</p> <p>An example of the data:</p> <pre><code>Date/Time Value 1/1/09 12:00 PM 10 1/1/09 5:00 PM 30 1/2/09 9:00 AM 100 1/2/09 6:00 PM 150 </code></pre> <p>Ideally, I want to have a single chart to graph the rate of the data, and would have the following features:</p> <ol> <li>Dynamic selection of graph date ranges as new data is gather. (N days to N years)</li> <li>Dynamic granularity of data rate display. (per hour, per day, per month, per year)</li> <li>Extra credit, enable a secondary plot of data to overlay the first plot.</li> </ol> <p>Please comment on how feasible this is, and what techniques and features I can use to accomplish this in either Excel or preferably OpenOffice Calc.</p>
<p>While you maybe can use spreadsheets for this, I think this is better done with tools specifically made for such graphing. If you search for "graph network traffic" or "graph disk temperature" you should get loads of results with different solutions.</p> <p>For monitoring network cards/routers <a href="http://oss.oetiker.ch/mrtg/" rel="nofollow">MRTG</a> + <a href="http://oss.oetiker.ch/rrdtool" rel="nofollow">rrdtool</a> is a common solution. For monitoring other things, like disk temperature for several disks, mrtg is not so suitable but rrdtool still is, see <a href="http://martybugs.net/linux/hddtemp.cgi" rel="nofollow">here</a> for an example of that.</p> <p>You could also have a look <a href="http://www.supershareware.com/info/traffic-graph.html" rel="nofollow">here</a> for a list of other alternatives.</p>
getting a view controller to disappear <p>I'm trying out a multiple view application, but I can't seem to get the first view controller to go away when I bring in the new view controller. I'm laying the second (coming) view controller at index 0, and it's just placing it in the background. I thought the [going.view removeFromSuperview] would remove the original viewcontroller, but that's not what is happening...</p> <pre><code>UIViewController *coming = nil; UIViewController *going = nil; UIViewAnimationTransition transition; if (answer == YES) { coming = boyController; going = getInfoController; transition = UIViewAnimationTransitionFlipFromLeft; } else { coming = girlController; going = getInfoController; transition = UIViewAnimationTransitionFlipFromLeft; } NSLog(child); [UIView setAnimationTransition:transition forView: self.view cache:YES]; [coming viewWillAppear:YES]; [going viewWillDisappear:YES]; [going.view removeFromSuperview]; [self.view insertSubview:coming.view atIndex:0]; [going viewDidDisappear:YES]; [coming viewDidAppear:YES]; [UIView commitAnimations]; </code></pre>
<p>First a little refactoring:</p> <pre><code>coming = (answer ? boyController : girlController); </code></pre> <p>You can delete <code>going</code> and <code>transition</code>, as they're only used once. Then, to actually do the animation, you need to put everything in the context of an animation block.</p> <pre><code>[UIView beginAnimations:@"flipAnimation" context:NULL]; [UIView setAnimationTransition:transition forView:self.view cache:YES]; [getInfoController.view removeFromSuperview]; [self.view addSubview:coming.view]; [UIView commitAnimations]; </code></pre> <p><code>viewWillAppear:</code> and <code>viewWillDisappear:</code> are delegate methods. These will be called automatically on those views' delegates, if any. They shouldn't ever be called manually.</p>
PHP arrow operator closing tags <p>I am writing a php app on the websever I set up at my house. It is a fedora10 machine, running php5 and mysql. I have code like this:</p> <pre><code>&lt;?php echo $var-&gt;function(); ?&gt; </code></pre> <p>But for some reason the -> is closing the php tag, so the output has 'function(); ?' added to it...is there something I need to change in my php or webserver configuration?</p>
<p>I dont think that you have mod_php enabled in your apache config file, or else you would never see the php code in the output. <a href="http://dan.drydog.com/apache2php.html" rel="nofollow">Here is a good tutorial</a> on setting up php 5 in apache.</p>
Is The Web's version of MVC different than traditional MVC? <p>I've done a fair amount of work on MVC on the web, and we're learning about it in my OOP class. I'm seeing some differences, and I can't tell whether that's because the Web's version of the MVC pattern is different than the traditional one, or whether I misunderstood it.</p> <p>From my understanding, The model (your flat files, RDBMS', etc) is a generic data-housing object. The View (Browser, HTML, etc) is what the user interacts with, and the controller mediates between the users actions and the data. The controller is the most domain-specific part, and it manages the views, tells the model what it needs, and tells the views what to display.</p> <p>In class, we have the Views matching what I just described, the Model contains a list of the views so that it can update them when the data changes, and the controller simply maps the user's actions to calls to the model and to specific objects (which may themselves, ask the model to update the views). What ends up happening is that most of the business logic is in the model, and it's tied very heavily to the simulation or application that is being written, while the Controller is reduced to a mapping tool between commands and methods.</p> <p>What are your thoughts on this?</p>
<p>In a non-web interface the controller handles the inputs from things like the keyboard and mouse, choosing which views to render and what changes to make in the model based on those inputs. The view and model can be more closely related because the view can register callbacks directly with the model entities to be notified of changes and thus be updated based on changes to the model directly instead of being updated by the controller.</p> <p>In the web world, views are necessarily more decoupled from the model. It must act through the controller actions because it has no direct access (after being rendered and delivered to the browser) to the model. The controller takes a larger role in this environment even though the only "input" it has to deal with are browser requests. In a sense, the coupling that used to occur with the view in non-web MVC is transferred to the controller acting on its behalf. Since there are no callbacks from the model to respond to (let's forget about "push" technologies for now), more business code is incorporated into the controller since it's the natural place to model business processes, though perhaps not validation.</p>
Are Windows Logo (TM) Certified applications harder to write in Java? <p>Third party vendors using our software as a component view Windows Logo Certification as an important selection criteria. 90% of the requirements are easy to adhere to given the flexibility in deploying Java programs. Some immediate difficulties present themselves: </p> <ul> <li>Tagging jar files with resource strings for versioning information.</li> <li>Moving From properties files to .INI files</li> <li>Short Path Name / Long Path Name / UNC isn't well support by the libraries</li> <li>Look and feel requirements </li> </ul> <p>These will require some serious recoding to address. I may be interpreting the specifications too closely. I found one decent example of an application that obtained <a href="http://cert.veritest.com/ReportFiles/Pivotal%5FeRelationship%5FsReport.pdf" rel="nofollow">Windows 2000 certification</a>. The look and feel in this instance only refers to any visible installer that we present. Even the specifications themselves imply things in the descriptions that are not really covered in the title of the requirement.</p> <p>1.5 <a href="http://msdn.microsoft.com/en-us/library/aa372825%28VS.85%29.aspx" rel="nofollow">The application should not read from or write to Win.ini, System.ini, Autoexec.bat or Config.sys</a></p> <p>excerpt: </p> <p>If your application uses information that you do not want to put in the registry, create a private initialization file and place it in the directory with the application's executable files. You can easily manage the installation of <em>a private .ini file, as well as add or remove information from existing .ini files</em>, by using Windows Installer to install your application. </p> <p>Any feedback would be appreciated.</p>
<p>For the look and feel, call this at the beggining of your <code>main()</code> function:</p> <pre><code> log.info("Setting java look and feel"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.warn("Could not set system look and feel", e); } // Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); </code></pre>
Add new attribute (element) to JSON object using JavaScript <p>How do I add new attribute (element) to JSON object using JavaScript?</p>
<p>JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.</p> <p>To add a property to an existing object in JS you could do the following.</p> <pre><code>object["property"] = value; </code></pre> <p>or </p> <pre><code>object.property = value; </code></pre> <p>If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.</p>
daemon threads in an app container <p>I read in <a href="http://www.igniterealtime.org/community/message/189500" rel="nofollow">a post</a> to the Smack forum recently that </p> <blockquote> <p>Starting daemon threads in a Java EE server is a big no no</p> </blockquote> <p>Basically Smack's XMPPConnection starts one daemon thread to monitor incoming data &amp; another to send outgoing data from/to the jabber server respectively. Is it reasonable to use daemon threads to listen for write/reads in this scenario ? </p>
<p>Yes, XMPPConnection creates two threads--one for listening/reading and one for writing. But these only live as long as the XMPPConnection instance, which I assume is not forever. </p> <blockquote> <p>"Starting daemon threads in a Java EE server is a big no no"</p> </blockquote> <p>Are you writing spec compliant EJB? If so, then this applies. The spec says don't do it. EJB 2.1 specification: </p> <blockquote> <p>"The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups."</p> </blockquote> <p>Or is it just a webapp that happens to be running in Tomcat? If this is the case, then I do not see any fundamental problem. Without the threads, your Smack client would be unable to communicate with the server. </p>
Need ad-hoc reporting component <p>We need some simple ad-hoc reporting solution for our ASP.NET web-site.</p> <p>Just an ability to build a query with user friendly interface, then show the result of this query in some table and maybe export it to Excel or print.</p> <p>The solution must be quite easy for end users (our site visitors) who know nothing about databases, SQL and other tech stuff.</p>
<p><a href="http://devtools.korzh.com/eq/dotnet/">EasyQuery.NET</a> may suit your needs. It is proprietary but they have free version as well.</p>
How do I find the smallest item in an array? <p>I have an array, and need to find the index of the smallest item, using Java or C, without altering the content or ordering of the array.</p> <p>For example, with the input:</p> <pre><code>a = [2, 2, 2, 3, 3, 4, 3] </code></pre> <p>0 should be returned.</p> <p>I am unsure how to do this, can anybody help?</p>
<blockquote> <p>It should return me the array position of the smallest number.</p> </blockquote> <p>Simply iterate through the array, keeping track of whether a particular index has a smaller value than the smallest one encountered so far.</p> <p>In pseudocode:</p> <pre><code>j = 0 for i = 1 ... arr.length: if arr[i] &lt; arr[j]: j = i return j // j now contains the index of the smallest value in the array. </code></pre>
ASP.NET MVC retrieving route to controller, action and parameters <p>In ASP.NET MVC how can I generate a URL to a specific controller and action along with other parameters. The RedirectToAction allows me to redirect, but I would like to retrieve this URL instead from within my controller.</p> <p>I tried using:</p> <pre><code>Url.Action("Page", "Administrator", New With {.page = _currentPage}) </code></pre> <p>But that returned a link like /Administrator/Page?page=2 whereas I was hoping to retrieve something like /Administrator/Page/2</p> <p>I've searched countless forums and I'm sure there is something around for this, but I cannot find it for the life of me.</p> <p>Thanks!</p>
<p>What do your routes look like? The standard route expects an id as the third parameter. If you haven't changed your routes, try using:</p> <pre><code>Url.Action( "Page", "Administrator", New With { id = _currentPage } ) </code></pre>
How does the DiggBar work? <p>How does the DiggBar work? </p> <p>I'm trying to make an ASP.NET MVC DiggBar clone just for learning purposes and does anyone have a suggestion on how to specify the url of the content for the lower frame? How would you go about constructing that in MVC?</p> <p>Also, I know that it is an iFrame, but how do they position it so regardless of scrolling it stays positioned at the top? Is it CSS magic?</p> <p><img src="http://imgur.com/IBFBW.png" alt="alt text" /></p> <p>Edit: I'm not interested in whether or not you like them. I am not putting one into production and I'm not asking for whether they are good design or not. I simply ~want~ to make one. </p> <p>I find the DiggBar useful and I like it. Hell, you can turn it off in two clicks! Similarly, reddit has a reddit bar which is opt-in (probably better approach).</p>
<p>The basic <code>html</code> is:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #toolbar {position: fixed; top: 0; height: 40px; width: 100%; ... } #page {width: 100%; height: 100%;} &lt;/style&gt; &lt;/head&gt; &lt;div id="toolbar"&gt; All your toolbar stuff here. &lt;/div&gt; &lt;iframe id="page" name="page" src="http://url.to/page" frameborder="0" noresize="noresize"&gt;&lt;/iframe&gt; &lt;/html&gt; </code></pre> <p>You would have a slug on your own URLs that maps to the page's URL, e.g.<br /> <code>d1oKo3 =&gt; <a href="http://news.bbc.co.uk/2/hi/technology/7991708.stm" rel="nofollow">http://news.bbc.co.uk/2/hi/technology/7991708.stm</a></code></p> <p>All your view would have to do is look up the mapping and put the page's URL into the <code>iframe</code>'s <code>src</code>. Just make sure you have a way for users to opt out, as some people don't like this sort of toolbar.</p>
"Administer Web Site" equivalent for IIS deployment <p>During development, i can easily manage my users/roles/smtp etc using the "Administer Web Site" or "ASP.net configuration "command in Visual Studio. Once the site is deployed to a IIS server, How can i get the same functionality (user and role management).</p> <p>I am using IIS 6</p> <h1>Edit 1</h1> <p>My Server doesnt have the web server executable mentioned in the blog post (JP's response). So i copied it from my dev machine. but it still isnt working. The server is crashing with error:</p> <pre><code>Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'WebDev.WebHost, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f 11d50a3a' or one of its dependencies. The system cannot find the file specified. </code></pre>
<p>The IIS admin tools will be available on the production server as well. <a href="http://blogs.neudesic.com/blogs/phil%5Fscott/archive/2006/07/04/187.aspx" rel="nofollow">Here is a blog post</a> on the ASP.NET config. web site.</p> <p>Edit for comment:</p> <p>I don't think you can just copy the exe over. I think you need to at least install <a href="http://www.microsoft.com/express/download/" rel="nofollow">visual web developer</a>. That will ensure that all the dependencies are installed as well.</p>
SqlConnectionStringBuilder form in .net C# <p>I am wondering how I can add DATA LINK form to my WIN application. You know those forms where Users can choose on witch SQL server they going to connect and what type of security they going to use and on wht database. </p> <p>Something like on this picture <img src="http://img186.imageshack.us/img186/7259/datalink.png" alt="alt text" /></p>
<p>You can do it through some COM Introp...but then you have to pull in a bunch of Interop assemblies into your project which can be a drag. This code will show the dialog using reflection instead.</p> <pre><code>public static string ShowDialog( IWin32Window owner, string connectionString ) { Type dlType = Type.GetTypeFromProgID( "DataLinks", true ); Type acType = Type.GetTypeFromProgID( "ADODB.Connection", true ); object form = Activator.CreateInstance( dlType ); object connection = Activator.CreateInstance( acType ); acType.InvokeMember( "ConnectionString", BindingFlags.Public | BindingFlags.SetProperty, null, connection, new object[]{ connectionString } ); object result = dlType.InvokeMember( "PromptEdit", BindingFlags.Public | BindingFlags.InvokeMethod, null, form, new object[]{ connection } ); if( result != null &amp;&amp; (bool)result ) return acType.InvokeMember( "ConnectionString", BindingFlags.Public | BindingFlags.GetProperty, null, connection, new object[]{} ) as string; return null; } </code></pre> <p>This basically translates to the following VB Script</p> <pre><code>form = GetObject( "DataLinks" ) connection = GetOBject( "ADODB.Connection" ) connection.ConnectionString = "existing connection" form.PromptEdit( connection ) Return connection.ConnectionString </code></pre>
Should I call my validation script in the prebuild section of my ccnet.config? <p>I have a ccnet.config section which I had implemented for a demo purpose. So I have a simple validation check which is done before my build is being triggered. So if the validation passes then my build starts of successfully.So validation check is to count the number of '#defines' present in a single .c file which is <code>a.c</code> for example. I had achieved this using VB scripts(.vbs) which is called with the help of .bat files.</p> <p>So my doubt is </p> <ol> <li>If it is correct to call my .bat file in the ccnet.config file in the prebuild section.</li> <li>If I am able to get the return value, ie. the number of #defines in a .c file into a variable in my .bat file, how should I proceed with comparing or validating this return value against a fixed known value?</li> </ol> <p>I hope I am able to convey my doubts clearly. Please get back to me if you need any more clarification.</p>
<p>The prebuild section is executed before the source is updated, so you probably want to call your bat file in the tasks section instead. </p> <p>I would make the vbs/bat file do the comparing/validating as well as the counting, then you just have to exit with an errorlevel > 0 to indicate that the build should fail.</p> <p>Also, ccnet have very good documentation <a href="http://confluence.public.thoughtworks.org/display/CCNET/Project%2BConfiguration%2BBlock" rel="nofollow">here</a>.</p>
Resized images not smooth in flex <p>I am loading images in flex 3.0 , but when they are resized they look grainy and distortered . Can i give some sort of effect or dsomething to fix this .thanks </p>
<p><a href="http://blog.flexmonkeypatches.com/2007/02/05/scaling-an-image-with-smoothing/" rel="nofollow">Try this site. Flex Monkey Patches</a></p>
The deserializer has no knowlege of any type that maps to this contract <p>I'm trying to serialize and deserialize a tree of Node objects. My abstract "Node" class as well as other abstract and concrete classes that derive from it are defined in my "Informa" project. In addition, I've created a static class in Informa for serialization / deserialization. </p> <p>First I'm deconstructing my tree into a flat list of type <strong>Dictionary(guid,Node)</strong> where guid is the unique id of Node.</p> <p>I am able to serialize all my Nodes with out a problem. But when I try to deserialize I get the following exception.</p> <blockquote> <p>Error in line 1 position 227. Element '<a href="http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value" rel="nofollow">http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value</a>' contains data of the 'Informa:Building' data contract. The deserializer has no knowlege of any type that maps to this contract. Add the type corresponding to 'Building' to the list of known types - for example, by usying the KnownTypeAttribute or by adding it to the list of known types passed to DataContract Serializer.</p> </blockquote> <p>All classes that derive from Node, including Building, have the <strong>[KnownType(typeof(type t))]</strong> attribute applied to them. </p> <p>My serialization and deserialization methods are below:</p> <pre><code>public static void SerializeProject(Project project, string filePath) { try { Dictionary&lt;Guid, Node&gt; nodeDic = DeconstructProject(project); Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); //serialize DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary&lt;Guid, Node&gt;),"InformaProject","Informa"); ser.WriteObject(stream,nodeDic); // Cleanup stream.Close(); } catch (Exception e) { MessageBox.Show("There was a problem serializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error); throw e; } } public static Project DeSerializeProject(string filePath) { try { Project proj; // Read the file back into a stream Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary&lt;Guid, Node&gt;), "InformaProject", "Informa"); Dictionary&lt;Guid, Node&gt; nodeDic = (Dictionary&lt;Guid, Node&gt;)ser.ReadObject(stream); proj = ReconstructProject(nodeDic); // Cleanup stream.Close(); return proj; } catch (Exception e) { MessageBox.Show("There was a problem deserializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } </code></pre>
<blockquote> <p>All classes that derive from Node, including Building, have the [KnownType(typeof(type t))] attribute applied to them.</p> </blockquote> <p><code>KnownType</code> is usually applied to the <em>base</em> type - i.e.</p> <pre><code>[DataContract, KnownType(typeof(Building)), ...] abstract class Node { ... } </code></pre> <p>(note - you can also specify the known-types in the <code>DataContractSerializer</code> constructor, without requiring attributes)</p> <p><strong>EDIT RE YOUR REPLY</strong></p> <p>If the framwork class doesn't know about all the derived types, then you need to specify the known types when creating the serializer:</p> <pre><code>[DataContract] abstract class SomeBase { } [DataContract] class Foo : SomeBase { } [DataContract] class Bar : SomeBase { } ... // here the knownTypes argument is important new DataContractSerializer(typeof(SomeBase), new Type[] { typeof(Foo), typeof(Bar) }); </code></pre> <p>This can be combined with (for example) <code>preserveObjectReferences</code> etc by replacing the <code>null</code> in the previous example.</p> <p><strong>END EDIT</strong></p> <p>However, without something reproducible (i.e. <code>Node</code> and <code>Building</code>), it is going to be hard to help much.</p> <p>The other odd thing; trees structures are <em>very well suited</em> to things like <code>DataContractSerializer</code> - there is usually no need to flatten them first, since trees can be trivially expressed in xml. Do you really need to flatten it?</p> <p><hr /></p> <p>Example:</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Xml; [DataContract, KnownType(typeof(Building))] abstract class Node { [DataMember] public int Foo {get;set;} } [DataContract] class Building : Node { [DataMember] public string Bar {get;set;} } static class Program { static void Main() { Dictionary&lt;Guid, Node&gt; data = new Dictionary&lt;Guid, Node&gt;(); Type type = typeof(Dictionary&lt;Guid, Node&gt;); data.Add(Guid.NewGuid(), new Building { Foo = 1, Bar = "a" }); StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { DataContractSerializer dcs = new DataContractSerializer(type); dcs.WriteObject(xw, data); } string xml = sw.ToString(); StringReader sr = new StringReader(xml); using (XmlReader xr = XmlReader.Create(sr)) { DataContractSerializer dcs = new DataContractSerializer(type); Dictionary&lt;Guid, Node&gt; clone = (Dictionary&lt;Guid, Node&gt;) dcs.ReadObject(xr); foreach (KeyValuePair&lt;Guid, Node&gt; pair in clone) { Console.WriteLine(pair.Key + ": " + pair.Value.Foo + "/" + ((Building)pair.Value).Bar); } } } } </code></pre>
problem with mvc beginform <p>I have two dropdowns in my form. Selected values from this dropdowns should be send to the proper route. One is called "category" and second is called "status". When I send my form I don't get expected:</p> <p>Home/List/category/status adress</p> <p>but something like this:</p> <p>Home/List?category=category&amp;status=status</p> <p>how I can solve this? thanx</p>
<p>If you have parameters appended as a query string this means they don't have a place in the route so you have to setup a route for them. Somewhere in your route you need to have a place for them to fall.</p> <p>You would need to add a route or change the default one to look like this...</p> <pre><code>routes.MapRoute( "MyRouteName", "Home/List/{category}/{status}", new { category = "default", status = "alsoDefault" } ); routes.MapRoute( "MyRouteName", "{controller}/{action}/{category}/{status}", new { controller = "Home", action = "Index", category = "default", status = "alsoDefault" } ); </code></pre>
Is there ever a good reason to use Insertion Sort? <p>For general-purpose sorting, the answer appears to be no, as quick sort, merge sort and heap sort tend to perform better in the average- and worst-case scenarios. However, insertion sort appears to excel at incremental sorting, that is, adding elements to a list one at a time over an extended period of time while keeping the list sorted, especially if the insertion sort is implemented as a linked list (O(log n) average case vs. O(n)). However, a heap seems to be able to perform just (or nearly) as well for incremental sorting (adding or removing a single element from a heap has a worst-case scenario of O(log n)). So what exactly does insertion sort have to offer over other comparison-based sorting algorithms or heaps?</p>
<p>From <a href="http://www.sorting-algorithms.com/insertion-sort" rel="nofollow">http://www.sorting-algorithms.com/insertion-sort</a>:</p> <blockquote> <p>Although it is one of the elementary sorting algorithms with O(n<sup>2</sup>) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead).</p> <p>For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as merge sort or quick sort.</p> </blockquote>
Is ASP.NET MVC 1.0 Futures beta/preview code? <p>I understand that the "1.0" in "ASP.NET MVC 1.0 Futures" means that it is the ASP.NET MVC Futures built against the ASP.NET MVC 1.0 RTW (final/release to web). What I'd like to know is whether the Futures code is solid enough to treat as 1.0 / gold quality?</p> <p>We're about to jump into ASP.NET MVC for the first time and it came up that we should consider adding Futures to our build. Problem is, if it's alpha code I'm wondering if it would be wise; stability is going to be very important for us.</p>
<p>It is the official release, not the beta. However, like any Microsoft product, 2.0 will always better if you can wait, but as far as your question concerned, it's the full release.</p>
Good Java community and resource <p>I've just started learning Java as part of my uni course, and am so far really liking it. I did a quick search to try and find a Java Community online, but haven't really had any luck. I was looking for something along the lines of gotoandlearn.com and www.kirupa.com like the flash communities have. </p> <p>Can anyone recommend a good starting point and friendly place for a java n00b?</p> <p>Thanks.</p>
<p>You can try javaranch.com. It is one of most active Java community on Internet.</p>
Which SOAP XML object serialization library for Java would you recommend? <p>Which Java SOAP XML object serialization library would you recommend for <strong>Java object exchange</strong> with other platforms / languages (.NET, Delphi)?</p> <p>Communication scenarios could look like this:</p> <ul> <li>Java object writer -> SOAP XML text -> .NET or Delphi object reader</li> <li>.NET or Delphi object writer -> SOAP XML text -> Java object reader</li> </ul> <p>I know there is the XStream XML serialization library and JSON as alternative solutions, however since Delphi and .Net have built-in support for SOAP XML serialized objects, this would offer a 'standardized' way with support for advanced features like nested objects, arrays and so on.</p> <p><strong>Edit:</strong> Meanwhile, I found <strong>JAXB</strong> - (https://jaxb.dev.java.net/), <strong>JAXMe</strong>, and <strong>JiBX</strong> - Binding XML to Java Code(<a href="http://jibx.sourceforge.net/" rel="nofollow">http://jibx.sourceforge.net/</a>). But they do not generate SOAP serialized XML by default.</p> <p>A possible solution would be a web service library which is able to run without a HTTP server, and offers a simple file interface for the SOAP XML content (not a complete request, just a serialized object). <strong>Axis 2</strong> and <strong>CXF</strong> look very interesting.</p>
<p>I prefer JAX-WS (with JAXB 2.1 databinding) over the other liberaries I've used (JAX-RPC, Axis 1 and 2, but not XFire). The JAXB 2 databinding uses generics, which makes for a pleasant mapping of properties with a maxoccurs > 1. JAX-WS itself is reasonably well documented and provides a reasonably good API. The method and parameter annotations can get a bit out of hand in some cases - XML hell in annotation form. It usually isn't so bad.</p> <p>One of the nice aspects of the JAX-WS stack is project Metro, which Sun co-developed with Microsoft and interoperates well with the web service support .NET 3.0, going so far as to implement MTOM in a workable fashion.</p>
Create Weak Multimap with Google Collections <p>Is there an equivalent to the nice MapMaker for MultiMaps? currently i create the cache like this:</p> <pre><code> public static Map&lt;Session,List&lt;Person&gt;&gt; personCache = new MapMaker().weakKeys().makeMap(); </code></pre> <p>the whole point of MultiMap is to avoid the nested List Values. is there any way to construct the multimap with weak keys?</p>
<p>Unfortunately not. Yet. Could you file a MultimapMaker feature request in our issues db? <a href="http://google-collections.googlecode.com" rel="nofollow">http://google-collections.googlecode.com</a></p>
Why doesn’t url rewrite work in server <p>In asp.net 3.5, I'm rewriting the url</p> <pre><code> http://www.dotoobeta/blogs/1108 </code></pre> <p>to the following</p> <pre><code> http://www.dotoobeta/blogs/blogs.aspx </code></pre> <p>I am using the <code>UrlRewritingNet.UrlRewriter.dll</code> and it works fine locally, but it is not work on my other server. I already modified the configuration in IIS also.</p> <p>What is the solution?</p>
<p>Perhaps your server is not configured to route requests like <a href="http://www.dotoobeta/blogs/1108" rel="nofollow">http://www.dotoobeta/blogs/1108</a> through ASP.NET pipeline. If you have IIS 6 or higher on the server, you can configure wildcard handler and handle everything via ASP.NET. Don't forget to uncheck "verify that file exists" checkbox, or it won't work for nonexisting paths. </p>
Is double-checked locking safe in Ruby? <p>This <a href="http://en.wikipedia.org/wiki/Double%5Fchecked%5Flocking%5Fpattern" rel="nofollow">article</a> states that double-checked locking is unsafe on certain language/hardware combinations when a shared variable can be updated with a reference to an object that is only partially initialized. </p> <p>I was wondering: does this also apply to Ruby? Is this something that varies by the Ruby implementation on the platform that it is run on or is the correct behavior detailed in the language specification?</p>
<p>Which implementation of Ruby? Ruby 1.8, 1.9, and JRuby have quite different threading implementations so it may be impossible to say.</p> <p>I don't have the answer for your question, but it appears that you might be trying to write fast concurrent code in Ruby. My experiences with Ruby 1.8 is that this isn't a reasonable goal. Ruby 1.9 may be better, but still has a global interpreter lock like Python.</p> <p>If you are writing Ruby code where you are considering these sort of potentially unsafe optimizations to wring out some extra performance, you should probably consider using another language. Idiomatic Ruby tends to emphasize readability and expressiveness before efficiency and speed. Trying to wring speed increases and increased reliability out of the MRI has been an exercise in frustration for me.</p> <p>I've been working on a Ruby project for awhile that has just entered the phase where we are seriously looking at optimization. Running the project in JRuby and replacing the bottlenecks implemented in Ruby with Java libraries resulted in a pretty remarkable increase in speed and reliability with relatively little effort on our part.</p> <p>JRuby is not perfect, but its Java integration has proven to be helpful and easy. If it is impossible to use JRuby for your project, or you are comfortable with C but not Java, and sure you can write safe C without memory leaks, writing a C extensions to Ruby 1.8 or 1.9 may be the best path.</p> <p>I apologize if this question was completely academic in nature. Perhaps if you could let us know what, exactly, you're trying to do?</p>
Show YouTube video in a Drupal Section <p>Thanks to <a href="http://stackoverflow.com/questions/736755/multiple-sections-in-content-block-for-drupal">the help of SOers</a>, now I can create a few sections in a Drupal page using <a href="http://drupal.org/project/panels" rel="nofollow">Panels module</a>. I want to embed a YouTube video inside one of the section, anyway to do this? </p>
<p>Paste the "embed" code directly into the node body and set the Input format to be Filtered HTML. No need for any additional modules.</p>
send form data as web service in symfony <p>I am making a restrictive portal to a WiFi network using symfony, and I want to send a form as web service to other sites that want to use this portal. How should I solve this? I realize I could go the SOAP/WSDL route, but since symfony is already RESTful, it seems to me I could go the RESTful route with considerably less pain and loss of performance.</p> <p>Right now, I have a working form, but I've only made a casual attempt to bring the form to a remote site by using cURL. The form does not work remotely since the routing is not set up correctly (I think). Can someone help me with this?</p> <p>Thanks.</p>
<p>to call restfull service somewhere you simply call its URL and read result. Do you have any example of what exactly is not working? Does "other" service support restfull calls? :) I hope so. </p> <p>Calling rest service is really as easy as opening a website with some parameters in URL. So I am wondering what should not work. You can use some simplexmlreader or such to read restful services directly if you don't have blocked access to that remote service.</p>
C/C++: Array size at run time w/o dynamic allocation is allowed? <p>I've been using C++ for a few years, and today I don't know if this is a mere brainfart or what, but how can this be perfectly legal:</p> <pre><code>int main(int argc, char **argv) { size_t size; cin &gt;&gt; size; int array[size]; for(size_t i = 0; i &lt; size; i++) { array[i] = i; cout &lt;&lt; i &lt;&lt; endl; } return 0; } </code></pre> <p>Compiled under GCC. How can the size be determined at run-time without new or malloc? Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error. Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5: Only constants can be used to declare the size of automatic and static arrays.</p> <p>Enlight me.</p>
<p>This is valid in C99. </p> <p>C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.</p> <p>Note that this is different from <code>malloc</code> and <code>new</code>. <code>gcc</code> allocates the array on the stack, just like it does with <code>int array[100]</code> by just adjusting the stack pointer. No heap allocation is done. It's pretty much like <a href="http://msdn.microsoft.com/en-us/library/wb1s57t5(VS.80).aspx"><code>_alloca</code></a>.</p>
LINQ: How to perform an update like UPDATE <T> SET Update(<T>, <T>) SELECT FROM clause in LINQ? <p>I want to update and insert some records based on a csv I read. The insert is not a problem, but how to update a bunch of data in a single statement? I have not clear how to join them.</p> <pre><code>Update Item Set Name = t.Name From Item i, TextFile t Where i.ItemNo = t.ItemNo </code></pre> <p>For the Name = t.Name I created an private Item <code>UpdateItem(Item originalItem, Item newItem)</code> in which the logic for updating is present.</p> <p>I want to know to to call this functions and perform an db.SubmitChanges() with the changed records.</p> <p>Any help appreciated.</p>
<p>I'm making the assumption that TextFile is an in memory collection of objects that you've read from the CSV file and Items is a Table in the data context from your database. In that case I don't think you will be able to do an actual join without first fetching all of the items from the database into an in memory collection as well -- which may be a costly operation. The sample below selects just those items and its matching new name from the text file into a new collection, then iterates through that collection and sets the name on the item. It won't use your UpdateItem method.</p> <pre><code>var textFile = ...collection of objects from CSV... var textIDs = textFile.Select( t =&gt; t.ItemNo ); using (var db = new DataContext()) { var toUpdate = db.Items .Where( i =&gt; textIDs.Contains( i.ItemNo ) ) .ToList() // &lt;--- this will force the query .Select( i =&gt; new { Item = i, NewName = textFile.Where( t =&gt; t.ItemNo == i.ItemNo ) .Single() .Name }); foreach (var item in toUpdate) { item.Item.Name = item.NewName; } db.SubmitChanges(); } </code></pre>
Why prefer Properties to public variables? <p>Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?</p>
<p>We've had this subject before but I can't find anything now.</p> <p>In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.</p> <p>This is <em>bad</em> because it potentially costs a lot of money.</p> <p>Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.</p> <p>Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:</p> <pre><code>public DataType MyProperty { get; set; } </code></pre> <p>Will implement the necessary backing field and getter/setter code for you.</p> <p>I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.</p>
Exporting a web from to MS word <p>IS it possible to export a web page contents to MS word? If yes give some links to refer.</p>
<p>^A ^C ^V ^S ?</p>