input
stringlengths
51
42.3k
output
stringlengths
18
55k
How do I find the name of the calling function? <p>I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.</p> <p>In C++ how can I get the function name of the calling routine?</p>
<p>Here is a solution you can often use. It has the advantage of requiring no changes to the actual function code (<em>no adding calls to stackwalk functions, changing parameters to pass in function names, or linking to extra libraries.</em>). To get it working, you simply need to use a bit of preprocessor magic:</p> <h2>Simple Example</h2> <pre><code>// orignal function name was 'FunctionName' void FunctionNameReal(...) { // Do Something } #undef FunctionName #define FunctionName printf("Calling FunctionName from %s\n",__FUNCTION__);FunctionNameReal </code></pre> <p>You must rename your function temporarily, but see the note below for more suggestions. This will result in a <code>printf()</code> statement at each point of calling the function. Obviously, you have to make some arrangements if you are calling a member function, or need to capture the return value (<em>Like pass the function call and</em> <code>__FUNCTION__</code> <em>to a custom function that returns the same type...</em>), but the basic technique is the same. You might want to use <code>__LINE__</code> and <code>__FILE__</code> or some other preprocessor macros depending on which compiler you have. (This example is specifically for MS VC++, but probably works in others.)</p> <p>Also, you might want to put something like this in your header surrounded by <code>#ifdef</code> guards to conditionally turn it on, which can handle renaming the actual function for you as well.</p> <h1>UPDATE [2012-06-21]</h1> <p>I got a request to expand my answer. As it turns out, my above example is a bit simplistic. Here are some fully compiling examples of handling this, using C++. </p> <h2>Full Source Example with a return value</h2> <p>Using a <code>class</code> with <code>operator()</code> makes this pretty straight forward. This first technique works for freestanding functions with and without return values. <code>operator()</code> just needs to reflect the same return as the function in question, and have matching arguments.</p> <p>You can compile this with <code>g++ -o test test.cpp</code> for a non-reporting version and <code>g++ -o test test.cpp -DREPORT</code> for a version that displays the caller information.</p> <pre><code>#include &lt;iostream&gt; int FunctionName(int one, int two) { static int calls=0; return (++calls+one)*two; } #ifdef REPORT // class to capture the caller and print it. class Reporter { public: Reporter(std::string Caller, std::string File, int Line) : caller_(Caller) , file_(File) , line_(Line) {} int operator()(int one, int two) { std::cout &lt;&lt; "Reporter: FunctionName() is being called by " &lt;&lt; caller_ &lt;&lt; "() in " &lt;&lt; file_ &lt;&lt; ":" &lt;&lt; line_ &lt;&lt; std::endl; // can use the original name here, as it is still defined return FunctionName(one,two); } private: std::string caller_; std::string file_; int line_; }; // remove the symbol for the function, then define a new version that instead // creates a stack temporary instance of Reporter initialized with the caller # undef FunctionName # define FunctionName Reporter(__FUNCTION__,__FILE__,__LINE__) #endif void Caller1() { int val = FunctionName(7,9); // &lt;-- works for captured return value std::cout &lt;&lt; "Mystery Function got " &lt;&lt; val &lt;&lt; std::endl; } void Caller2() { // Works for inline as well. std::cout &lt;&lt; "Mystery Function got " &lt;&lt; FunctionName(11,13) &lt;&lt; std::endl; } int main(int argc, char** argv) { Caller1(); Caller2(); return 0; } </code></pre> <p><em>Sample Output (Reporting)</em></p> <pre><code>Reporter: FunctionName() is being called by Caller1() in test.cpp:44 Mystery Function got 72 Reporter: FunctionName() is being called by Caller2() in test.cpp:51 Mystery Function got 169 </code></pre> <p>Basically, anywhere that <code>FunctionName</code> occurs, it replaces it with <code>Reporter(__FUNCTION__,__FILE__,__LINE__)</code>, the net effect of which is the preprocessor writing some object instancing with an immediate call to the <code>operator()</code> function. You can view the result (in gcc) of the preprocessor substitutions with <code>g++ -E -DREPORT test.cpp</code>. Caller2() becomes this:</p> <pre><code>void Caller2() { std::cout &lt;&lt; "Mystery Function got " &lt;&lt; Reporter(__FUNCTION__,"test.cpp",51)(11,13) &lt;&lt; std::endl; } </code></pre> <p>You can see that <code>__LINE__</code> and <code>__FILE__</code> have been substituted. (I'm not sure why <code>__FUNCTION__</code> still shows in the output to be honest, but the compiled version reports the right function, so it probably has something to do with multi-pass preprocessing or a gcc bug.)</p> <h2>Full Source Example with a Class Member Function</h2> <p>This is a bit more complicated, but very similar to the previous example. Instead of just replacing the call to the function, we are also replacing the class.</p> <p>Like the above example, you can compile this with <code>g++ -o test test.cpp</code> for a non-reporting version and <code>g++ -o test test.cpp -DREPORT</code> for a version that displays the caller information.</p> <pre><code>#include &lt;iostream&gt; class ClassName { public: explicit ClassName(int Member) : member_(Member) {} int FunctionName(int one, int two) { return (++member_+one)*two; } private: int member_; }; #ifdef REPORT // class to capture the caller and print it. class ClassNameDecorator { public: ClassNameDecorator( int Member) : className_(Member) {} ClassNameDecorator&amp; FunctionName(std::string Caller, std::string File, int Line) { std::cout &lt;&lt; "Reporter: ClassName::FunctionName() is being called by " &lt;&lt; Caller &lt;&lt; "() in " &lt;&lt; File &lt;&lt; ":" &lt;&lt; Line &lt;&lt; std::endl; return *this; } int operator()(int one, int two) { return className_.FunctionName(one,two); } private: ClassName className_; }; // remove the symbol for the function, then define a new version that instead // creates a stack temporary instance of ClassNameDecorator. // FunctionName is then replaced with a version that takes the caller information // and uses Method Chaining to allow operator() to be invoked with the original // parameters. # undef ClassName # define ClassName ClassNameDecorator # undef FunctionName # define FunctionName FunctionName(__FUNCTION__,__FILE__,__LINE__) #endif void Caller1() { ClassName foo(21); int val = foo.FunctionName(7,9); // &lt;-- works for captured return value std::cout &lt;&lt; "Mystery Function got " &lt;&lt; val &lt;&lt; std::endl; } void Caller2() { ClassName foo(42); // Works for inline as well. std::cout &lt;&lt; "Mystery Function got " &lt;&lt; foo.FunctionName(11,13) &lt;&lt; std::endl; } int main(int argc, char** argv) { Caller1(); Caller2(); return 0; } </code></pre> <p>Here is sample output:</p> <pre><code>Reporter: ClassName::FunctionName() is being called by Caller1() in test.cpp:56 Mystery Function got 261 Reporter: ClassName::FunctionName() is being called by Caller2() in test.cpp:64 Mystery Function got 702 </code></pre> <p>The high points of this version are a class that decorates the original class, and a replacement function that returns a reference to the class instance, allowing the <code>operator()</code> to do the actual function call.</p> <p>Hope that helps someone!</p>
How do I replace an Int property with an Enum in Entity Framework? <p>I have an entity class that has a property with an underlying db column of datatype Int, however in reality I want this property to be an Enum. Is there any way to specify that this property returns an Enum?</p>
<p>Indirectly, like <a href="http://weblogs.asp.net/alexeyzakharov/archive/2008/09/18/enum-in-ado-net-entity-framework-v1.aspx" rel="nofollow">so</a>.</p> <p>Personally, I leave the storage int public (for example as <code>DbFoo</code>, where the enum property is <code>Foo</code>) - that way I can still write lambdas against the column for execution at the DB, for example:</p> <pre><code>where row.DbFoo == SomeConstant </code></pre> <p>If you don't expose the storage value, you can't do this as cleanly. You could equally leave it internal, and have some methods in the context to do the filtering... here's one I wrote earlier today:</p> <pre><code>public IOrderedQueryable&lt;User&gt; Administrators { get { return Users.Where(x =&gt; x.DbUserType == User.UserTypeAdmin) .OrderBy(x =&gt; x.Name); } </code></pre> <p>where <code>User.UserTypeAdmin</code> is my internal constant. In this case, I couldn't use a discriminated subclass, as it was interfering with ADO.NET Data Services.</p>
ActiveX component can't create object (comReport) <p>I am trying to print a pdf report and it is not printing and giving this error. Error Type: ComReport (0x800A01AD) ActiveX component can't create object</p> <p>I have registered the ComReport.dll with my OS.</p> <p>This works fine on our developemtn and production server but is not working locally on my machine. And I need for it to work on my local so I can debug some stuff and see what query is being ran. Page I am trying to debug is classic asp in .net 2003. I googled some stuff and they are just saying to make sure browser has ActiveX enabled...which it does!</p>
<p>Maybe it is a missing reference. You can use "Depends.exe" (Shipped with Visual Studio) to determine missing libraries.</p>
How can I detect a ThreadAbortException in a finally block? (.NET) <p>I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I'd also like to detect the ThreadAbortException. I've found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?</p> <pre> try { try { } finally { // critical logic } } catch(Exception ex) { // ThreadAbortException is not caught here, but exceptions thrown // from within the critical logic are } </pre>
<p>This is a curious problem.</p> <p>The code you posted <em>should</em> work. It seems there's some kind of optimization going on that decides not to call your catch handler.</p> <p>So, I wanted to detect the exception with this:</p> <pre><code>bool threadAborted = true; try { try { } finally { /* critical code */ } threadAborted = false; } finally { Console.WriteLine("Thread aborted? {0}", threadAborted); } Console.WriteLine("Done"); </code></pre> <p>(My actual code just slept in that critical code section, so I could be sure it would abort after that finally.)</p> <p>It printed:</p> <blockquote> <p>Thread aborted? False</p> </blockquote> <p>Hmmm, strange indeed!</p> <p>So I thought about doing a little bit more work there, to trick any "smart" optimizations:</p> <pre><code>bool threadAborted = true; try { try { } finally { /* critical code */ } threadAborted = AmIEvil(); } finally { Console.WriteLine("Thread aborted? {0}", threadAborted); } Console.WriteLine("Done"); </code></pre> <p>Where <code>AmIEvil</code> is just:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] static bool AmIEvil() { return false; } </code></pre> <p>Finally it printed:</p> <blockquote> <p>Thread aborted? True</p> </blockquote> <p>And there you have it. Use this in your code:</p> <pre><code>try { try { } finally { /* critical code */ } NoOp(); } catch (Exception ex) { // ThreadAbortException is caught here now! } </code></pre> <p>Where <code>NoOp</code> is just:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] static void NoOp() { } </code></pre>
What is a line of code? <p>I realize there's no definitely "right" answer to this question, but when people talk about lines of code, what do they mean? In C++ for example, do you count blank lines? comments? lines with just an open or close brace?</p> <p>I know some people use LoC as a productivity measure, and I'm wondering if there is a standard convention here. Also, I think there's a way to get various compilers to count lines of code - is there a standard convention there?</p>
<p>No, there is no standard convention, and every tool that counts them will be slightly different.</p> <p>This may make you ask, "Why then would I ever use LOC as a productivity measure?" and the answer is, because it doesn't really matter how you count a line of code, as long as you count them consistently you can get some idea of the general size of a project in relation to others.</p>
Easiest way to get a common base class from a collection of types <p>I'm building a custom property grid that displays the properties of items in a collection. What I want to do is show only the properties in the grid that are common amongst each item. I am assuming the best way to do this would be to find the the common base class of each type in the collection and display it's properties. Is there any easier way? Can you give me a code example of the best approach to do this?</p>
<p>You can do this with a method that keeps checking for common base classes. I wrote up this, quickly, using the BaseClass feature of the Type class. You don't have to use an array, a list or other IEnumerable can work with small modifications to this. </p> <p>I tested it with:</p> <pre><code>static void Main(string[] args) { Console.WriteLine("Common Types: " + GetCommonBaseClass(new Type[] {typeof(OleDbCommand), typeof(OdbcCommand), typeof(SqlCommand)}).ToString()); } </code></pre> <p>And got the right answer of DbCommand. Here is my code.</p> <pre><code> static Type GetCommonBaseClass(Type[] types) { if (types.Length == 0) return (typeof(object)); else if (types.Length == 1) return (types[0]); // Copy the parameter so we can substitute base class types in the array without messing up the caller Type[] temp = new Type[types.Length]; for (int i = 0; i &lt; types.Length; i++) { temp[i] = types[i]; } bool checkPass = false; Type tested = null; while (!checkPass) { tested = temp[0]; checkPass = true; for (int i = 1; i &lt; temp.Length; i++) { if (tested.Equals(temp[i])) continue; else { // If the tested common basetype (current) is the indexed type's base type // then we can continue with the test by making the indexed type to be its base type if (tested.Equals(temp[i].BaseType)) { temp[i] = temp[i].BaseType; continue; } // If the tested type is the indexed type's base type, then we need to change all indexed types // before the current type (which are all identical) to be that base type and restart this loop else if (tested.BaseType.Equals(temp[i])) { for (int j = 0; j &lt;= i - 1; j++) { temp[j] = temp[j].BaseType; } checkPass = false; break; } // The indexed type and the tested type are not related // So make everything from index 0 up to and including the current indexed type to be their base type // because the common base type must be further back else { for (int j = 0; j &lt;= i; j++) { temp[j] = temp[j].BaseType; } checkPass = false; break; } } } // If execution has reached here and checkPass is true, we have found our common base type, // if checkPass is false, the process starts over with the modified types } // There's always at least object return tested; } </code></pre>
Facebook sharer, pass in a comment? <p>Is it possible to post a description/comment variable to the facebook sharer url? It's only possible for url and title as far as I can figure out.</p>
<p>The parameters that you can pass to the actual <code>sharer.php</code> are "u" and "t" which are <code>url</code> and <code>title</code>. You can add <code>meta</code> tags to your page to get more info to appear in the sharer. To quote the <a href="http://www.facebook.com/share_partners.php" rel="nofollow">docs</a> (make sure you click the advance partners link):</p> <blockquote> <p>In order to make sure that the preview is always correctly populated, you should add the tags shown below to your html. An example news story could have the following: </p> <pre class="lang-html prettyprint-override"><code>&lt;meta name="title" content="Smith hails 'unique' Wable legacy"&gt; &lt;meta name="description" content="John Smith claims beautiful football ..." /&gt; &lt;link rel="image_src" href="http://www.onjd.com/design05/images/PH2/WableAFC205.jpg" /&gt; </code></pre> <p>As shown, title contains the preview title, description contains the preview summary and image_src contains the preview image. Please make sure that none of the content fields contain any html markup because it will be stripped out. For consistency's sake, please use the &lt;meta&gt; tag to provide text data for the preview, and the &lt;link&gt; tag for any source urls.</p> <p>The title and summary tags are the minimum requirements for any preview, so make sure to include these two.</p> </blockquote>
Prevent creation of class whose member functions are all static <p>All the member variables and member functions in my class ClassA are static. </p> <p>If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class. </p> <p>Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?</p> <p>Thank you</p>
<p>Instead of using a class with all static methods, you may be better off making the methods free-standing functions in a separate namespace. The call syntax would be the same:</p> <p><code>namespace::function()</code> instead of <code>classname::function()</code></p> <p>and you don't need to deal with someone trying to instantiate your class.</p>
How do I make LINQ to XML and HTML work together? <p>I have an html table </p> <pre><code> &lt;table border="0" width="100%"&gt; &lt;tr class="headerbg"&gt; &lt;th width="5%"&gt; No &lt;/th&gt; &lt;th width="30%"&gt; Name &lt;/th&gt; &lt;th width="20%"&gt; Department or Division &lt;/th&gt; &lt;th width="25%"&gt; Email &lt;/th&gt; &lt;th width="20%"&gt; Staff/Student &lt;/th&gt; &lt;/tr&gt; &lt;tr class="bg2"&gt; &lt;td&gt; 1 &lt;/td&gt; &lt;td&gt; &lt;strong&gt;&lt;a class="searchLink2" href="tel_search.php?fore=Dave&amp;amp;sur=Rumber"&gt;Dave Rumber&lt;/a&gt;&lt;/strong&gt; &lt;/td&gt; &lt;td&gt; Medical School &lt;/td&gt; &lt;td&gt; &lt;a class="searchLink2" href="mailto:Dave.Rumber@Home.com"&gt;Dave.Rumber@Home.com&lt;/a&gt; &lt;/td&gt; &lt;td&gt; Student&amp;nbsp; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Sometimes there will be more than one row of people results. I would like to be able to go through each row and pluck out the name and e-mail information and do some other processing. Put the data in a datagrid, and possibly into a database.</p> <p>I guess my question is how do I do this? </p> <pre><code> string table = GetContents(buffer); table = table.Replace("&amp;nbsp;", ""); table = table.Replace("&amp;", "&amp;amp;"); XElement inters = XElement.Parse(table); </code></pre> <p>I can put it into an XElement but I am not quite sure where to go from here! </p> <p>Thanks!</p>
<p>You can actually use an HTML table as a data source for OLE DB:</p> <p><a href="http://connectionstrings.com/html-table" rel="nofollow">http://connectionstrings.com/html-table</a></p> <p>Full Disclosure: I haven't actually tried this - but I'm guessing it'll be much easier than trying to parse XML out of HTML.</p>
Open-source IDE's with Git support <p>I'm having trouble finding an open-source IDE with support for Git. Are there any that you could point me to or recommend?</p>
<p>There's an <a href="http://www.eclipse.org/egit/" rel="nofollow">Eclipse plugin in progress</a>.</p>
.NET Web Service Best Practice for multiple developers <p>We have a large ASP.NET project consisting of several hundred reports. We are in the process of moving all the SQL Queries (running against an Oracle Database) into three web services. The web services are categorized by command, selections and report queries. We have to deploy a sub-set of our project using a SQL*Server backend to several locations that are disconnected from the Internet. Therefore, having all connections to the database and queries in the web services makes the application manageable and we can pull the sub-set of reports and not have to modify the code. The project is under source control using Serena ChangeMan software. </p> <p>The issue is we have several programmers and they all need check out the web services files to work on their items. We have just implemented branching, but it is slowly becoming a nightmare. We have monthly production deliveries and sometimes items that are supposed to go into the monthly build get held up until next month. The merging has become a manual process.</p> <p>I have conduct Internet Searches and I’m surprised that I have not been able to find any good “Best Practice” web services architecture white pages. There are many big companies that must have faced these issues. </p> <p>Do most large development groups use branching? I did read that Visual Studio Team System Database Edition could provide standard code that will allow the application to connect to different databases. Would purchasing Team System be the best method? Or does anyone know where I can find documentation that will help us address these issues? </p> <p>Thank you, Lorie</p>
<p>This problem would seem to be quite independent of the purpose of the software. The issue here is that you have a small, finite number of files that multiple developers will be working with on a daily basis. I do not have experience with Serena ChangeMan software nor TFS other than playing around with it. I do have experience with a couple of version control systems that use a merge/commit model: <strong><a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow">CVS</a></strong> and <strong><a href="http://en.wikipedia.org/wiki/Subversion_(software)" rel="nofollow">Subversion</a></strong>. These are both excellent, free version control systems that are widely used. </p> <p>If you are unfamiliar with the merge/commit model, the idea here is that no single developer can "checkout" and lock a file for changes. Everyone can download and make changes to any file. When it is time to commit these changes to the source code database, the repository software will prevent a commit if other changes have been made to the file by another developer. The new version is then downloaded, and in most cases the changes are automatically merged with your changes. You re-test, and then you commit that version. This model is very successful and very scalable.</p> <p>Having said all of that, even the merge/commit model cannot solve the grief of having a small number of files with a lot of developers making changes to said files. I would recommend splitting your functionality into more web services. Perhaps instead of three, monolithic web services you might create three groups of related web services. I think this, coupled with using a version control system with merge/commit will solve your problems.</p> <p>CVS and Subversion servers run on Windows, Mac and Linux. There are a number of clients for each, available on a number of operating systems. These include stand-along clients, Visual Studio plug-ins, and shell plugins. Another plus is that both CVS and Subversion are available from the command line which makes scripting (think automated build) fairly easy.</p>
Is storing an array of objects in ASP.NET viewstate the best solution for this? <p>I'm wondering if storing the data in viewstate is a good idea for this given problem. He's a simplified example of what I am trying to achieve, firstly we have a Repeater control:</p> <pre><code>&lt;asp:Repeater id="Repeater1" runat="server"&gt; &lt;ItemTemplate&gt; &lt;asp:TextBox id="Name" runat="server" /&gt; &lt;asp:TextBox id="Age" runat="server" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; &lt;asp:TextBox id="NewPersonName" runat="server" /&gt; &lt;asp:TextBox id="NewPersonAge" runat="server" /&gt; &lt;asp:Buttin id="Button1" runat="server" Text="Add" OnClick"Button1_Click"/&gt; </code></pre> <p>To keep things simple I'll forego the databinding code, as this is working it loads in the current list of people and ages and binds perfectly.</p> <p>The problem is with the bottom 3 controls, what I want is for the user to be able to type in a new entry, click the add button and this would then be added to the Repeater, but not persisted to the database.</p> <p>The user should be able to add multiple names to the list and then click a Save button to commit all the new names in one click rather than committing for each entry.</p>
<p>Are you persisting the entire list from the database in the viewstate or just the uncommitted additions?</p> <p>If it's just the additions, then this is a fine use of viewstate.</p> <p>If the list from the DB isn't very large or volatile, then I guess that'd be OK, too.</p>
How does OpenID authentication work? <p>I am a little curious to know about how OpenID authentication works.</p> <p>Is there any difference between OpenID authentication and the authentication which sites use exclusively for themselves?</p>
<h2>What is OpenID?</h2> <blockquote> <p>OpenID is an open, <strong>decentralized</strong>, <strong>free</strong> framework for user-centric digital identity. OpenID takes advantage of already existing internet technology (URI, HTTP, SSL, Diffie-Hellman) and realizes that people are already creating identities for themselves whether it be at their blog, photostream, profile page, etc. With OpenID you can easily transform one of these existing URIs into an account which can be used at sites which support OpenID logins.</p> </blockquote> <p><a href="http://openid.net/what/">OpenID</a></p> <h2>Difference between OpenID and conventional authentification form?</h2> <p>The difference is that the identification will be decentralized to an external site (for example Wordpress, Yahoo, ...). The website will know whether or not the identification is OK and let you login. Conventional website authentication performs a comparison with data held in a private database, so your username and password can be used to login to this website only. With OpenID you can use the same credentials on multiple websites.</p> <h2>How it works?</h2> <ul> <li><a href="http://openid.net/pres/protocolflow-1.1.png">You can see the Flow of operation here (image)</a></li> <li><a href="http://www.windley.com/archives/2006/04/how_does_openid.shtml">Step-by-step activities here</a></li> <li><a href="http://tinisles.blogspot.com/2008/02/how-does-openid-work.html">Step-by-step activities here (other blog)</a></li> </ul> <h1>Steps</h1> <ol> <li>User connects to OpenID enabled website.</li> <li>User enters credential information.</li> <li>A POST is made with a BASE64 (website to provider)</li> <li>An answer is built (that contains expiration)</li> <li>The website redirects the user to the provider to login.</li> <li>User enters password and submit.</li> <li>Verification is done.</li> <li>Login!</li> </ol>
How do I do a join in SQL based on table name? <p>Ok, so we have a bunch of tables that are named like this:</p> <pre><code>training_data_001 training_data_002 training_data_003 training_data_004 training_data_005 </code></pre> <p>And then to find those we look at a field in another table, let's just call it master.training_type.</p> <p>Anyway, I was wondering if anyone knew of a way to do a weird table name based join with this kind of data. Something like this:</p> <pre><code>SELECT foo FROM master WHERE id = ? INNER JOIN training_data_${master.training_type} ON foo.id = training_data_${master.training_type}.foo_id </code></pre> <p>I know that I can do this on the client side, but it would be nice to have the db do it.</p> <p>Also note: it's SQL Server.</p> <p><strong>Update</strong>: I decided to just do it on the client side. Thanks anyway everyone.</p> <p>Thanks!</p> <p>-fREW</p>
<p>You can only use dynamic SQL to read master.training_type to build a string that you then execute using <code>EXEC (@stringvar)</code></p>
Large MySQL tables <p>For a web application I'm developing, I need to store a large number of records. Each record will consist of a primary key and a single (short-ish) string value. I expect to have about 100GB storage available and would like to be able to use it all.</p> <p>The records will be inserted, deleted and read frequently and I must use a MySQL database. Data integrity is not crucial, but performance is. What issues and pitfalls am I likely to encounter and which storage engine would be best suited to the task?</p> <p>Many thanks, J</p>
<p>Whatever solution you use, since you say your database will be write-heavy you need to make sure the whole table doesn't get locked on writes. This rules out MyISAM, which some have suggested. MyISAM will lock the table on an update,delete or insert. That means any client who wants to read from the table will have to wait for the write to finish. Dunno what the INSERT LOW PRIORITY does though, probably some hack around table-locking :-)</p> <p>If you simply must use MySQL, you'll want InnoDB, which doesn't lock on write. I dunno how MySQL does VACUUM's InnoDB tables (InnoDB is MVCC like PostgreSQL and so needs to clean up)... but you'll have to take that into consideration if you are doing a lot of updates or deletes. </p>
How do I pass pointers to a DLL using Win32:API? <p>I am trying to passing in 3 pointers to a DLL function. I have:</p> <pre> { $code=1; $len=100; $str=" " x $len; $function = new Win32::API(DLLNAME,'dllfunction','PPP','V'); $function->Call($code,$str,$len); } </pre> <p>The DLL is defined as <code>void dllfunction(int* a, char* str, int* len);</code> The DLL will modify all the variables pointed by the three pointers.</p> <p>However, I am segfaulting when I run this. The documentation for <a href="http://search.cpan.org/dist/Win32-API" rel="nofollow">Win32::API</a> specified that I should use actual variable name instead of the Perl variable references. Can anyone tell me what I am missing? Thanks.</p> <p>*more information:</p> <p>I added <code>printf()</code> in the DLL to print out the address of the three pointers, and <code>printf</code> in Perl to print out the reference of the three variables. And I get the following</p> <p>DLL : Code = 0x10107458 Error = 0x10046b50 str = 0x10107460</p> <p>Perl : Code = 0x101311b8 Error = 0x101312a8 str = 0x10131230</p> <p>Any idea why the DLL is getting the wrong addresses?</p> <p>****More information</p> <p>After much debugging, I found out that this is happening when returning from the DLL function. I added printf("done\n"); as the very last line of this DLL function, and this does output, then the program segfaults. I guess its happening in Win32::API? Has anyone experienced this?</p> <p>Also, I am able to access the initial variables of all the three variables from the DLL. So the pointer is passed correctly, but for some reason it causes a segfault when returning from the DLL. Maybe it's segfaulting when trying to copy the new data into the Perl variable?</p>
<p>AH!! I figured it out.</p> <p>The problem was this </p> <blockquote> <ol> <li>And optionally you can specify the calling convention, this defaults to '__stdcall', alternatively you can specify '_cdecl'.</li> </ol> </blockquote> <p>The dll function was exported with extern "C" __declspec(dllexport) so I figured maybe I should be using '_cdecl' flag.</p> <p>Win32::API('dll','dllfunction','PPP','V','_cdecl');</p> <p>works!</p> <p>thanks everyone.</p>
SQL join: where clause vs. on clause <p>After reading it, this is <em>not</em> a duplicate of <a href="http://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins">Explicit vs Implicit SQL Joins</a>. The answer may be related (or even the same) but the <strong>question</strong> is different.</p> <p><hr /></p> <p>What is the difference and what should go in each?</p> <p>If I understand the theory correctly, the query optimizer should be able to use both interchangeably.</p>
<p>They are not the same thing.</p> <p>Consider these queries:</p> <pre><code>SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID WHERE Orders.ID = 12345 </code></pre> <p>and</p> <pre><code>SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID AND Orders.ID = 12345 </code></pre> <p>The first will return an order and its lines, if any, for order number <code>12345</code>. The second will return all orders, but only order <code>12345</code> will have any lines associated with it.</p> <p>With an <code>INNER JOIN</code>, the clauses are <em>effectively</em> equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning.</p>
In Javascript, what is the difference between indexOf() and search()? <p>Being fairly new to Javascript, I'm unable to discern when to use each of these.</p> <p>Can anyone help clarify this for me?</p>
<p>If you require a regular expression, use <code>search()</code>. Otherwise, <code>indexOf()</code> is going to be faster.</p>
How to determine if two nodes are connected? <p>I'm concerned that this might be working on an NP-Complete problem. I'm hoping someone can give me an answer as to whether it is or not. And I'm looking for more of an answer than just yes or no. I'd like to know why. If you can say,"This is basically this problem 'x' which is/is not NP-Complete. (wikipedia link)"</p> <p>(No this is not homework)</p> <p>Is there a way to determine if two points are connected on an arbitrary non-directed graph. e.g., the following</p> <pre><code>Well | | A | +--B--+--C--+--D--+ | | | | | | | | E F G H | | | | | | | | +--J--+--K--+--L--+ | | M | | House </code></pre> <p>Points A though M (no 'I') are control points (like a valve in a natural gas pipe) that can be either open or closed. The '+'s are nodes (like pipe T's), and I guess the Well and the House are also nodes as well.</p> <p>I'd like to know if I shut an arbitrary control point (e.g., C) whether the Well and House are still connected (other control points may also be closed). E.g., if B, K and D are closed, we still have a path through A-E-J-F-C-G-L-M, and closing C will disconnect the Well and the House. Of course; if just D was closed, closing only C does not disconnect the House.</p> <p>Another way of putting this, is C a bridge/cut edge/isthmus?</p> <p>I could treat each control point as a weight on the graph (either 0 for open or 1 for closed); and then find the shortest path between Well and House (a result >= 1 would indicate that they were disconnected. There's various ways I can short circuit the algorithm for finding the shortest path too (e.g., discard a path once it reaches 1, stop searching once we have ANY path that connects the Well and the House, etc.). And of course, I can also put in some artificial limit on how many hops to check before giving up.</p> <p>Someone must have classified this kind of problem before, I'm just missing the name.</p>
<p>Your description seems to indicate that you are just interested in whether two nodes are connected, not finding the shortest path.</p> <p>Finding if two nodes are connected is relatively easy:</p> <pre><code>Create two sets of nodes: toDoSet and doneSet Add the source node to the toDoSet while (toDoSet is not empty) { Remove the first element from toDoList Add it to doneList foreach (node reachable from the removed node) { if (the node equals the destination node) { return success } if (the node is not in doneSet) { add it to toDoSet } } } return failure. </code></pre> <p>If you use a hash table or something similar for toDoSet and doneSet, I believe this is a linear algorithm.</p> <p>Note that this algorithm is basically the mark portion of mark-and-sweep garbage collection.</p>
Adding a SOAP header to a SOAPpy request <p>Does anyone know how to do this? I need to add a header of the form:</p> <p> value1 value2 </p>
<p>As the question is phrased, it's hard to guess what the intention (or even the intended semantics) is. For setting headers, try the following:</p> <pre><code>import SOAPpy headers = SOAPpy.Types.headerType() headers.value1 = value2 </code></pre> <p>or</p> <pre><code>[...] headers.foo = value1 headers.bar = value2 </code></pre>
Transitions and setting up Layers/Scenes in cocos2d iPhone <p>I am looking to setup a transition between two levels(after one level is complete, use one of cocos2d's slick transition to transition into the next level). In my GameLayer implementation, I have methods setup to do things like [self buildLevel: 3] to build the playfield. What do I need to do to instantiate a new GameLayer or Layer node or GameScene or Scene node to be able to do things such as:</p> <p>GameLayer * nextLevelLayer;</p> <p>[nextLevelLayer buildLevel: 4];</p> <p>... do a transition between the level 3 and level 4</p> <p>Perhaps I've laid out my code in a complete misunderstanding of Objective C. I am assuming you can't setup a new GameLayer in the init code, as it will hang, continuously created new nodes. I probably have too much playfield setup code in my init code for the GameLayer, how do you guys usually handle it? Do you set a flag before scheduling the selector for the game's main loop, then if the flag is set, setup the level in the game's main loop, or is there a better way to go about it?</p> <p>Thanks in advance!</p>
<p>For those who might care, here's what I ended up doing:</p> <pre><code>GameScene * gs = [GameScene node]; [[Director sharedDirector] runScene: gs]; [[Director sharedDirector] replaceScene: [ShrinkGrowTransition transitionWithDuration:0.5 scene: gs]]; </code></pre> <p>This was done within the GameLayer implementation after a level was complete. </p>
Preventing automatic change of default-directory <p>As per <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/File-Names.html">the Emacs docs</a>, every time you open a file, Emacs changes <code>default-directory</code> to the directory containing that file. </p> <p>Then, if the cursor is in that buffer and you (for example) start SLIME, it uses <code>default-directory</code> as the current working directory for SLIME. If you try to open a new file, it opens the file with <code>default-directory</code> as your starting point.</p> <p>I want to be able to <code>M-x cd</code> or otherwise <code>cd</code> to a directory, and then never have Emacs change my current working directory to anything but that directory until I tell it otherwise. I want this to be global across all buffers, so that any time I'm doing something involving the current working directory, I know what it's set to regardless of where my cursor is at the moment. Is there a way to do this?</p>
<p>You could try using something like this:</p> <pre><code>(add-hook 'find-file-hook (lambda () (setq default-directory command-line-default-directory))) </code></pre>
Create a colored bubble/circle programmatically in ObjectiveC and Cocoa <p>Can anyone guide me in the correct way to build a colored bubble/circle programmatically?</p> <p>I can't use images as I need it to be able to be any color depending on user interaction.</p> <p>My thought was maybe to make a white circle image and then overlay a color on top of it. However I am not sure if this would work, or how to really go about it.</p> <p>If someone could point me the right direction I would appreciate it.</p>
<p>There are a couple steps to drawing something in Cocoa.</p> <p>First you need a path that will be used to define the object that you are going to be drawing. Take a look here <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html#//apple_ref/doc/uid/TP40003290-CH206-BBCHFJJG">Drawing Fundamental Shapes</a> for a guide on creating paths in Cocoa. You will be most interested in sending the "appendBezierPathWithOvalInRect" message to an "NSBezierPath" object, this takes a rectangle that bounds the circle you want to draw.</p> <p>This code will create a 10x10 circle at coordinates 10,10:</p> <pre><code>NSRect rect = NSMakeRect(10, 10, 10, 10); NSBezierPath* circlePath = [NSBezierPath bezierPath]; [circlePath appendBezierPathWithOvalInRect: rect]; </code></pre> <p>Once you have your path you want to set the color for the current drawing context. There are two colors, stroke and fill; stroke is the outline of the path and the fill is the interior color. To set a color you send "set" to an "NSColor" object.</p> <p>This sets the stroke to black and the fill to red:</p> <pre><code>[[NSColor blackColor] setStroke]; [[NSColor redColor] setFill]; </code></pre> <p>Now that you have your path and you have your colors set just fill the path and then draw it:</p> <pre><code>[path stroke]; [path fill]; </code></pre> <p>All of this will need to be done in a graphics context like in drawRect of a view perhaps. All of this together with a graphics context would look like this:</p> <pre><code>- (void)drawRect:(NSRect)rect { // Get the graphics context that we are currently executing under NSGraphicsContext* gc = [NSGraphicsContext currentContext]; // Save the current graphics context settings [gc saveGraphicsState]; // Set the color in the current graphics context for future draw operations [[NSColor blackColor] setStroke]; [[NSColor redColor] setFill]; // Create our circle path NSRect rect = NSMakeRect(10, 10, 10, 10); NSBezierPath* circlePath = [NSBezierPath bezierPath]; [circlePath appendBezierPathWithOvalInRect: rect]; // Outline and fill the path [circlePath stroke]; [circlePath fill]; // Restore the context to what it was before we messed with it [gc restoreGraphicsState]; } </code></pre>
Number of arrangements <p>Suppose we have <em>n</em> elements, <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, ..., <em>a</em><sub>n</sub>, arranged in a circle. That is, <em>a</em><sub>2</sub> is between <em>a</em><sub>1</sub> and <em>a</em><sub>3</sub>, <em>a</em><sub>3</sub> is between <em>a</em><sub>2</sub> and <em>a</em><sub>4</sub>, <em>a</em><sub><em>n</em></sub> is between <em>a</em><sub><em>n</em>-1</sub> and <em>a</em><sub>1</sub>, and so forth.</p> <p>Each element can take the value of either 1 or 0. Two arrangements are different if there are corresponding <em>a</em><sub><em>i</em></sub>'s whose values differ. For instance, when <em>n</em>=3, (1, 0, 0) and (0, 1, 0) are different arrangements, even though they may be isomorphic under rotation or reflection.</p> <p>Because there are <em>n</em> elements, each of which can take two values, the total number of arrangements is 2<sup><em>n</em></sup>.</p> <p><strong>Here is the question:</strong></p> <p>How many arrangements are possible, such that no two adjacent elements both have the value 1? If it helps, only consider cases where <em>n</em>>3. </p> <p>I ask here for several reasons:</p> <ol> <li>This arose while I was solving a programming problem</li> <li>It sounds like the problem may benefit from Boolean logic/bit arithmetic</li> <li>Maybe there is no closed solution.</li> </ol>
<p>Let's first ask the question "how many 0-1 sequences of length n are there with no two consecutive 1s?" Let the answer be A(n). We have A(0)=1 (the empty sequence), A(1) = 2 ("0" and "1"), and A(2)=3 ("00", "01" and "10" but not "11").</p> <p>To make it easier to write a recurrence, we'll compute A(n) as the sum of two numbers:<br/> B(n), the number of such sequences that end with a 0, and<br/> C(n), the number of such sequences that end with a 1.</p> <p>Then B(n) = A(n-1) (take any such sequence of length n-1, and append a 0)<br/> and C(n) = B(n-1) (because if you have a 1 at position n, you must have a 0 at n-1.)<br/> This gives A(n) = B(n) + C(n) = A(n-1) + B(n-1) = A(n-1) + A(n-2). By now it should be familiar :-)</p> <p>A(n) is simply the Fibonacci number F<sub>n+2</sub> where the Fibonacci sequence is defined by<br/> F<sub>0</sub>=0, F<sub>1</sub>=1, and F<sub>n+2</sub>= F<sub>n+1</sub>+F<sub>n</sub> for n &ge; 0.<br/></p> <p>Now for your question. We'll count the number of arrangements with a<sub>1</sub>=0 and a<sub>1</sub>=1 separately. For the former, a<sub>2</sub> &hellip; a<sub>n</sub> can be any sequence at all (with no consecutive 1s), so the number is A(n-1)=F<sub>n+1</sub>. For the latter, we must have a<sub>2</sub>=0, and then a<sub>3</sub>&hellip;a<sub>n</sub> is any sequence with no consecutive 1s that <em>ends with a 0</em>, i.e. B(n-2)=A(n-3)=F<sub>n-1</sub>.</p> <p>So <strong>the answer is F<sub>n+1</sub> + F<sub>n-1</sub>.</strong></p> <p><sub>Actually, we can go even further than that answer. Note that if you call the answer as<br/> G(n)=F<sub>n+1</sub>+F<sub>n-1</sub>, then <br/> G(n+1)=F<sub>n+2</sub>+F<sub>n</sub>, and <br/> G(n+2)=F<sub>n+3</sub>+F<sub>n+1</sub>, so even G(n) satisfies the same recurrence as the Fibonacci sequence! [Actually, any linear combination of Fibonacci-like sequences will satisfy the same recurrence, so it's not all that surprising.] So another way to compute the answers would be using:<br/> G(2)=3<br/> G(3)=4<br/> G(n)=G(n-1)+G(n-2) for n&ge;4.</p> <p>And now you can also use the <a href="http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html" rel="nofollow">closed form</a> F<sub>n</sub>=(&alpha;<sup>n</sup>-&beta;<sup>n</sup>)/(&alpha;-&beta;) (where &alpha; and &beta; are (1±√5)/2, the roots of x<sup>2</sup>-x-1=0), to get <br/> <strong>G(n) = ((1+√5)/2)<sup>n</sup> + ((1-√5)/2)<sup>n</sup>.</strong><br/> [You can ignore the second term because it's very close to 0 for large n, in fact G(n) is the <strong>closest integer to ((1+√5)/2)<sup>n</sup></strong> for all n&ge;2.] </sub></p>
How do I keep an NSPathControl updated with the path of the selected cell in an NSBrowser <p>I need to keep an NSPathControl updated with the currently selected path in an NSBrowser, but I'm having trouble figuring out a way of getting notifications when the path has changed from the NSBrowser. The ideal way to do this would just to be to observe the path key path in the NSBrowser, but that gives a KVO can only observe set<code>&lt;key&gt;</code> methods which return void message and no updates (setPath returns a bool success value).</p> <p>I also tried observing the selectedCell key path, but I'm not getting notifications when the selection there is changed.</p> <p>Is there some other really obvious way to do this that I'm missing?</p>
<p>Courtesy of Rob Keniger over at <a href="http://cocoadev.com/forums/comments.php?DiscussionID=600&amp;page=1#Item_1">Cocoa Dev</a>:</p> <blockquote> <p>Have you looked at the SimpleBrowser example in /Developer/Examples? It shows how to get the current selection when it is changed by the user, basically by just setting up the action of the NSBrowser.</p> </blockquote> <p>That is indeed the way to do it. Just implement a - (void)broswerClicked: method (including mapping it in interface builder) with whatever you want to happen each time the selection changes inside that method, e.g.</p> <pre><code>- (void)browserClicked:(id)browser { self.pathToSelectedCell = [browser path]; // NSPathControl is bound to pathToSelectedCell } </code></pre>
Using an epsilon value to determine if a ball in a game is not moving? <p>I have balls bouncing around and each time they collide their speed vector is reduced by the Coefficient of Restitution.</p> <p>Right now my balls CoR for my balls is .80 . So after many bounces my balls have "stopped" rolling because their speed has becoming some ridiculously small number. </p> <p>In what stage is it appropriate to check if a speed value is small enough to simply call it zero (so I don't have the crazy jittering of the balls reacting to their micro-velocities). I've read on some forums before that people will sometimes use an epsilon constant, some small number and check against that.</p> <p>Should I define an epsilon constant and do something like:</p> <pre><code>if Math.abs(velocity.x) &lt; epsilon then velocity.x = 0 </code></pre> <p>Each time I update the balls velocity and position? Is this what is generally done? Would it be reasonable to place that in my Vector classes setters for x and y? Or should I do it outside of my vector class when I'm calculating the velocities. </p> <p>Also, what would be a reasonable epsilon value if I was using floats for my speed vector?</p>
<p>A reasonable value for epsilon is going to depend on the constraints of your system. If you are representing the ball graphically, then your epsilon might correspond to, say, a velocity of .1 pixels a second (ensuring that your notion of stopping matches the user's experience of the screen objects stopping). If you're doing a physics simulation, you'll want to tune it to the accuracy to which you're trying to measure your system.</p> <p>As for how often you check - that depends as well. If you're simulating something in real time, the extra check might be costly, and you'll want to check every 10 updates or once per second or something. Or performance might not be an issue, and you can check with every update.</p>
Adobe Flex/AIR: Scrolling a sub-component, not the whole window <p>I'm developing an application with Adobe Flex and AIR, and I've been banging my head against the wall trying to figure out how to solve a scrolling issue.</p> <p>The basic structure of my main application window (simplified greatly) is this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" paddingTop="0" paddingRight="0" paddingBottom="0" paddingLeft="0" width="800" height="600" layout="vertical" verticalAlign="top" &gt; &lt;mx:VBox id="MainContainer" width="100%" height="100%"&gt; &lt;mx:Panel id="Toolbars" width="100%" height="25" /&gt; &lt;mx:HDividedBox width="100%" height="100%" &gt; &lt;mx:Panel id="Navigation" minWidth="200" height="100%" /&gt; &lt;mx:VBox id="MainContent" width="100%"&gt; &lt;mx:Panel width="100%" height="200" /&gt; &lt;mx:Panel width="100%" height="200" /&gt; &lt;mx:Panel width="100%" height="200" /&gt; &lt;mx:Panel width="100%" height="200" /&gt; &lt;mx:Panel width="100%" height="200" /&gt; &lt;/mx:VBox&gt; &lt;mx:Panel id="HelpContent" minWidth="200" height="100%" /&gt; &lt;/mx:HDividedBox&gt; &lt;mx:Panel id="FooterContent" width="100%" height="25" /&gt; &lt;/mx:VBox&gt; &lt;/mx:WindowedApplication&gt; </code></pre> <p>The trouble is that the "MainContent" box might contain a huge list of subcomponents, and the presence of that long list causes a vertical scrollbar to appear at the highest level of the GUI, surrounding the "MainContainer" vbox.</p> <p>It looks really silly, having scrollbars around the entire application window.</p> <p>What I'm looking for instead is a solution where the scrollbar is only applied to the "MainContent" vbox (as well as the Navigation and HelpContent panels, if their content stretches past the window bounds).</p> <p>I found a <a href="http://stackoverflow.com/questions/245292/best-way-to-size-containers-in-flex-to-obey-only-parent-containers-explicit-dim">related question</a> on StackOverflow, where the problem's solution was to use "autoLayout" and "verticalScrollPolicy" attributes on parent containers.</p> <p>So I tried adding autoLayout="false" and verticalScrollPolicy="off" attributes to all of the parent containers, as well as verticalScrollPolicy="on" to the "MainContent" vbox. But the end-result of that experiment was that the content was simply clipped from the main container (and a useless scrollbar with no thumb was added to the MainContent vbox).</p> <p>Anyone know how to solve this?</p>
<p>An HBox or a VBox will try as hard as possible to display its content without scroll bars. This forces a parent container (often all the way up to the main Application) to be the one that must scroll if the content is too large to fit in the available bounds.</p> <p>Behind the scenes, the HBox or VBox is setting the measuredMinWidth and measuredMinHeight properties in its measure() function to match the dimensions required by its children. The parent container will honor that recommendation and the task of scrolling moves up the display list.</p> <p>hasseg's solution works in many cases because it stops the container from measuring, but it's kind of hacky. Here's what you can do without building replacement subclasses for your containers. On the container instance that you want to scroll, <strong>set minWidth or minHeight to 0</strong>. This will take precedence over the measuredMinWidth or measuredMinHeight properties of that container, allowing the parent to set the actual size to something more manageable.</p>
Displaying foreign key relationships in Oracle 9i <p>Is there a command in oracle 9i that displays the foreign keys of a table and also the table that those foreign keys reference?</p> <p>I was searching, did not find anything but i found an equivalent command that works with MySql which is SHOW CREATE TABLE </p> <p>Is there an equivalent command for this within oracle's SQL?</p> <p>I appreciate your response, however I thought there was a really short way of doing this like MySql. </p>
<p>Here's another answer: The <code>dbms_metadata</code> package has a function that can return the DDL for a table definition.</p> <pre><code>SELECT dbms_metadata.get_ddl('TABLE', '&lt;table&gt;', '&lt;schema&gt;') FROM dual; </code></pre> <p>This package has apparently been available since Oracle 9.2</p> <p><a href="http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_metada.htm#1656" rel="nofollow">http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_metada.htm#1656</a></p>
Use "references" for multiple items of same type <p>So I'm teaching myself Ruby on Rails, with a PHP background. I've written a sloppy, proof-of-concept PHP application called "<a href="http://rezich.com/storybored" rel="nofollow">2NDP.</a>" I want to re-create this in Ruby on Rails (but more basic, more clean, and with a better interface), so I can learn some of the basics.</p> <p>2NDP is a website where you can basically write your own "Choose-Your-Own-Adventure" books, but collaboratively, with other people. The way I made this work with PHP/MySQL is, I had a table of stories and a table of pages. The pages would belong to stories (obviously), but each page would have references to up to four other pages by having four separate columns, one for each possible page ID that could be referenced.</p> <p>So right now in my RoR application, I have "stories" that have "pages" that are associated with them. I need a way to get the pages to reference each other, but the possibility of more than one reference per page (one page may reference up to four other pages).</p> <p>I really like the "references" thing that RoR has, but is there any way to gracefully implement this sort of system? Keep in mind that my only RoR experience is walking through four tutorials, and I'm trying to re-apply what I've learned with a "real-life application."</p>
<p>Rather then having four seperate columns, a separate joining table might be more appropriate. For example:</p> <p>Pages -> LinkedPages -> Pages</p> <p>Then you can create a <a href="http://wiki.rubyonrails.org/rails/pages/Beginner+Howto+on+has_many+:through" rel="nofollow">has_many through</a> relationship.</p> <pre><code>class Pages &lt; ActiveRecord::Base has_many :linked_pages has_many :pages, :through =&gt; :linked_pages end class LinkedPages &lt; ActiveRecord::Base belongs_to :pages, :class_name =&gt; "Pages", :foreign_key =&gt; "page_id" belongs_to :linked_pages, :class_name =&gt; "Pages", :foreign_key =&gt; "linked_id" end </code></pre> <p>Then when using your Page object you can simply say:</p> <pre><code>my_page.pages </code></pre>
Should Class Helpers be used in developing new code? <p>Delphi 8 introduced Class Helpers for the purposes of mapping the VCL/RTL to the .NET object hierarchy. They allow injecting methods into an existing class without overriding the the class or modifying the original. Later versions of Delphi found class helpers improved and they were ported to Win32.</p> <p>In the help it says "they should not be viewed as a design tool to be used when developing new code."</p> <p>Class Helpers violate traditional OOP, but I don't think that makes them a bad thing. Is this warning warranted? </p> <p>Should class helpers be used when developing new code? </p> <p>Do you use them when developing new code? </p> <p>Why or why not?</p> <p>Per <a href="http://stackoverflow.com/questions/354940/should-class-helpers-be-used-in-developing-new-code#355086">Malcolm's comments</a>: New code means daily application development, where you have some 3rd party libraries, some existing code, and then code you are writing. </p>
<p>Depends what you mean by "new code". </p> <p>They aren't really relevant for classes you are newly developing, so in that case, no, they probably shouldn't be used. </p> <p>But even in a brand new project, you may still need to modify an existing class that you can't change in other ways (vcl class, third-party class, etc). In this case, sure, I'd say go ahead. </p> <p>They're not evil in and of themselves. Like most other things, you just need to understand how they work and use them in an appropriate context.</p>
Formatting double as string in C# <p>I have a Double which could have a value from around 0.000001 to 1,000,000,000.000</p> <p>I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:</p> <pre><code>String.Format("{0:.000000000}", number); </code></pre> <p>if it's not that small, say 0.001 then I want to use something like</p> <pre><code>String.Format("{0:.00000}", number); </code></pre> <p>and if it's over, say 1,000 then format it as:</p> <pre><code>String.Format("{0:.0}", number); </code></pre> <p>Is there a clever way to construct this format string based on the size of the value I'm going to format?</p>
<p>Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately.</p> <pre><code>string s; double epislon = 0.0000001; // or however near zero you want to consider as zero if (Math.Abs(value) &lt; epislon) { int digits = Math.Log10( Math.Abs( value )); // if (digits &gt;= 0) ++digits; // if you care about the exact number if (digits &lt; -5) { s = string.Format( "{0:0.000000000}", value ); } else if (digits &lt; 0) { s = string.Format( "{0:0.00000})", value ); } else { s = string.Format( "{0:#,###,###,##0.000}", value ); } } else { s = "0"; } </code></pre> <p>Or construct it dynamically based on the number of digits.</p>
Is it possible to avoid a wakeup-waiting race using only POSIX semaphores? Is it benign? <p>I'd like to use POSIX semaphores to manage atomic get and put from a file representing a queue. I want the flexibility of having something named in the filesystem, so that completely unrelated processes can share a queue. I think this plan rules out pthreads. The named posix semaphores are great for putting something in the filesystem that any process can see, but I can't find the standard CondWait primitive:</p> <pre><code>... decide we have to wait .... CondWait(sem, cond); </code></pre> <p>When CondWait is called by a process it atomically posts to sem and waits on cond. When some other process posts to cond, the waiting process wakes up only if it can atomically decrement sem as well. The alternative of</p> <pre><code>... decide we have to wait .... sem_post(sem); sem_wait(cond); sem_wait(sem); </code></pre> <p>is subject to a race condition in which some other process signals cond just before this process waits on it.</p> <p>I hardly ever do any concurrent programming, so I thought I would ask SO: if I use a standard POSIX counting semaphore for the condition variable, is it possible that this race is benign?</p> <p>Just in case anybody wants the larger context, I am building get and put operations for an atomic queue that can be called from shell scripts. </p>
<p>Since there are no other answers I will follow up with what I've learned:</p> <ul> <li>Pthreads will not work with my application because I have processes without a common ancestor which need to share an atomic queue.</li> <li>Posix semaphores <em>are</em> subject to the wakeup-waiting race, but because unlike classic condition variables <strong>they are counting semaphores</strong>, the race is benign. I don't have a proof of this claim but I have had a system running for two days now and working well. (Completely meaningless I know, but at least it meant I got the job done.)</li> <li>Named Posix semaphores are <strong>difficult to garbage-collect from the filesystem</strong>.</li> </ul> <p>To summarize, named Posix semaphores turned out to be a <strong>good basis for implementing an atomic queue abstraction to be shared among unrelated processes</strong>.</p> <p>I would like to have a proof or a validated SPIN model, but as my need for the application is limited, it seems unlikely that I will write one. I hope this helps someone else who may want to use Posix semaphores.</p>
C# vs Java generics <p>I have heard that the Java implementation of Generics is not as good as the C# implementation. In that the syntax looks similar, what is it that is substandard about the Java implementation, or is it a religious point of view?</p>
<p><a href="http://www.jprl.com/Blog/archive/development/2007/Aug-31.html">streloksi's link</a> does a great job of breaking down the differences. The quick and dirty summary though is ...</p> <p>In terms of syntax and usage. The syntax is roughly the same between the languages. A few quirks here and there (most notably in constraints). But basically if you can read one, you can likely read/use the other. </p> <p>The biggest difference though is in the implementation. </p> <p>Java uses the notion of type erasure to implement generics. In short the underlying compiled classes are not actually generic. They compile down to Object and casts. In effect Java generics are a compile time artifact and can easily be subverted at runtime. </p> <p>C# on the other hand, by virtue of the CLR, implement generics all they way down to the byte code. The CLR took several breaking changes in order to support generics in 2.0. The benefits are performance improvements, deep type safety verification and reflection. </p> <p>Again the provided <a href="http://www.jprl.com/Blog/archive/development/2007/Aug-31.html">link</a> has a much more in depth breakdown I encourage you to read</p>
Defining const values in C <p>I have a C project where all code is organized in <code>*.c</code>/<code>*.h</code> file pairs, and I need to define a constant value in one file, which will be however also be used in other files. How should I declare and define this value?</p> <p>Should it be as <code>static const ...</code> in the <code>*.h</code> file? As <code>extern const ...</code> in the <code>*.h</code> file and defined in the <code>*.c</code> file? In what way does it matter if the value is not a primitive datatype (<code>int</code>, <code>double</code>, etc), but a <code>char *</code> or a <code>struct</code>? (Though in my case it is a <code>double</code>.)</p> <p>Defining stuff inside <code>*.h</code> files doesn't seem like a good idea generally; one should declare things in the <code>*.h</code> file, but define them in the <code>*.c</code> file. However, the <code>extern const ...</code> approach seems inefficient, as the compiler wouldn't be able to inline the value, it instead having to be accessed via its address all the time.</p> <p>I guess the essence of this question is: Should one define <code>static const ...</code> values in <code>*.h</code> files in C, in order to use them in more that one place?</p>
<p>The rule I follow is to only declare things in H files and define them in C files. You can declare and define in a single C file, assuming it will only be used in that file.</p> <p>By declaration, I mean notify the compiler of its existence but don't allocate space for it. This includes "#define"s, "typedef"s, "extern int x", and so on.</p> <p>Definitions assign values to declarations and allocate space for them, such as "int x" and "const int x". This includes function definitions; including these in header files frequently lead to wasted code space.</p> <p>I've seen too many junior programmers get confused when they put "const int x = 7;" in a header file and then wonder why they get a link error for x being defined more than once. I think at a bare minimum, you would need "static const int x" so as to avoid this problem.</p> <p>I wouldn't be too worried about the speed of the code. The main issue with computers (in terms of speed and cost) long ago shifted from execution speed to ease of development.</p>
Downloading the gzip file and Uncompressing to retrieve Content using IPHONE SDK on iphone and ipod touch devices <p>I had the following questions related to downloading the file from the server.</p> <p>a) Is it possible to download directly the GZIP (Compressed)file to the iphone device using IPHONE SDK. b) If the compressed file can be downloaded , then how to uncompress it(using ZLIB or else...).</p>
<p>Not at all sure about this, but if its http encoded with gzip, then that may well be auto-unzipped for you - as part of the http protocol - a guess and would need to be tested. Also may not be appropriate for your situation.</p>
Convert VB.NET --> C# Projects <p>Can anyone recommend a good application that could be used to convert VB.NET projects to C#, without having to do too much manual work?</p> <p>We've used Reflector to do small libraries manually, but some of the larger projects will be too slow and complex to do this manually.</p>
<p>You can use Lutz Roeders Reflector (<a href="http://www.red-gate.com/products/reflector">http://www.red-gate.com/products/reflector</a>) which can decompile whole Assemblies into Visual Studio projects. This way you can convert from ANY .NET Langauge into one of the supported languages of this program (C#.VB.NET,MC++,Delphi,Chrome)</p>
How to set WPF's Grid.RowDefinitions via Style <p>I'm using a couple of <code>Grid</code>s to format multiple <code>GridViewColumn.CellTemplate</code>s:</p> <pre><code>&lt;ListView SharedSizeScope="true"&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition SharedSizeGroup="foo" /&gt; &lt;!-- ... --&gt; </code></pre> <p>I tried to extract the <code>RowDefinition</code>s (which are the same for all columns) into a <code>Style</code>:</p> <pre><code>&lt;Style TargetType="{x:Type Grid}"&gt; &lt;Setter Property="RowDefinitions"&gt; &lt;Setter.Value&gt; &lt;RowDefinition SharedSizeGroup="foo" /&gt; &lt;!-- ... --&gt; </code></pre> <p>But the compiler complains:</p> <blockquote> <p>Error: The Property Setter 'RowDefinitions' cannot be set because it does not have an accessible set accessor.</p> </blockquote> <p>Which is kind of obvious, but not very helpful.</p> <p>How could I avoid specifying the row definitions multiple times (see also <a href="http://c2.com/cgi/wiki?DontRepeatYourself">Don't Repeat Yourself</a>) short of coding up a custom derivation of the <code>Grid</code>?</p>
<p>Grid doesn't support control templates (info taken from <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/731bf94e-0881-49e1-a35a-99a2e2ca647f/">here</a> and, indirectly, from <a href="http://social.expression.microsoft.com/Forums/en-US/wpf/thread/51448155-637c-469d-856b-ff81552fe980/">here</a>).</p>
What are the typical use cases of Genetic Programming? <p>Today I read <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/" rel="nofollow">this blog entry by Roger Alsing</a> about how to paint a replica of the <a href="http://en.wikipedia.org/wiki/Mona_Lisa" rel="nofollow">Mona Lisa</a> using only 50 semi transparent polygons.</p> <p>I'm fascinated with <a href="http://rogeralsing.files.wordpress.com/2008/12/evolutionofmonalisa1.gif" rel="nofollow">the results</a> for that particular case, so I was wondering (and this is my question): <strong>how does genetic programming work</strong> and what other <strong>problems could be solved</strong> by genetic programming?</p>
<p>There is some debate as to whether Roger's Mona Lisa program is <a href="http://en.wikipedia.org/wiki/Genetic_programming">Genetic Programming</a> at all. It seems to be closer to a (1 + 1) <a href="http://en.wikipedia.org/wiki/Evolution_strategy">Evolution Strategy</a>. Both techniques are examples of the broader field of Evolutionary Computation, which also includes <a href="http://en.wikipedia.org/wiki/Genetic_algorithm">Genetic Algorithms</a>.</p> <p>Genetic Programming (GP) is the process of evolving computer programs (usually in the form of trees - often Lisp programs). If you are asking specifically about GP, John Koza is widely regarded as the leading expert. His <a href="http://www.genetic-programming.org/">website</a> includes lots of links to more information. GP is typically very computationally intensive (for non-trivial problems it often involves a large grid of machines).</p> <p>If you are asking more generally, evolutionary algorithms (EAs) are typically used to provide good approximate solutions to problems that cannot be solved easily using other techniques (such as NP-hard problems). Many optimisation problems fall into this category. It may be too computationally-intensive to find an exact solution but sometimes a near-optimal solution is sufficient. In these situations evolutionary techniques can be effective. Due to their random nature, evolutionary algorithms are never guaranteed to find an optimal solution for any problem, but they will often find a good solution if one exists.</p> <p>Evolutionary algorithms can also be used to tackle problems that humans don't really know how to solve. An EA, free of any human preconceptions or biases, can generate surprising solutions that are comparable to, or better than, the best human-generated efforts. It is merely necessary that we can recognise a good solution if it were presented to us, even if we don't know how to create a good solution. In other words, we need to be able to formulate an effective <a href="http://en.wikipedia.org/wiki/Fitness_function">fitness function</a>.</p> <p><strong>Some Examples</strong></p> <ul> <li><a href="https://watchmaker.dev.java.net/examples/salesman.html">Travelling Salesman</a></li> <li><a href="https://watchmaker.dev.java.net/examples/sudoku.html">Sudoku</a></li> </ul> <p><strong>EDIT:</strong> The freely-available book, <a href="http://www.gp-field-guide.org.uk/">A Field Guide to Genetic Programming</a>, contains examples of where GP has produced <em>human-competitive</em> results.</p>
Event log messages get overrriden by another event log <p>I create event logs for asp.net projects error logging. I do it by adding a key in regedit, and then a sub-key.<br /> Sometimes, I create a new key and sub-key, and instead of getting a new, empty event log, I see in the event viewer that it's showing me the logs from a different project. I'm not able to find a pattern as to when this happens.<br /> Has anyone encountered such a problem? Am I doing something wrong? </p>
<p>You probably want to use the <a href="http://msdn.microsoft.com/en-us/library/2awhba7a.aspx" rel="nofollow">EventLog.CreateEventSource</a> API to do this - it should take care of any details for you.</p> <p>A quick read thru the docs seems to show that the 1st 8 characters are checked for uniqueness...perhaps that's where your issue is?</p> <p>Edit: From Reflector, the API does this...</p> <ol> <li>Check for invalid characters ("non printable" based on Unicode category, \, *, ?)</li> <li>Checks that the created reg key will be &lt;= 254 characters</li> <li>Checks if the source is already registered</li> <li>Checks that the log name isn't reserved (AppEvent, SecEvent, SysEvent)</li> <li>Checks for another log with the same beginning 8 chars</li> <li>Checks that the log name doesn't exist as a source</li> <li>Creates the log subkey</li> <li>Initializes the log subkey with default values (MaxSize = 524288, AutoBackupLogFiles = 9. Retention = 604800, File = %SystemRoot%\System32\config\logName.Substring(0, 8) + ".evt")</li> <li>If OS is not > Windows NT 5.x (Vista or higher), creates a multi string value on the logkey with logName and source name. Or, if value exists, appends source name to the existing array.</li> <li>Creates a subkey for source</li> <li>Initializes the source subkey with default values (EventMessageFile, ParameterMessageFile, CategoryMessageFile, CategoryCount)</li> </ol>
Rails: Blocking an user using routes.rb <p>I have a special url which I would want only few people to have access to. I have a list of super users stored as an array in the app.yml. How can I use this array in :requirements section of a specific route in the routes.rb file to allow only those super users access to this route? Thanks a lot.</p>
<p>No, you can't. <code>:requirements</code> are related to route parameters only.</p> <p>Which is, in my opinion, a good thing. It's a well known convention to have authentication logic in controllers.</p>
Sorting an Array of Objects in PHP In a Specific Order <p>I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)</p> <p>The second array ($user_results) is comprised of an array of objects like so:</p> <pre><code>Array ( [0] =&gt; stdClass Object ( [ID] =&gt; 1 [user_login] =&gt; user1 ) [1] =&gt; stdClass Object ( [ID] =&gt; 6 [user_login] =&gt; user6 ) [2] =&gt; stdClass Object ( [ID] =&gt; 8 [user_login] =&gt; user8 ) ) </code></pre> <p>I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:</p> <pre><code>Array ( [0] =&gt; stdClass Object ( [ID] =&gt; 8 [user_login] =&gt; user8 ) [1] =&gt; stdClass Object ( [ID] =&gt; 1 [user_login] =&gt; user1 ) [2] =&gt; stdClass Object ( [ID] =&gt; 6 [user_login] =&gt; user6 ) ) </code></pre> <p>I'm weak on data structures. How could I do this? :-)</p> <p>Thanks in advance for your help!</p> <p>-Bob</p>
<p>Use <a href="http://php.net/uksort">usort</a> and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:</p> <pre><code>function cmp($a, $b) { global $author_array; $pos1=array_search ($a-&gt;ID, $author_array); $pos2=array_search ($b-&gt;ID, $author_array); if ($pos1==$pos2) return 0; else return ($pos1 &lt; $pos2 ? -1 : 1); } usort($user_results, "cmp"); </code></pre>
How to sort the data in alphanumeric values <p>I have these values: <code>d1, d45, d79, d33, d100</code></p> <p>I want to sort these variables in ascending order from my table.</p> <p>What is the query to get the output as:</p> <pre><code>d1 d33 d45 d79 d100 </code></pre>
<p>What you want is called a "natural sort". For Microsoft SQL Server 2005, see <a href="http://stackoverflow.com/questions/34509/natural-human-alpha-numeric-sort-in-microsoft-sql-2005">this question</a>. For other languages, see (for example) <a href="http://stackoverflow.com/questions/127913/sorting-strings-is-much-harder-than-you-thought">this other question</a>.</p>
Virtual Directory in ASP.NET project <p>In our web application we have a directory which resides outside of the project. On IIS that's no problem to do, but can I do that also in my project in Visual Studio? </p> <p><strong>Edit:</strong> My project is running on File System, and not on Local IIS</p>
<p>If you click <code>File|Open|Website</code> and then click on the <code>Local IIS</code> button on the left-hand side of the dialog, then navigate to your project file and open from there you should find the virtual directories are included in Solution Explorer.</p>
Codenamed Products and Visual Studio <p>Are there any practices regarding using codenames of products in Visual Studio projects and solutions? In that typically, namespaces, assembly names, binary outputs, et al need to be renamed once a product name is chosen: is there any way to deal with this?</p>
<p>In one place I worked we'd choose an unrelated and inoffensive, and typically systematic name for any given project.. Jupiter, Orca, Feynman whatever... and stick with that namespace forevermore.</p> <p>Because as you've seen what the marketing/client/board chooses to call a product (hell, even what version number they choose) is so rarely going to be known at the start let alone the same by the end, that it's just so much easier for everyone to be able to have a fixed internal reference they don't have to refactor later.</p> <p>I can't stress how important it is that the name is simple, one word and inoffensive though.</p>
C++ HTML template framework, templatizing library, HTML generator library <p>I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.</p> <p>It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.</p> <p>Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters.</p> <p>Do you have any recommendations?</p> <p>I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.</p>
<p>A quick review of the mentioned project.</p> <p><a href="http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language">http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language</a></p> <h2>ClearSilver</h2> <ul> <li>Site: <a href="http://www.clearsilver.net">http://www.clearsilver.net</a></li> <li>Project: <a href="https://code.google.com/p/clearsilver/">https://code.google.com/p/clearsilver/</a></li> <li>Group: <a href="http://tech.groups.yahoo.com/group/ClearSilver">http://tech.groups.yahoo.com/group/ClearSilver</a></li> <li>License: New BSD License</li> <li>Language: C</li> <li>Last Update: Nov 28, 2011</li> <li>Last Release: 0.10.5 on July 12, 2007</li> <li>Document: Rich</li> <li>Community: Medium (&lt;10 discussion per month)</li> </ul> <h2>Teng</h2> <ul> <li>Site: <a href="http://teng.sourceforge.net">http://teng.sourceforge.net</a></li> <li>Code: <a href="http://teng.svn.sourceforge.net/teng/">http://teng.svn.sourceforge.net/teng/</a></li> <li>Group: <a href="http://sourceforge.net/projects/teng/">http://sourceforge.net/projects/teng/</a></li> <li>License: New BSD License</li> <li>Language: C++</li> <li>Binding: php, python</li> <li>Last Update: Mar 8, 2011</li> <li>Last Release: 2.1.1 on Mar 8, 2011</li> <li>Document: Rich</li> <li>Community: Low (rare discussion since 2010)</li> </ul> <h2>Templatizer</h2> <ul> <li>Site: <a href="http://www.lazarusid.com/libtemplate.shtml">http://www.lazarusid.com/libtemplate.shtml</a></li> <li>Project: download only</li> <li>Group: none</li> <li>License: free to use</li> <li>Language: C (low level)/C++ (interface) mixed</li> <li>Last Update: unknown</li> <li>Last Release: unknown</li> <li>Document: none</li> <li>Community: none</li> </ul> <h2>HTML Template C++</h2> <ul> <li>Site: <a href="http://nulidex.com/code/docs/html_template/">http://nulidex.com/code/docs/html_template/</a></li> <li>Project: <a href="http://sourceforge.net/projects/htmltemplatec">http://sourceforge.net/projects/htmltemplatec</a> </li> <li>Group: <a href="http://sourceforge.net/projects/htmltemplatec">http://sourceforge.net/projects/htmltemplatec</a></li> <li>License: GPL</li> <li>Language: C++</li> <li>Last Update: Mar 27, 2011</li> <li>Last Release: Beta 0.7.4, Mar 27, 2011</li> <li>Document: Medium</li> <li>Community: none</li> </ul> <h2>ctpp</h2> <ul> <li>Site: <a href="http://ctpp.havoc.ru/en/">http://ctpp.havoc.ru/en/</a></li> <li>Project: download only</li> <li>Group: none</li> <li>License: BSD License</li> <li>Language: C++ with C API</li> <li>Last Update: Oct 5, 2011</li> <li>Last Release: Version 2.7.2 on Oct 5, 2011</li> <li>Document: Rich</li> <li>Community: none</li> </ul> <h2>Wt</h2> <ul> <li>Site: <a href="http://www.webtoolkit.eu/wt/">http://www.webtoolkit.eu/wt/</a></li> <li>Project: <a href="http://www.webtoolkit.eu/wt/">http://www.webtoolkit.eu/wt/</a></li> <li>Group: <a href="http://www.webtoolkit.eu/wt/community">http://www.webtoolkit.eu/wt/community</a></li> <li>License: GPL and Commercial</li> <li>Language: C++</li> <li>Last Update: Nov 29, 2011</li> <li>Last Release: 3.2.0 on Nov 29, 2011</li> <li>Document: Rich</li> <li>Community: Low (rare activity)</li> </ul> <h2>Flate</h2> <ul> <li>Site: <a href="http://flate.dead-inside.org/">http://flate.dead-inside.org/</a></li> <li>Project: none</li> <li>Group: none</li> <li>License: LGPL v2.1</li> <li>Language: C</li> <li>Last Update: Sep 4, 2010</li> <li>Last Release: 2.0 on Sep 4, 2010</li> <li>Document: Poor</li> <li>Community: none</li> </ul>
Is returning early from a function more elegant than an if statement? <p>Myself and a colleague have a dispute about which of the following is more elegant. I won't say who's who, so it is impartial. Which is more elegant?</p> <pre><code>public function set hitZone(target:DisplayObject):void { if(_hitZone != target) { _hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver); _hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut); _hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown); _hitZone = target; _hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true); _hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true); _hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true); } } </code></pre> <p>...or...</p> <pre><code>public function set hitZone(target:DisplayObject):void { if(_hitZone == target)return; _hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver); _hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut); _hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown); _hitZone = target; _hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true); _hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true); _hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true); } </code></pre>
<p>In most cases, returning early reduces the complexity and makes the code more readable.</p> <p>It's also one of the techniques applied in <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan%5Fprogramming">Spartan programming</a>:</p> <blockquote> <p><strong>Minimal use of Control</strong></p> <ol> <li>Minimizing the use of conditionals by using specialized constructs such ternarization, inheritance, and classes such as Class Defaults, Class Once and Class Separator</li> <li>Simplifying conditionals with early <code>return</code>.</li> <li>Minimizing the use of looping constructs, by using action applicator classes such as Class Separate and Class FileSystemVisitor.</li> <li>Simplifying logic of iteration with early exits (via <code>return</code>, <code>continue</code> and <code>break</code> statements).</li> </ol> </blockquote> <p>In your example, I would choose option 2, as it makes the code more readable. I use the same technique when checking function parameters.</p>
Symbian C++ STOMP library <p>I want my S60 Application to utilize the Stomp protocol.</p> <p>Although it would be fairly simple to implement myself (but nothing is ever as simple as I hope with Symbian) - I am wondering if anyone has any experience in this already.</p> <p>It seems a Stomp library exists in almost every other language already. The closest match for Symbian would be the C++ library listed <a href="http://stomp.codehaus.org/Clients" rel="nofollow">here</a> but that is embedded quite integrally within the ActiveMQ source.</p> <p>Can anyone offer any advice/experience?</p> <p>Thanks!</p>
<p>In case this is still relevant - I've just finished my implementation of a STOMP client for Symbian, fully using the Active Scheduler framework. We're going to release it as opensource once I get something set up on Google Code.</p> <p>As Adam says - the implementation needed to be purely within the Symbian framework or it would be unusable (i.e. you'd either need to thread it - arg - or it would just cause all sorts of blocking problems).</p> <p>I'd also like to get in touch with the STOMP people and have it listed on the website, but haven't been able to find a contact - does anyone here know the best way to do it?</p>
ASP.NET MVC public alternative to UrlHelper.GenerateUrl <p>I want to embed a link to a controller action in my page so I can use it from javascript. Something like</p> <pre><code>var pollAction = '/Mycontroller/CheckStatus' </code></pre> <p>Now I am happy to hardcode it, but it would be really nice if there were a method I could use to create the URL. The AjaxHelper/HtmlExtensions contain methods to create hyperlinks (.ActionLink(...) and so on), but if you look into the guts of them, they rely on a method called UrlHelper.GenerateUrl() to resolve a controller and action into a url. This is internal so I can't really get at this.</p> <p>Anyone found a good method in the framework to do this? Or must I roll my own?</p>
<p>Have you tried something along these lines?</p> <pre><code>var pollAction = '&lt;%=Url.Action("CheckStatus", "MyController") %&gt;'; </code></pre>
The best way to store class instances to a file/database <p>What is the best way to store instances of a class to file/database?</p> <p>We have a base class called Command and loads of derived classes. Users create instances of these classes by adding commands to a graphical designer where they can configure them. (Set the properties).</p> <p>We then need a way to store these "commands" to a file without losing any information.</p> <p>One idea was to use db4o, but the GPL license is not acceptable for this project.</p> <p>Any suggestions or code samples?</p> <p>Update:</p> <p>(In order to "de-blurryfie" my question :p)</p> <p>The generated code might look something like:</p> <pre><code> command[i++] = new DelayInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 254); command[i++] = new DaliRequestCommand(2, false, 254); command[i++] = new DaliRequestCommand(3, false, 254); command[i++] = new WaitInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 0); command[i++] = new DaliRequestCommand(2, false, 0); command[i++] = new DaliRequestCommand(3, false, 0); command[i++] = new JumpCommand(0); </code></pre> <p>But then with loads of different commands.</p> <p>I know it's possible with .NET serialization, altough I've never used it before, but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project.</p> <p>Update 2:</p> <p>Thank you for the replies. I'll probably go with the serialization solution now, but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.</p>
<p>Are you trying to save the data in tables? or as blob/clob data? Since you mention files, I assume the latter: any of the standard .NET serializers should be fine - they all support inheritance etc. I'd consider for <code>DataContractSerializer</code>, as this combines the field-level support (like <code>BinaryFormatter</code>), and the assembly-independence of <code>XmlSerializer</code>.</p> <p>You could also consider more esoteric things like <a href="http://code.google.com/p/protobuf-net/" rel="nofollow">protobuf-net</a>.</p> <p>So: what is it you need to do that won't work under the standard serializers?</p>
Caching HTML output with PHP <p>I would like to create a cache for my php pages on my site. I did find too many solutions but what I want is a script which can generate an HTML page from my database ex:</p> <p>I have a page for categories which grabs all the categories from the DB, so the script should be able to generate an HTML page of the sort: my-categories.html. then if I choose a category I should get a my-x-category.html page and so on and so forth for other categories and sub categories.</p> <p>I can see that some web sites have got URLs like: wwww.the-web-site.com/the-page-ex.html</p> <p>even though they are dynamic.</p> <p>thanks a lot for help</p>
<p>check ob_start() function</p> <pre><code>ob_start(); echo 'some_output'; $content = ob_get_contents(); ob_end_clean(); echo 'Content generated :'.$content; </code></pre>
What is Microsoft OSLO? <p>Is it a DSL generation tool or natural query language?</p>
<p>”Oslo” is the codename for Microsoft’s forthcoming modeling platform. Modeling is used across a wide range of domains and allows more people to participate in application design and allows developers to write applications at a much higher level of abstraction. “Oslo” consists of:</p> <ul> <li>A tool that helps people define and interact with models in a rich and visual manner</li> <li>A language that helps people create and use textual domain-specific languages and data models</li> <li>A relational repository that makes models available to both tools and platform components</li> </ul> <p><a href="http://www.microsoft.com/soa/products/oslo.aspx" rel="nofollow">More Information</a></p> <p>Also see: <a href="http://msdn.microsoft.com/en-us/library/dd129873.aspx" rel="nofollow">OSLO FAQ</a></p>
How can I display Arabic data in Crystal Reports? <p>I am using Crystal Reports 10. The reports are obtaining data from an Oracle 10G database. We have some data in Arabic. When I try to display the Arabic data it is showing as ?.</p> <p>Any ideas on what I can do to display this correctly?</p>
<p>I've never used crystal reports and my oracle knowledge is limited, however I've done some work in Arabic. Things to look out for.</p> <p>Does the Database have the arabic locale installed can it display right to left text.</p> <p>Under windows check the languages settings and check that the option to include support for left to right writing systems is installed.</p> <p>Check that your database is the international version and not one that only supports the latin character set. It may be that there is a problem converting between ASCII and Unicode.</p> <p>Arabic Characters are not on the same ASCII code page as the Latin Character set your machine will be used to using, there might be a special version of crystal reports that supports arabic.</p> <p>Check that the machine you are running crystal reports on has the arabic locale/fonts installed on it.</p> <p><strong>UPDATE</strong></p> <p>I've Had a quick look on the internet and you might want to look at <a href="https://boc.sdn.sap.com/node/1212" rel="nofollow">this link</a></p> <p>Here is a summary:</p> <blockquote> <p>This issue can be solved when you create the reports without needing to write any extra code. I haven't tested this solution because I don't have any data to test it against.</p> <p>First you want to make sure that you are using a UNICODE font which I'm sure you are probably already doing. Then to configure the "Right to Left" you can right click on any field and select "Format Text" or "Format Field". You should see a "Paragraph" tab. In there you can set the content to be "Left to Right" or "Right to Left". The button on the right allows you to make this setting conditional on a parameter value or something like that. I hope this helps.</p> </blockquote>
How is Domain Driven Design different from just using a specification? <p>I read that Domain Driven Design is about concentrating on the problem domain instead of concentrating on the software. They say that it is easier to solve the complexities of the problem domain than the complexities of the software, because after you have solved the domain, you know better how to build the software, too. Also they say that actually the domain is more complex than the structures of the software or that if you don't see the forest from the woods, you are in trouble.</p> <p>But how is Domain Driven Design different from just using a specification for the software? I mean, of course we should get to know the problem domain before we start coding. Is DDD reinventing the wheel?</p>
<p>Domain-driven design is more about establishing a common model of the world (and an associated common language) that both you and the domain experts can use.</p> <p>In theory this means that developers can write code that reads like a description of the problem domain, and domain experts can look over developers' shoulders and see what's going on.</p> <p>A specification makes no such promises about a common language or model of the world, it just says "we're going to build something specific". The highly specified class model you come up with might work, but it may not reflect 'reality' particularly well.</p> <p>There's a good free book on Domain-Driven design <a href="http://www.infoq.com/minibooks/domain-driven-design-quickly" rel="nofollow">here</a> (login required unfortunately).</p>
How do you test for the existence of a user in SQL Server? <p>I'd like to drop a user in a SQL Server script but I'll need to test for existence first or I'll get script errors. When dropping tables or stored procs, I check the sysobjects table like so:</p> <pre><code>IF EXISTS ( SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[up_SetMedOptions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) Drop Procedure up_SetMedOptions; GO </code></pre> <p>What is the corollary for checking for a user? Note that I am NOT asking about a database login to the server! The question pertains to a User in a specific database.</p>
<p>SSMS scripts it in the following way:</p> <p>For SQL 2005/2008:</p> <pre><code>IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'username') DROP USER [username] </code></pre> <p>For SQL 2000:</p> <pre><code>IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username') EXEC dbo.sp_revokedbaccess N'username' </code></pre>
Have ReSharper keep 'using System;' when optimizing usings <p>I was wondering if there is some option to keep ReSharper from removing just the <code>using System;</code> directive? Perhaps this is configurable somewhere?</p> <p>Also, is there a way to have ReSharper sort the remaining directives just as Visual Studio 2008 does it (alphabetically, I think)?</p> <p>Thanks.</p>
<p>Yes, there is such an option: ReSharper->Languages->C#->Namespace Imports. You can add namespaces,that should not be removed, as well as namespaces, that should always be imported.</p>
How to find out the TabSelection <p>I have using the following code for developing tabs.</p> <pre><code>$(document).ready(function() { $('#container-1').tabs(); } .... &lt;div id="container-1"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#fragment-1"&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#fragment-2"&gt;&lt;span&gt;Contact&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; ... </code></pre> <p>It works fine! I need the tab click event. If it is the <em>Home</em> tab click, I have to do <code>alert();</code>. How do I achieve this?</p>
<p>Set the id of the <em>Home</em> tab span element:</p> <pre><code>&lt;li&gt;&lt;a href="#fragment-1"&gt;&lt;span id="home"&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; </code></pre> <p>And add the click handler to it somewhere:</p> <pre><code>$("#home").click(function() { alert("Home tab is selected!"); }); </code></pre>
How to compute the nth root of a very big integer <p>I need a way to compute the nth root of a long integer in Python. </p> <p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p> <blockquote> <p>OverflowError: long int too large to convert to float</p> </blockquote> <p>Any ideas?</p> <p>By long integer I mean REALLY long integers like:</p> <blockquote> <p>11968003966030964356885611480383408833172346450467339251 196093144141045683463085291115677488411620264826942334897996389 485046262847265769280883237649461122479734279424416861834396522 819159219215308460065265520143082728303864638821979329804885526 557893649662037092457130509980883789368448042961108430809620626 059287437887495827369474189818588006905358793385574832590121472 680866521970802708379837148646191567765584039175249171110593159 305029014037881475265618958103073425958633163441030267478942720 703134493880117805010891574606323700178176718412858948243785754 898788359757528163558061136758276299059029113119763557411729353 915848889261125855717014320045292143759177464380434854573300054 940683350937992500211758727939459249163046465047204851616590276 724564411037216844005877918224201569391107769029955591465502737 961776799311859881060956465198859727495735498887960494256488224 613682478900505821893815926193600121890632</p> </blockquote>
<p>If it's a REALLY big number. You could use a binary search.</p> <pre><code>def find_invpow(x,n): """Finds the integer component of the n'th root of x, an integer such that y ** n &lt;= x &lt; (y + 1) ** n. """ high = 1 while high ** n &lt;= x: high *= 2 low = high/2 while low &lt; high: mid = (low + high) // 2 if low &lt; mid and mid**n &lt; x: low = mid elif high &gt; mid and mid**n &gt; x: high = mid else: return mid return mid + 1 </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; x = 237734537465873465 &gt;&gt;&gt; n = 5 &gt;&gt;&gt; y = find_invpow(x,n) &gt;&gt;&gt; y 2986 &gt;&gt;&gt; y**n &lt;= x &lt;= (y+1)**n True &gt;&gt;&gt; &gt;&gt;&gt; x = 119680039660309643568856114803834088331723464504673392511960931441&gt; &gt;&gt;&gt; n = 45 &gt;&gt;&gt; y = find_invpow(x,n) &gt;&gt;&gt; y 227661383982863143360L &gt;&gt;&gt; y**n &lt;= x &lt; (y+1)**n True &gt;&gt;&gt; find_invpow(y**n,n) == y True &gt;&gt;&gt; </code></pre>
How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0? <p>How to wait in a bash script for several subprocesses spawned from that script to finish and return exit code !=0 when any of the subprocesses ends with code !=0 ?</p> <p>Simple script:</p> <pre><code>#!/bin/bash for i in `seq 0 9`; do doCalculations $i &amp; done wait </code></pre> <p>The above script will wait for all 10 spawned subprocesses, but it will always give exit status 0 (see <code>help wait</code>). How can I modify this script so it will discover exit statuses of spawned subprocesses and return exit code 1 when any of subprocesses ends with code !=0?</p> <p>Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?</p>
<p><code>wait</code> also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.</p>
How to write a unix filter that outputs only a line every N lines <p>Suppose to feed the filter standard input with these line:</p> <pre><code>line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10 </code></pre> <p>It would be nicer if someone tell me how to write a script that prints only every 4 lines, in the case of the example input above:</p> <pre><code>line 1 line 5 line 9 </code></pre>
<pre><code>$ yes | cat -n | head -10 | awk 'NR % 4 == 1' 1 y 5 y 9 y </code></pre> <p>That is, your answer is "<code>awk 'NR % 4 == 1'</code>".</p>
Designing Address validation for app <p>I am planning to design an address validation for users registering in my app. Possibly validating by zipcode and state.</p> <p>Any idea how to handle addresses from around the globe?</p> <p>Do i need to insert all the zipcodes in the database and then validate the address. Any possible suggestion for the implementation?</p> <p>Thanks and Welcome :) Krisp</p>
<p>Since there is no international standard for zip codes and a list of all zip codes in the world would be out of date before you were finished putting it together, I suggest a smaller approach:</p> <p>Identify the countries that you will have to handle most and develop seperate validation rules for each of them. Make certain that with this you handle a vast majority of your users (e.g. 95%, or98%). For all the other countries, just accept what they enter vithout further validation. </p> <p>There are so many different address formats in the world that it is just not worth the effort (if at all possible) to handle them all.</p>
Build dependency tree from csproj files <p>I'm currently using msbuild for a solution of over 600 projects. </p> <p>Imagine I change the code for 1 library that is used by 10 projects. Instead of providing all 600 projects to msbuild and let it compile all of them and figure out the dependencys. I was wondering if there was a program or library I could use that would analyse the dependencys of all 600 projects, and allow me to only compile the 11 that are necessary.</p> <p>In other words given the input of all 600 projects to scan, and BaseLibrary.csproj as a project that has been modified parameter, provide me only the 11 projects I need to compile as output.</p> <p>I'm experienced in writing custom tasks, I'd just rather use a third party library to do the dependency analysis if there is already one out there.</p> <p>My company does incremental releases to production every 3-4 months. As an experiment I wrote a custom task that looks at the previous releases "Subversion tag" and evaluates all the compiled files that have changed since then and maps them to a project. </p> <p>The only use case I can think of that doesn't work is the one I mentioned where a base library is changed and the system doesn't know about all the projects that depend on it.</p>
<p>Have you tried <a href="http://www.drewnoakes.com/code/dependancyanalyser/" rel="nofollow">.NET assembly dependency analyser</a>?. </p> <p>It is open source, and the graph output in <a href="http://www.graphviz.org/doc/info/lang.html" rel="nofollow">dot script</a> might be what you need. An example from the site:</p> <pre><code>digraph G { size="100,69" center="" ratio=All node[width=.25,hight=.375,fontsize=12,color=lightblue2,style=filled] 1 -&gt; 9; 1 -&gt; 11; 9 -&gt; 10; 11 -&gt; 10; 1 [label="Drew.Controls.Map"]; 9 [label="Drew.Types"]; 10 [label="nunit.framework"]; 11 [label="Drew.Util"]; } </code></pre> <p>With the list of projects and this script output, you can create your compilation list.</p>
Regular Expression to Extract HTML Body Content <p>I am looking for a regex statement that will let me extract the HTML content from just between the body tags from a XHTML document.</p> <p>The XHTML that I need to parse will be very simple files, I do not have to worry about JavaScript content or <code>&lt;![CDATA[</code> tags, for example.</p> <p>Below is the expected structure of the HTML file is that I have to parse. Since I know exactly all of the content of the HTML files that I am going to have to work with, this HTML snippet pretty much covers my entire use case. If I can get a regex to extract the body of this example, I'll be happy.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt; &lt;/title&gt; &lt;/head&gt; &lt;body contenteditable="true"&gt; &lt;p&gt; Example paragraph content &lt;/p&gt; &lt;p&gt; &amp;nbsp; &lt;/p&gt; &lt;p&gt; &lt;br /&gt; &amp;nbsp; &lt;/p&gt; &lt;h1&gt;Header 1&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Conceptually, I've been trying to build a regex string that matches everything BUT the inner body content. With this, I would use the C# <code>Regex.Split()</code> method to obtain the body content. I thought this regex:</p> <pre class="lang-none prettyprint-override"><code>((.|\n)*&lt;body (.)*&gt;)|((&lt;/body&gt;(*|\n)*) </code></pre> <p>...would do the trick, but it doesn't seem to work at all with my test content in RegexBuddy.</p>
<p>Would this work ?</p> <pre><code>((?:.(?!&lt;body[^&gt;]*&gt;))+.&lt;body[^&gt;]*&gt;)|(&lt;/body\&gt;.+) </code></pre> <p>Of course, you need to add the necessary <code>\s</code> in order to take into account <code>&lt; body ...&gt;</code> (element with spaces), as in:</p> <pre><code>((?:.(?!&lt;\s*body[^&gt;]*&gt;))+.&lt;\s*body[^&gt;]*&gt;)|(&lt;\s*/\s*body\s*\&gt;.+) </code></pre> <p>On second thought, I am not sure why I needed a negative look-ahead... This should also work (for a well-formed xhtml document):</p> <pre><code>(.*&lt;\s*body[^&gt;]*&gt;)|(&lt;\s*/\s*body\s*\&gt;.+) </code></pre>
CSS Positioning, want to make content's width fixed when window is resized <p>I have a div with two nested divs inside, the (float:left) one is the menu bar, and the right (float:right) should display whatever content the page has, it works fine when the window is at a maximum, but when i resize it the content is collapsed until it can no longer has any space, at which it is forced to be displayed BELOW the left menu bar, how can I make the width fixed so that the user may scroll when resized? (css width didn't work, i alternated between floating the right content and not), here is the code: </p> <pre><code>&lt;div style="width:100%"&gt; &lt;div style="float:left; background:#f5f5f5; border-right:1px solid black; height:170%; width:120px;"&gt;&lt;/div&gt; &lt;div style="margin-right:2px;margin-top:15px; margin-bottom:5px; width:100%; border:1px solid #f5f5f5"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I only need to have this working on Interner Explorer for now. </p>
<p>This should do it (container is the parent div containing that 2 divs):</p> <pre><code>.container { width: 1024px; display: block; } </code></pre>
LINQ to SQL object versioning <p>I'm trying to create a LINQ to SQL class that represents the "latest" version of itself.</p> <p>Right now, the table that this entity represents has a single auto-incrementing ID, and I was thinking that I would add a version number to the primary key. I've never done anything like this, so I'm not sure how to proceed. I would like to be able to abstract the idea of the object's version away from whoever is using it. In other words, you have an instance of this entity that represents the most current version, and whenever any changes are submitted, a new copy of the object is stored with an incremented version number.</p> <p>How should I proceed with this?</p>
<p>If you can avoid keeping a history, do. It's a pain.</p> <p>If a complete history is unavoidable (regulated financial and medical data or the like), consider adding history tables. Use a trigger to 'version' into the history tables. That way, you're not dependent on your application to ensure a version is recorded - all inserts/updates/deletes are captured regardless of the source.</p> <p>If your app needs to interact with historical data, make sure it's readonly. There's no sense capturing transaction histories if someone can simply change them.</p> <p>If your concern is concurrent updates, consider using a record change timestamp. When both User A and User B view a record at noon, they fetch the record's timestamp. When User A updates the record, her timestamp matches the record's so the update goes through and the timestamp is updated as well. When User B updates the record five minutes later, his timestamp doesn't match the record's so he's warned that the record has changed since he last viewed it. Maybe it's automatically reloaded...</p> <p>Whatever you decide, I would avoid inter-mingling current and historic data.</p> <p><hr /></p> <p>Trigger resources per comments:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms189799(SQL.90).aspx" rel="nofollow">MSDN</a></li> <li><a href="http://www.sqlteam.com/article/an-introduction-to-triggers-part-i" rel="nofollow">A SQL Team Introduction</a></li> <li>Stackoverflow's <a href="http://stackoverflow.com/users/5/jon-galloway">Jon Galloway</a> describes a <a href="http://weblogs.asp.net/jgalloway/archive/2008/01/27/adding-simple-trigger-based-auditing-to-your-sql-server-database.aspx" rel="nofollow">general data-change logging trigger</a></li> </ul> <p>The keys to an auditing trigger are the <a href="http://msdn.microsoft.com/en-us/library/ms191300(SQL.90).aspx" rel="nofollow">virtual tables 'inserted' and 'deleted'</a>. These tables contain the rows effected by an INSERT, UPDATE, or DELETE. You can use them to audit changes. Something like:</p> <pre><code>CREATE TRIGGER tr_TheTrigger ON [YourTable] FOR INSERT, UPDATE, DELETE AS IF EXISTS(SELECT * FROM inserted) BEGIN --this is an insert or update --your actual action will vary but something like this INSERT INTO [YourTable_Audit] SELECT * FROM inserted END IF EXISTS(SELECT * FROM deleted) BEGIN --this is a delete, mark [YourTable_Audit] as required END GO </code></pre>
C# Extracting a name from a string <p>I want to extract 'James\, Brown' from the string below but I don't always know what the name will be. The comma is causing me some difficuly so what would you suggest to extract James\, Brown?</p> <p>OU=James\, Brown,OU=Test,DC=Internal,DC=Net</p> <p>Thanks</p>
<p>A regex is likely your best approach</p> <pre><code>static string ParseName(string arg) { var regex = new Regex(@"^OU=([a-zA-Z\\]+\,\s+[a-zA-Z\\]+)\,.*$"); var match = regex.Match(arg); return match.Groups[1].Value; } </code></pre>
A good library for converting PDF to TIFF? <p>I need a Java library to convert PDFs to TIFF images. The PDFs are faxes, and I will be converting to TIFF so that I can then do barcode recognition on the image. Can anyone recommend a good library (free or $$) for conversion from PDF to TIFF? </p>
<p>I can't recommend any code library, but it's easy to use GhostScript to convert PDF into bitmap formats. I've personally used the script below (which also uses the netpbm utilties) to convert the <em>first</em> page of a PDF into a JPEG thumbnail:</p> <pre><code>#!/bin/sh /opt/local/bin/gs -q -dLastPage=1 -dNOPAUSE -dBATCH -dSAFER -r300 \ -sDEVICE=pnmraw -sOutputFile=- $* | pnmcrop | pnmscale -width 240 | cjpeg </code></pre> <p>You can use <code>-sDEVICE=tiff...</code> to get direct TIFF output in various TIFF sub-formats from GhostScript.</p>
Select object when a property equals Max with NHibernate <p>We have a query that selects rows depending on the value of another, ie. the max. I don't think that really makes much sense, so here is the query:</p> <pre><code>var deatched = DetachedCriteria.For&lt;Enquiry&gt;("e2") .SetProjection(Projections.Alias(Projections.Max("Property"), "maxProperty")) .Add(Restrictions.EqProperty("e2.EnquiryCode", "e.EnquiryCode")); session.CreateCriteria(typeof(Enquiry), "e") .Add(Subqueries.PropertyEq("Property", deatched)) .AddOrder(Order.Asc("EnquiryCode")); </code></pre> <p>My question is, is this the best way? Can anyone suggest a better way?</p>
<p>For aggregations it is better to use SQL and not HQL.Use Nhibernate just for main Entities and their relations (very maintainable design) .Stored procedures are a better place to these aggregations and functions because they are data dependent and not object dependent</p>
OOP design question - keeping track of many similar things <p>I'm designing a Data Access layer for an C#/ASP.net application and I have a question regarding the treatment of parameters in sql queries.</p> <p>At the moment, when a query needs a dynamically set parameter for the Where clause I have to (1) define a variable to hold the value, (2) add a new QueryStringParameter to the SqlDataSource's SelectParameters collection, (3) set the temporary value of the parameter when the method containing the query is called, (4) and set the value of the parameter on the Selecting event of the SqlDataSource.</p> <p>I have a list of ~20 parameters that are used throughout the different queries and it seems as though I should be able to define each once and simply tell the method which to use (and update it's value appropriately).</p> <p>Is there a good way to set this up?</p>
<p>My favorite way to do this is to set up an object data source and then in your table adapter you can add queries for all of the different queries you want to perform with the different parameters you need for your various selects. This gives you the ability to ignore the actual parameters and just use the class to call the methods and pass the appropriate parameters. You also get the benefit that you are returned a first class object, or collection of objects instead of having to worry about typecasting each of the returned values. This method does not work well though if the schema you're returning modifies for each query.</p> <p>This article from Scott Gu's blog seems to cover what I'm talking about in much better depth, but honestly I only skimmed it:</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2006/01/15/435498.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2006/01/15/435498.aspx</a></p>
Obfuscating a .NET Web application <p>Is it possible to obfuscate a .NET web application? I tried to use the Dotofuscator tool that comes with Visual Studio 2005 and I was able to obfuscate the dlls of a precompiled web site, but when I deployed the soultion to an IIS server, I could not the pages of the application.</p> <p>So the question would be: was any of you able to obfuscate a complete .NET web application?</p> <p>Thanks for your answers</p> <p>EDIT: I obfuscated all the dlls on the bin folder. The site is built without allowing updates of the aspx files. After that when I go to <a href="http://serveradress/main.aspx" rel="nofollow">http://serveradress/main.aspx</a>, I get an error saying that main.aspx does not exists</p> <p>PD: I need to obfuscate the code because the application does some license chcecking and I want to make it harder to remove the license checking code</p>
<p>Just bear in mind that is you obfuscate an application that uses reflection, it can cause issues.</p> <p>I personally don't see the need to obfuscate, as <strong>people who <em>really</em> want to see your code, will get their hands on it with effort, regardless if you obfuscate it or not</strong>.</p>
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p> <p>I have basically this:</p> <pre><code>child = pexpect.spawn('command') child.expect('password:') child.sendline('the password') </code></pre> <p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p> <pre><code>child = pexpect.spawn('command2') child.expect('password:') child.sendline('the password') </code></pre> <p>And the code is hanging at the second "spawn"</p> <p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p> <p>Now, the other thing I haven't been able to do is wait until the first one stops. I've tried:<br /> child.close() - it hangs (both with True and False as parameters) child.read(-1) - it hangs<br /> child.expect(pexpect.EOF) - it hangs.<br /> child.terminate() - it hangs (both with True and False as parameters)</p> <p>Any ideas on what could be happening?<br /> NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p> <p>Thanks!</p> <p><hr /></p> <p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return. Also, apparently ssh-copy-id never returns an EOF.</p>
<p>Fortunately or not, but OpenSSH client seems to be very picky about passwords and where they come from.</p> <p>You may try using <a href="http://www.lag.net/paramiko/" rel="nofollow">Paramiko</a> Python SSH2 library. Here's a simple <a href="http://www.lag.net/pipermail/paramiko/2006-January/000180.html" rel="nofollow">example how to use it with password authentication</a>, then issue some shell commands (<code>echo "..." &gt;&gt; $HOME/.ssh/authorized_keys</code> being the simplest) to add your public key on remote host.</p>
C++ Functors - and their uses <p>I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?</p>
<p>A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:</p> <pre><code>// this is a functor struct add_x { add_x(int x) : x(x) {} int operator()(int y) const { return x + y; } private: int x; }; // Now you can use it like this: add_x add42(42); // create an instance of the functor class int i = add42(8); // and "call" it assert(i == 50); // and it added 42 to its argument std::vector&lt;int&gt; in; // assume this contains a bunch of values) std::vector&lt;int&gt; out(in.size()); // Pass a functor to std::transform, which calls the functor on every element // in the input sequence, and stores the result to the output sequence std::transform(in.begin(), in.end(), out.begin(), add_x(1)); assert(out[i] == in[i] + 1); // for all i </code></pre> <p>There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.</p> <p>As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function <code>std::transform</code> should call. It should call <code>add_x::operator()</code>. That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.</p> <p>If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.</p>
Using a user defined parameter in vba <p>I have an access database that ouptuts a query to an excel file. The query uses a date parameter to run. This parameter is chosen by the user. I would like to use the parameter in the filename of the export. How can I accomplish that with the minimum amount of code.</p> <p>01 01 09</p> <p>Ok the new year has begun. sorry for the delay but I was on Holiday.</p> <p>Details. </p> <p>I have an access Database that outputs a report in excel format, the report is dependent on a date parameter that is chosen by the user. This parameter is selected via a textbox (text100) that has a pop up calendar. I would like to use the date in the text box(text100) in the filename.</p>
<p>You have to take responsibility for asking for the parameter. I like using global parameters that I can get/set via global functions - this way they can be set anywhere and the queries can have access to them as well.</p> <p><strong>Just need a couple subs/functions in module:</strong></p> <pre><code>Some Module Dim vParam1 as variant Dim vParam1 as variant Public Sub ParameterSet(byval pParamName as String, byval pParamValue as variant) Select Case pParamName Case "Param1": vParam1 = pParamValue Case "Param2": vParam2 = pParamValue Case Else msgbox pParamName &amp; " parameter not defined" End Select End Sub Public Function ParameterGet(byval pParamName as String) as variant Select Case pParamName Case "Param1": ParamGet = vParam1 Case "Param2": ParamGet = vParam2 Case Else msgbox pParamName &amp; " parameter not defined" End Select End Sub </code></pre> <p><strong>Then in your query</strong> (remove the date parameter)</p> <pre><code>WHERE Field1 = ParameterGet("Param1") </code></pre> <p><strong>Then in your code where you run the export</strong></p> <pre><code>Private Sub Export_Click() dim vParam1 as variant vParam1 = inputbox("Enter the parameter:") ParameterSet "param1", vParam1 Transferspreadsheet blah, blah, FileName:= vParam1 &amp; ".xls" End Sub </code></pre> <p>Obviously this code needs a little tweaking to compile... :-)</p>
How to clone a jQuery Listen plugin event? <p>I have some <code>&lt;tr&gt;</code> elements on my page with a <code>click()</code> event attached to an image that sits inside each one. I use this code</p> <pre><code>$(this).clone(true).appendTo("table#foo"); </code></pre> <p>to do the following:</p> <ul> <li>copy those <code>&lt;tr&gt;</code>s into a different table</li> <li>preserve the click events on the images inside the <code>&lt;tr&gt;</code>s (because of the <code>true</code> argument)</li> </ul> <p>All of that works fine. Now I have added a <a href="http://plugins.jquery.com/project/Listen" rel="nofollow">jQuery Listen</a> event to those <code>&lt;tr&gt;</code>s, so that a user doesn't have to aim precisely: he/she can click anywhere on the <code>&lt;tr&gt;</code> and I can pass the click to the image.</p> <p>It's coded like this:</p> <pre><code>$('tr.record').listen('click','td',function(){ $(this).parent().find("img.clickable").click(); }); </code></pre> <p>The listen() event works fine on the original item, but <strong>on the cloned item, the listen() event fails.</strong> The image's click event still works fine.</p> <p>Here is what Firebug tells me:</p> <pre><code>m(this, e.type) is undefined </code></pre> <p>...and it references line 9 of jquery.listen-1.0.3-min.js.</p> <p><strong>How can I can make the listen() event work on the cloned elements?</strong></p> <h2>Update</h2> <p>By default, jQuery doesn't copy events on cloned elements, but <a href="http://plugins.jquery.com/project/copyEvents" rel="nofollow">this plugin</a> is made to do that.</p> <p>Meanwhile, the author of the listen() plugin suggested a different strategy - see my answer below.</p>
<p>Ariel Flesler, creator of the listen() plugin, gave me this advice via email:</p> <p><em>"I think this can be solved in another way. The idea of Listen (and event delegation) is to actually avoid all the copying of events for new elements."</em></p> <p><em>"You could simply do:"</em></p> <pre><code>$('table#foo').listen('click','td',function(){ $(this).parent().find("img.clickable").click(); }); </code></pre> <p><em>"Or even:"</em></p> <pre><code>$.listen('click','td',function(){ $(this).parent().find("img.clickable").click(); }); </code></pre> <p><em>"The first example will use the table as listener. In the 2nd one, the <code>&lt;html&gt;</code> tag is used. So no matter if you add new td/tr/tables. It'll still work."</em></p>
Memory Mapped Files .NET <p>I have a project and it needs to access a large amount of proprietary data in ASP.NET. This was done on the Linux/PHP by loading the data in shared memory. I was wondering if trying to use Memory Mapped Files would be the way to go, or if there is a better way with better .NET support. I was thinking of using the Data Cache but not sure of all the pitfalls of size of data being saved in the Cache.</p>
<p>I know this is a bit late, but the .NET 4.0 framework now supports memory-mapped files out of the box:</p> <p><a href="http://blogs.msdn.com/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx">http://blogs.msdn.com/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx</a></p>
ASP.NET/C# - Detect File Size from Other Server? <p>I'm trying to find the file size of a file on a server. The following code I got from <a href="http://www.thejackol.com/2005/06/11/aspnet-get-file-size/" rel="nofollow">this guy</a> accomplishes that for your own server:</p> <pre><code>string MyFile = "~/photos/mymug.gif"; FileInfo finfo = new FileInfo(Server.MapPath(MyFile)); long FileInBytes = finfo.Length; long FileInKB = finfo.Length / 1024; Response.Write("File Size: " + FileInBytes.ToString() + " bytes (" + FileInKB.ToString() + " KB)"); </code></pre> <p>It works. However, I want to find the filesize of, for example:</p> <pre><code>string MyFile = "http://www.google.com/intl/en_ALL/images/logo.gif"; FileInfo finfo = new FileInfo(MyFile); </code></pre> <p>Then I get a pesky error saying <code>URI formats are not supported.</code></p> <p>How can I find the file size of Google's logo with ASP.NET?</p>
<p>You can use the <code>WebRequest</code> class to issue an HTTP request to the server and read the <code>Content-Length</code> header (you could probably use HTTP <code>HEAD</code> method to accomplish it). However, not all Web servers respond with a <code>Content-Length</code> header. In those cases, you have to receive all data to get the size. </p>
Can configuration data be encrypted from an installation process? <p>I am developing a .NET (2.0) WinForms utility that connects to a SQL Server 2005 database. I have found reference material, such as <a href="http://stackoverflow.com/questions/42833/how-do-i-avoid-having-the-database-password-stored-in-plaintext-in-sourcecode">Avoiding Plaintext Passwords</a> for handling the actual encryption of the connection string data. I now need to implement the encryption during the installation process so that an administrator can install the utility on a user's desktop, but not provide the user with the database connection information.</p> <p>The sample code all seems geared toward performing the encrypting within the primary application. So the app would need to be executed once for the encryption to take place. If the application is installed but not executed, the configuration information would be in plain text in the configuration file.</p> <p>Can anyone provide information showing how the encryption can be performed from the setup app. Other approaches to the problem are welcome as well (however, due to business requirements, I am not in a position to require Windows authentication for the database connection - I am limited to SQL Server authentication).</p> <p><strong>Edit:</strong> I may have been overly brief with my description. We have already performed a risk assessment and determined that using the built-in .NET framework functionality for encrypting the connection information provides sufficient security for the application. </p> <p>We understand that a truly determined individual could eventually obtain the connection information, and we readily accept that risk. The purpose of encrypting the connection data is to simply raise the bar of effort and to help "keep honest people honest".</p> <p>Having already worked out the means of performing the encryption, I am now trying to work out a method of performing the encryption from within the installation process. Any help along those lines woul be appreciated. Thanks!</p>
<p>The main problem with encrypted configuration is protecting the key used to decrypt the configuration settings.</p> <p>With a server application, you can do this by restricting access to the server. A client WinForms app will need to have access to the key while running as the current user, therefore the user will be able to find the key if he is smart enough.</p> <p>If you can't use Windows authentication for the database connection, or use an n-tier architecture with the data access code on a server, you won't be secure.</p>
Load FreeMarker templates from database <p>I would like to store my FreeMarker templates in a database table that looks something like:</p> <pre><code>template_name | template_content --------------------------------- hello |Hello ${user} goodbye |So long ${user} </code></pre> <p>When a request is received for a template with a particular name, this should cause a query to be executed, which loads the relevant template content. This template content, together with the data model (the value of the 'user' variable in the examples above), should then be passed to FreeMarker.</p> <p>However, the <a href="http://freemarker.sourceforge.net/docs/api/index.html">FreeMarker API</a> seems to assume that each template name corresponds to a file of the same name within a particular directory of the filesystem. Is there any way I can easily have my templates loaded from the DB instead of the filesystem?</p> <p><strong>EDIT:</strong> I should have mentioned that I would like to be able to add templates to the database while the application is running, so I can't simply load all templates at startup into a new StringTemplateLoader (as suggested below).</p> <p>Cheers, Don</p>
<p>We use a StringTemplateLoader to load our tempates which we got from the db (as Dan Vinton suggested)</p> <p>Here is an example:</p> <pre><code>StringTemplateLoader stringLoader = new StringTemplateLoader(); String firstTemplate = "firstTemplate"; stringLoader.putTemplate(firstTemplate, freemarkerTemplate); // It's possible to add more than one template (they might include each other) // String secondTemplate = "&lt;#include \"greetTemplate\"&gt;&lt;@greet/&gt; World!"; // stringLoader.putTemplate("greetTemplate", secondTemplate); Configuration cfg = new Configuration(); cfg.setTemplateLoader(stringLoader); Template template = cfg.getTemplate(firstTemplate); </code></pre> <p><strong>Edit</strong> You don't have to load all templates at startup. Whenever we will access the template, we'll fetch it from the DB and load it through the StringLoader and by calling template.process() we generate (in our case) the XML output.</p>
Bypass IE "The webpage you are viewing..." pop up <p>Is there a way to bypass the following IE popup box:</p> <blockquote> <p>The webapge you are viewing is trying to close the window. Do you want to close this window? Yes|No</p> </blockquote> <p>This is occurring when I add window.close() to the onclick event of an asp.net button control.</p>
<h1>In the opened popup write following</h1> <pre><code>var objWin = window.self; objWin.open('','_self',''); objWin.close(); </code></pre>
How do I call .NET code (C#/vb.net) from vbScript? <p>I imagine I can compile a C# DLL and then expose it as a COM object so that it can be CreateObject'd from VBscript. I'm just not sure the steps involved in doing this...</p>
<p>It can be very simple to do this. But there are a lot of places where it's not so simple. It depends a lot on what your class needs to be able to do, and how you intend to deploy it.</p> <p>Some issues to consider:</p> <ul> <li>Your class has to have a parameterless constructor.</li> <li>It can't expose static methods.</li> <li>Is deploying your COM DLL in the global assembly cache OK? If not, you're going to have to give it a strong name and register it using <code>regasm /codebase</code>.</li> <li>Do you care what GUIDs identify the class and its interfaces? If not, you can let <code>regasm</code> assign them, but they'll be different every time (and every place) the class is registered. If you need the GUIDs to remain invariant across installations, you'll need to mark members with the <code>Guid</code> attribute.</li> <li>Are you going to use the default marshaling of data types between .NET and COM? If not, you're going to need to mark properties and methods with the <code>MarshalAs</code> attribute.</li> <li>Does it matter to you what kind of COM interface your class exposes? If so, you're going to need to deal with the <code>InterfaceType</code> attribute.</li> <li>Does your class need to raise or respond to events? If so, there are implications for how you design your class interface.</li> </ul> <p>There's a very good (if dated) article about COM interop and .Net <a href="http://www.codeproject.com/KB/COM/cominterop.aspx">here</a>. (A lot of things that article talks about, like generating type libraries, is handled for you automatically now.) And <a href="http://msdn.microsoft.com/en-us/library/zsfww439.aspx">Microsoft's documentation</a> is up to date, but not quite so detailed.</p>
.NET - How to build themes for big CSS files <p>I am in charge of providing a theme functionality for a site using a big CSS file (thousands of elements) I've just inherited. Basically we want to allow the user to be able to change the colors on the screen.</p> <p>Every CSS element, besides color definition also have lots of other attributes - size, font, float, etc... As well a specific color appears in various CSS elements.</p> <p>If I use the Theme functionality of ASP.NET to have a different CSS file per theme, I have to duplicate my CSS file across all the themes, and it becomes a maintenance nightmare. </p> <p>Optimally I would like to have a single CSS file (for maintenance) and be able to change the color attributes only.</p> <p>What are the options here?</p>
<p>You only have to duplicate the color attributes so if you have </p> <pre><code>a:hover { text-decoration:none; color:Black; display:block } </code></pre> <p>in your css file in your theme you only need:</p> <pre><code>a:hover { color:Red; } </code></pre> <p>Now in your page you want to make sure you still reference the original css file, and the browser will merge all the styles.</p>
reporting services anonymous access to reports <p>I can't create a NT account for everyone that need access to the reports. Does anyone know or have a link to the info to allow anonymous access to reporting services reports ?</p> <p>Thanks</p>
<p>Thanks, I had tried it before but was failing, tried again and worked fine, must have missed something the first time around.</p> <p>The steps are very simple:</p> <ol> <li>Standard install of SSRS 2005 (Integrated authentication) </li> <li>In IIS, duplicate the ReportingServices virtual directory and name it Public</li> <li>Under Public properties set Directory Security - Authentication and Access Control - to Enable Anonymous access using the IUSR_ account. Uncheck all other access types.</li> <li>Using the report manager, set up a folder named Public, and added the IUSR_ account to the Public directory role manager with a viewonly role. (Assuming you have already established a viewonly role as one with only the 'view reports' task enabled.) </li> <li>Add any other types of administrative/developer accounts</li> </ol>
Spring Integration 1.0 RC2: Streaming file content? <p>I've been trying to find information on this, but due to the immaturity of the Spring Integration framework I haven't had much luck.</p> <p>Here is my desired work flow:</p> <ol> <li><p>New files are placed in an 'Incoming' directory</p></li> <li><p>Files are picked up using a file:inbound-channel-adapter</p></li> <li><p>The file content is streamed, N lines at a time, to a 'Stage 1' channel, which parses the line into an intermediary (shared) representation. </p></li> <li><p>This parsed line is routed to multiple 'Stage 2' channels.</p></li> <li><p>Each 'Stage 2' channel does its own processing on the N available lines to convert them to a final representation. This channel must have a queue which ensures no Stage 2 channel is overwhelmed in the event that one channel processes significantly slower than the others.</p></li> <li><p>The final representation of the N lines is written to a file. There will be as many output files as there were routing destinations in step 4.</p></li> </ol> <p>*<em>'N' above stands for any reasonable number of lines to read at a time, from [1, whatever I can fit into memory reasonably], but is guaranteed to always be less than the number of lines in the full file.</em></p> <p>How can I accomplish <strong>streaming (steps 3, 4, 5)</strong> in Spring Integration? It's fairly easy to do without streaming the files, but my files are large enough that I cannot read the entire file into memory.</p> <p>As a side note, I have a working implementation of this work flow without Spring Integration, but since we're using Spring Integration in other places in our project, I'd like to try it here to see how it performs and how the resulting code compares for length and clarity.</p>
<p>This is a very interesting use case that I'm sorry I missed for such a long time. It's definitely worth creating an issue for. At the moment we have support in Spring Integration for picking up the files and sending <em>references to them</em> around. There is also some rudimentary support for converting the files to a byte[] or a String.</p> <p>The answer is that now you would do step 2 in custom java code, sending the chunks off to a Stage 2 channel. I would recommend against sending references to streams around as message payloads.</p>
Sorting multiple keys with Unix sort <p>I have potentially large files that need to be sorted by 1-n keys. Some of these keys might be numeric and some of them might not be. This is a fixed-width columnar file so there are no delimiters.</p> <p>Is there a good way to do this with Unix sort? With one key it is as simple as using '-n'. I have read the man page and searched Google briefly, but didn't find a good example. How would I go about accomplishing this?</p> <p>Note: I have ruled out Perl because of the file size potential. It would be a last resort.</p>
<p>Take care though:</p> <p>If you want to sort the file primarily by field 3, and secondarily by field 2 you don't want this:</p> <pre><code>sort -k 3 -k 2 &lt; inputfile </code></pre> <p>you want this instead:</p> <pre><code>sort -k 3,3 -k 2,2 &lt; inputfile </code></pre> <p>The first one sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).</p> <pre><code>-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2 (default end of line) </code></pre>
Is const_cast safe? <p>I can't find much information on const_cast. The only info I could find (on Stack Overflow) is:</p> <blockquote> <p>The const_cast&lt;>() is used to add/remove const(ness) (or volatile-ness) of a variable.</p> </blockquote> <p>This makes me nervous. Could using a const_cast cause unexpected behavior? If so, what?</p> <p>Alternatively, when is it okay to use const_cast?</p>
<p><code>const_cast</code> is safe only if you're casting a variable that was originally non-<code>const</code>. For example, if you have a function that takes a parameter of a <code>const char *</code>, and you pass in a modifiable <code>char *</code>, it's safe to <code>const_cast</code> that parameter back to a <code>char *</code> and modify it. However, if the original variable was in fact <code>const</code>, then using <code>const_cast</code> will result in undefined behavior.</p> <pre><code>void func(const char *param, size_t sz, bool modify) { if(modify) strncpy(const_cast&lt;char *&gt;(param), sz, "new string"); printf("param: %s\n", param); } ... char buffer[16]; const char *unmodifiable = "string constant"; func(buffer, sizeof(buffer), true); // OK func(unmodifiable, strlen(unmodifiable), false); // OK func(unmodifiable, strlen(unmodifiable), true); // UNDEFINED BEHAVIOR </code></pre>
Who's Using Cairngorm 2.2 with Imported Web Services? <p>I'm very new to Cairngorm, so apologies for what's probably a simple question:</p> <p>I'm working with a number of WCF services imported into Flex Builder 3 (via Data > Manage Web Services), and I'm wondering how to expose those services to the ServiceLocator in Cairngorm. From what I've read so far, it looks like Cairngorm prefers the services be defined in Services.mxml (or somehow in MXML), but that won't work in my case.</p>
<p>I'm working on an app right now where Services.mxml is driving me nuts... calls are just not being made. I've read the blog posts that describe solutions to this issue but it's a recurring, nagging problem so I want to find a more reliable approach. I believe that you could simply replace the code in your Delegate where you retrieve the reference to the web service </p> <pre><code>this.service = ServiceLocator.getInstance().getWebService("web service name here"); </code></pre> <p>to something like this:</p> <pre><code>this.service = generated.webservices.MyService(); </code></pre> <p>I'm hoping that, after that, the rest should be straight forward. I'm planning to do some testing tonight so I'll let you know how it goes.</p>
ASP.net AJAX: textbox readonly state <p>I currently have a button called Edit and a text box call blah on a ajax updatepanel. is it possible to set the asp.net's textbox Readonly via trigger? </p>
<p>Yes it is possible.</p> <p>Assuming the trigger is the edit button's onclick handler, put the code there...</p>
What's a good way to debug unit tests written with multiple [Row] attributes? <p>When I run the following test in Gallio's Icarus it passes, but when I step into it using TestDriven.NET (Test With->Debugger), it fails because the parameters are not set according to the Row attributes.</p> <p>I was expecting that the method would be called once for each Row attribute applied.</p> <p>What am I doing wrong? If nothing, then what do I need to do to debug these tests when they break? Should I avoid parametrized tests if they are not debuggable?</p> <pre><code>[TestFixture] public class TestDrivenIgnoresMbUnitAttributesWhenDebugging { [Test] [Row(1)] [Row(2)] public void SomeFunc(int x) { Assert.AreNotEqual(default(int), x); } } </code></pre>
<p>Hmm... did you install TestDriven.Net BEFORE installing Gallio?</p> <p>If not, then the Gallio extensions for TestDriven.Net will not be installed. In that case, TestDriven.Net might run the test in "ad-hoc" mode with default values for its parameters.</p> <p>It should be pretty to tell whether this is the case. If the Gallio extensions for TestDriven.Net are installed then you'll see a "Gallio" banner message in the Output Window during test execution. If not you may see something else like "ad-hoc".</p> <p>To fix the problem, reinstall Gallio. Alternately you can use the add/remove features part of the Gallio installer then ensure that the TestDriven.Net components are selected for installation (under "Test Runners").</p>
Replacing a word with another word zero or more times in javascript using regular expressions <p>I have a word : [lesserthen] , that I need to replace with &lt; zero or more times in a string. I'm using the String.replace method to do so. But the word is only replaced one time in the string, I need to be replaced more then one time. I'm very weak with regular expressions and I'm interested to find a solution for this problem.</p> <p>Here is the code I've been using:</p> var wordReplaced="This a text with one [lesserthen], and another [lesserthen]"; wordReplaced=wordReplaced.replace("[lesserthen]"," <p>The result I am aiming is : "This a text with one &lt;, and another &lt;". </p> <p>But what I got instead is : "This a text with one &lt;, and another [lesserthen]"</p>
<p>Try using an actual regex (with "g" option) in the replace instead of a search string, for example:</p> <pre><code>wordReplaced = wordReplaced.replace(/\[lesserthen\]/g,"&lt;"); </code></pre>
C# Round Value of a Textbox <p>I have a small calculator that I am creating in C# (Sharp Develop). The user enters two values and the code returns the third. I am having trouble rounding the third value once it is returned. I have been through a couple of forums and the msdn site and I understand the code that is posted there, but I cant seem to make it work in my situation. Can anyone provide a little help? Reference the code below.</p> <pre><code>int y; decimal x, z; x = int.Parse(tb2_fla.Text); y = int.Parse(tb2_e.Text); z = (x * y * 1.732050808m) / 1000; tb2_kva.Text = z.ToString(); </code></pre> <p>I welcome both assistance and criticism<br /> Greg</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.math.round.aspx" rel="nofollow">Math.Round</a>. Or, since you're going into a string, you could use either the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="nofollow">Standard Numeric Format Strings</a>, or the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="nofollow">Custom ones</a>.</p> <pre><code>Math.Round(z, 2).ToString(); z.ToString("0.00"); </code></pre>
A small question about python's variable scope <p>I am a beginner of python and have a question, very confusing for me. If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function? for example:</p> <pre><code>def hello(x,y): good=hi(iy,ix) "then do somethings,and use the parameter'good'." return something def hi(iy,ix): "code" return good </code></pre>
<p>The scope of functions <code>hello</code> and <code>hi</code> are entirely different. They do not have any variables in common.</p> <p>Note that the result of calling <code>hi(x,y)</code> is some object. You save that object with the name <code>good</code> in the function <code>hello</code>.</p> <p>The variable named <code>good</code> in <code>hello</code> is a different variable, unrelated to the variable named <code>good</code> in the function <code>hi</code>.</p> <p>They're spelled the same, but the exist in different namespaces. To prove this, change the spelling the <code>good</code> variable in one of the two functions, you'll see that things still work.</p> <p><hr /></p> <p>Edit. Follow-up: "so what should i do if i want use the result of <code>hi</code> function in <code>hello</code> function?"</p> <p>Nothing unusual. Look at <code>hello</code> closely.</p> <pre><code>def hello(x,y): fordf150 = hi(y,x) "then do somethings,and use the variable 'fordf150'." return something def hi( ix, iy ): "compute some value, good." return good </code></pre> <p>Some script evaluates <code>hello( 2, 3)</code>.</p> <ol> <li><p>Python creates a new namespace for the evaluation of <code>hello</code>.</p></li> <li><p>In <code>hello</code>, <code>x</code> is bound to the object <code>2</code>. Binding is done position order.</p></li> <li><p>In <code>hello</code>, <code>y</code> is bound to the object <code>3</code>.</p></li> <li><p>In <code>hello</code>, Python evaluates the first statement, <code>fordf150 = hi( y, x )</code>, <code>y</code> is 3, <code>x</code> is 2.</p> <p>a. Python creates a new namespace for the evaluation of <code>hi</code>.</p> <p>b. In <code>hi</code>, <code>ix</code> is bound to the object <code>3</code>. Binding is done position order.</p> <p>c. In <code>hi</code>, <code>iy</code> is bound to the object <code>2</code>.</p> <p>d. In <code>hi</code>, something happens and <code>good</code> is bound to some object, say <code>3.1415926</code>.</p> <p>e. In <code>hi</code>, a <code>return</code> is executed; identifying an object as the value for <code>hi</code>. In this case, the object is named by <code>good</code> and is the object <code>3.1415926</code>.</p> <p>f. The <code>hi</code> namespace is discarded. <code>good</code>, <code>ix</code> and <code>iy</code> vanish. The object (<code>3.1415926</code>), however, remains as the value of evaluating <code>hi</code>.</p></li> <li><p>In <code>hello</code>, Python finishes the first statement, <code>fordf150 = hi( y, x )</code>, <code>y</code> is 3, <code>x</code> is 2. The value of <code>hi</code> is <code>3.1415926</code>.</p> <p>a. <code>fordf150</code> is bound to the object created by evaluating <code>hi</code>, <code>3.1415926</code>.</p></li> <li><p>In <code>hello</code>, Python moves on to other statements.</p></li> <li><p>At some point <code>something</code> is bound to an object, say, <code>2.718281828459045</code>.</p></li> <li><p>In <code>hello</code>, a <code>return</code> is executed; identifying an object as the value for <code>hello</code>. In this case, the object is named by <code>something</code> and is the object <code>2.718281828459045 </code>.</p></li> <li><p>The namespace is discarded. <code>fordf150</code> and <code>something</code> vanish, as do <code>x</code> and <code>y</code>. The object (<code>2.718281828459045 </code>), however, remains as the value of evaluating <code>hello</code>.</p></li> </ol> <p>Whatever program or script called <code>hello</code> gets the answer.</p>
Why do IE and Firefox render the same image differently, how can I prevent it? <p><img src="http://farm4.static.flickr.com/3199/3099078396_a3c4924c81_o.gif" alt="alt text" /></p> <p>On the left you will notice the google logo rendered by IE, I drew a black line at the top and bottom of the G which extends into the FF windows which rendered the same exact logo yet the FF version renders the image larger. There is NO css linked to this page, just plain and simple Html. </p> <p>Can anyone tell me why this is happening and can I prevent it? Is my box just fubar and no one else gets this behavior?</p> <p>Edit: Failed to mention IE7/FF3</p> <p>Edit: Posted Html as requested</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 id="ctl00_Head1"&gt;&lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;img src="http://www.google.com/intl/en_ALL/images/logo.gif" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>I just created a composite image of screenshots of the Google image in IE, Firefox &amp; Chrome and they're all in perfect register (top 2 images at 30% opacity).</p> <p>I believe it has to be a custom zoom you've got set in one of your browsers. Check IE's zoom at the right of the status bar, for example. </p> <p><img src="http://mikescommunity.com/public/images/googleimagecomposite.png" alt="composite image"></p>
How to analyse a HTTP dump? <p>I have a file that apparently contains some sort of dump of a keep-alive HTTP conversation, i.e. multiple GET requests and responses including headers, containing an HTML page and some images. However, there is some binary junk in between - maybe it's a dump on the TCP or even IP level (I'm not sure how to determine what it is).</p> <p>Basically, I need to extract the files that were transferred. Are there any free tools I could use for this?</p>
<p>Use <a href="http://www.wireshark.org/" rel="nofollow">Wireshark</a>.</p> <p>Look into the file format for its dumps and convert your dump to it. Its very simple. Its called the <a href="http://wiki.wireshark.org/Development/LibpcapFileFormat" rel="nofollow">pcap file format</a>. Then you can open it in Wireshark no problem and it should be able to recognize the contents. Wireshark supports many dozens if not many hundred communication formats at various OSI layers (including TCP/IP/HTTP) and is great for this kind of debugging.</p>
What happens when you select a non-existing file for upload in an HTML form? <p>On Internet Explorer, the standard HTML file upload form also allows for direct input of the file name (instead of using the file selector dialog). This makes it possible to enter non-existing files. On other browsers (which do not let you do that) I suppose this case can still occur if you delete the file after having selected it.</p> <p>In order to deal with bugs arising from this problem (like <a href="http://dev.fckeditor.net/ticket/2716" rel="nofollow">this one</a>), I need to add some validation code on the server-side (which is only possible if the request actually goes to the server, of which I am not sure at this point), or on the client-side (which cannot be very straightforward, as you cannot access the actual file from the JavaScript sandbox). Other than that, the only (and possibly best) option seems to be to hide the input box with CSS magic, like GMail does for attachment files.</p> <p>So, what happens when you try to upload a non-existing file? Is there still a POST request being sent? Or will the browser abort, and if it does, how can I detect that?</p>
<p>I think I figured it out.</p> <p>First of all, it seems to make a difference whether it is just the file that does not exist, or the whole path is incorrect. If only the file is missing, apparently a POST does take place.</p> <p>At least in the case I mentioned (FCKEditor's image upload dialog on WinXP and IE6), the browser does not submit the form at all (so that there is nothing that can be done server-side).</p> <p>It is possible to detect the problem on the client, by not using the normal form submit, but by having an onSubmit handler that stops the submit (returns false) and instead submits the form itself using form.submit(). If the file is missing, there will be an exception.</p> <pre><code>try{ form.submit(); } catch (e){ // show some error message } return false; </code></pre>
Moq tests using ExpectSet() with It.Is<T>() aren't behaving as... expected <p>I've isolated the behaviour into the following test case. I'd be grateful to anyone who can tell me how to expect/verify a property set for a <code>List&lt;T&gt;</code> property - it appears there's something going on inside <code>It.Is&lt;T&gt;(predicate)</code> that isn't making a whole lot of sense to me right now. Sample code will run as a console app from VS2008 - you'll need to add a reference to Moq 2.6 (I'm on 2.6.1014.1) - please try uncommenting the different ExpectSet statements to see what's happening...</p> <pre><code>using System; using Moq; using System.Collections.Generic; namespace MoqDemo { public interface IView { List&lt;string&gt; Names { get; set; } } public class Controller { private IView view; public Controller(IView view) { this.view = view; } public void PopulateView() { List&lt;string&gt; names = new List&lt;string&gt;() { "Hugh", "Pugh", "Barney McGrew" }; view.Names = names; } public class MyApp { public static void Main() { Mock&lt;IView&gt; mockView = new Mock&lt;IView&gt;(); // This works - and the expectation is verifiable. mockView.ExpectSet(mv =&gt; mv.Names); // None of the following can be verified. // mockView.ExpectSet(mv =&gt; mv.Names, It.Is&lt;Object&gt;(o =&gt; o != null)); // mockView.ExpectSet(mv =&gt; mv.Names, It.Is&lt;List&lt;string&gt;&gt;(names =&gt; names.Count == 3)); // mockView.ExpectSet(mv =&gt; mv.Names, It.IsAny&lt;IList&lt;String&gt;&gt;()); Controller controller = new Controller(mockView.Object); controller.PopulateView(); try { mockView.VerifyAll(); Console.WriteLine("Verified OK!"); } catch (MockException ex) { Console.WriteLine("Verification failed!"); Console.WriteLine(ex.Message); } Console.ReadKey(false); } } } } </code></pre>
<p>The second parameter of ExpectSet() is the value you're expecting. You can't use <code>It.Is&lt;T&gt;</code> in this case as there's no overload that takes a predicate - though it would be nice ;) Here's a (simplified) excerpt from your sample, illustrating the use of a value:</p> <pre><code>var mockView = new Mock&lt;IView&gt;(); var list = new List&lt;string&gt; { "Hugh", "Pugh", "Barney McGrew" }; mockView.ExpectSet(mv =&gt; mv.Names, list); mockView.Object.Names = list; </code></pre> <p>Hope that helps.</p> <p>Edit: fixed typo.</p>
Best practices to test Asp.net MVC applications <p>Whats the best practice to test an Asp.net MVC application?</p>
<p>Choose your testing framework - I recommend <a href="http://www.codeplex.com/" rel="nofollow" title="xUnit.net">xUnit.net</a>.</p> <p>Decouple your classes using interfaces and use constructor injection in your controllers to satisfy dependencies. In your tests, pass mocks to your controllers using a mocking framework - I recommend <a href="http://code.google.com/p/moq/" rel="nofollow">MoQ</a>.</p> <p>When running the web site rather than tests, either have default constructors on your controllers that call the other constructors and pass your real implementations of your interfaces; or use a Dependency Injection (DI) container to do it automatically - I recommend <a href="http://structuremap.sourceforge.net/Default.htm" rel="nofollow">StructureMap</a>.</p> <p>Hope that helps.</p>
Have you come across any reason for three levels of indirection? <p>Just flicking through one of my favourite books (Ellen Ullman's The Bug) and there is a small bit where one programmer confronts another over three levels of indirection:</p> <pre><code>***object_array = ***winarray; </code></pre> <p>I get the idea of double indirection - a way of passing a pointer into a function, and allowing it to point to an object created within the function.</p> <p>But have you come across any reason to use three (or more) levels of indirection?</p>
<p>Sure<br /> 4 dimensional arrays.<br /> It doesn't take too much for an application for such an array either. Say some sort of lookup table. I've had lookup tables of 8 and more dimensions.</p>
jQuery: Can I do $('.superset').$('.within') instead of $('.within', $('.superset'))? <p>Can jQuery be extended so that I can use the above syntax?</p> <p>I can't figure out how to prototype whatever it is $() returns, so that I can call $().$()</p> <p>Thanks.</p>
<p>you can use <a href="http://docs.jquery.com/Traversing/find" rel="nofollow"><code>find()</code></a></p> <p>eg: <code>$('.superset').find('.within');</code></p> <p>or much simpler, <code>$('.superset .within');</code></p>
Space-Efficient Data Structure for Storing a Word List? <p>Is there anything better than a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a> for this situation?</p> <ul> <li>Storing a list of ~100k English words</li> <li>Needs to use minimal memory</li> <li>Lookups need to be reasonable, but don't have to be lightning fast</li> </ul> <p>I'm working with Java, so my first attempt was to just use a Set&lt;String&gt;. However, I'm targeting a mobile device and already running low on memory. Since many English words share common prefixes, a trie seems like a decent bet to save some memory -- anyone know some other good options?</p> <p>EDIT - More info - The data structure will be used for two operations</p> <ul> <li>Answering: Is some word XYZ in the list?</li> <li>Generating the neighborhood of words around XYZ with one letter different</li> </ul> <p>Thanks for the good suggestions</p>
<p>One structure I saw for minimizing space in a spelling dictionary was to encode each word as:</p> <ul> <li>the number of characters (a byte) in common with the last; and</li> <li>the new ending.</li> </ul> <p>So the word list</p> <pre><code>HERE would encode as THIS sanctimonious 0,sanctimonious sanction 6,on sanguine 3,guine trivial 0,trivial </code></pre> <p>You're saving 7 bytes straight up there (19%), I suspect the saving would be similar for a 20,000 word dictionary just due to the minimum distances between (common prefixes of) adjacent words.</p> <p>To speed lookup, there was a 26-entry table in memory which held the starting offsets for words beginning with a, b, c, ..., z. The words at these offsets always had 0 as the first byte as they had no letters in common with the previous word.</p> <p>This seems to be sort of a trie but without the pointers, which would surely get space-expensive if every character in the tree had a 4-byte pointer associated with it.</p> <p>Mind you, this was from my CP/M days where memory was much scarcer than it is now.</p>
ASP.NET MVC Upgrade to Beta: IControllerFactory is defined in an assembly that is not referenced <p>I'm currently in the process of updating a site from preview 2 of ASP.NET MVC to the Beta release. I'm down to my last compile error with no solution in site after an exhaustive search. I have some code in Global.asax.cs which sets up IOC using the Windsor container:</p> <pre><code>ControllerBuilder.Current.SetControllerFactory(typeof(WindsorControllerFactory)); </code></pre> <p>The compiler is complaining that:</p> <pre><code>The type 'System.Web.Mvc.IControllerFactory' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. </code></pre> <p>The weird thing is that this assembly <strong>is</strong> referenced. I reference it from the MVC beta assemblies folder and set to copy local. I can even delete the bin directory, rebuild, then view the assembly in reflector and see the interface. I've tried removing and re-adding the reference, changing web.config's assemblies and namespace sections. I even removed System.Web.Mvc from the GAC to make sure it was using the correct copy.</p> <p>While writing this question it occurred to me that perhaps Windsor is internally expecting the older version of the assembly. I'm downloading the latest from MvcContrib to determine if this is the issue and I'll post the result. If this is the case, shouldn't the version number of the assembly have changed with the latest release to make this obvious?</p> <p>Thanks for reading, Brett</p>
<p>PublicKeyToken=null doesn't seem right...</p> <p><strong>Edit:</strong> I was right, the PublicKeyToken should be "31bf3856ad364e35". It sounds like they're linked against a private build of System.Web.Mvc.dll that isn't signed.</p>
Alternate background colors for list items <p>I have a list, and each item is linked, is there a way I can alternate the background colors for each item?</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="link"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="link"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="link"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="link"&gt;Link 4&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="link"&gt;Link 5&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
<p>How about some lovely CSS3?</p> <pre><code>li { background: green; } li:nth-child(odd) { background: red; } </code></pre>