input
stringlengths
51
42.3k
output
stringlengths
18
55k
Inheriting a .net class <p>Ok here's what I'm trying to do I want to write a class that inherits everything from the class ListItem</p> <pre><code>class RealListItem : ListItem { public string anExtraStringINeed; } </code></pre> <p>For some reason or another .net is treating all the members like they are private when I try to do this so my class is worthless.</p> <p>I tried to do a work around and do it like this:</p> <pre><code>class RealListItem : ListItem { public string anExtraStringINeed; public ListItem list; } </code></pre> <p>but it still doesn't work because I need to use it in a function that uses the accepts type ListItem and RealListItem isn't playing nice like it should. I can do aRealListItem.list but that only passes the list from RealListItem I need the whole object to be passed along.</p> <p>Whats with this am I doing something wrong or will microsoft just not let you inherit .net classes?</p>
<p>The System.Web.UI.Controls.ListItem class is "sealed"... That means you cannot inherit from it... </p>
Is there a JavaScript alert that doesn't pause the script? <p>I'm looking for something like <code>alert()</code>, but that doesn't "pause" the script.</p> <p>I want to display an alert and allow the next command, a form <code>submit()</code>, to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK.</p> <p>Is there something like this or is it just one of those impossible things?</p>
<p>You could do the alert in a setTimeout (which a very short timeout) as setTimeout is asynchronous:</p> <pre><code>setTimeout("alert('hello world');", 1); </code></pre> <p>Or to do it properly you really show use a method rather than a string into your setTimeout:</p> <pre><code>setTimeout(function() { alert('hello world'); }, 1); </code></pre> <p>Otherwise you open yourself up to JavaScript injection attacks. When you pass a string it is run through the JavaScript <code>eval</code> function.</p>
What are use-cases for a coroutine? <p>The concept of a <a href="http://en.wikipedia.org/wiki/Coroutine">coroutine</a> sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use-cases for coroutines, that can be solved more elegant, simpler or more efficient as with other methods?</p>
<p>Some good answers describing what coroutines are.</p> <p>But for an actual use-case. Take a web server. It has multiple simultaneous connections, and it wants to schedule reading and writing all of them.</p> <p>This can be implemented using coroutines. Each connection is a coroutine that reads/writes a small amount of data, then "yields" control to the scheduler, which passes to the next coroutine (which does the same thing) as we cycle through all the available connections.</p>
Variable (dynamic) OPTION lists in HTML SELECT using IE <p>I'm trying to implement a dynamic OPTION list in JavaScript. Depending on other selections in the web form, some of the OPTIONS in a specific SELECT are not valid. Things I've tried that don't work in IE are: </p> <ul> <li>populate all options, then set the disabled property for those that are invalid</li> <li>populate all options and use option groups, then disable invalid option groups </li> <li>I even tried using a style of text-decoration:line-through</li> </ul> <p>At this point I'm resigned to repopulating the SELECT with only valid OPTIONs, but it seems like there ought to be a better way that actually works in IE. I require compatibility with IE6 and up. How have you dealt with this?</p>
<p><a href="http://webbugtrack.blogspot.com/2007/11/bug-293-cant-disable-options-in-ie.html" rel="nofollow">IE doesn't support the disabled attribute on options</a>, and worse yet, <a href="http://webbugtrack.blogspot.com/2007/11/bug-280-lack-of-events-for-options.html" rel="nofollow">IE doesn't support events on options</a>, and the <a href="http://webbugtrack.blogspot.com/2007/11/bug-291-no-styling-options-in-ie.html" rel="nofollow">styling abilities are very limited in IE</a>.</p> <p>Until IE joins the rest of the browser world in terms of common support for basic elements and basic functionality, you are SOL.</p>
what's the best way to parse a body of text against multiple (15+) regexes on each line? <p>I have a body of text that I have to scan and each line contains at least 2 and sometimes four parts of information. The problem is that each line can be 1 out of 15-20 different actions.</p> <p>in ruby the current code looks somewhat like this:</p> <pre> text.split("\n").each do |line| #around 20 times.. .............. expressions['actions'].each do |pat, reg| #around 20 times ................. </pre> <p>this obviously is 'THE PROBLEM' I did manage to make it faster (in c++ by a 50% margin) by combining all the regexen into one but that is still not the speed I require -- I need to parse thousands of these files FAST!</p> <p>Right now I match them with regexes -- however this is intolerably slow. I started with ruby and hopped over to c++ in hopes that I'd get a speed boost and it just isn't happening.</p> <p>I've casually read on PEGs and grammar based parsing but it looks somewhat difficult to implement. Is this the direction I should head or are there different routes?</p> <p>basically I'm parsing poker hand histories and each line of the hand history usually contains 2-3 bits of information that I need to collect: who the player was, how much money or what cards the action entailed.. etc..</p> <p>sample text that needs to be parsed:</p> <pre> buriedtens posts $5 The button is in seat #4 *** HOLE CARDS *** Dealt to Mayhem 31337 [8s Ad] Sherwin7 folds OneMiKeee folds syhg99 calls $5 buriedtens raises to $10 </pre> <p>after I collect this information each action is turned into an xml node</p> <p>right now my ruby implementation of this is much faster than my c++ one but that's prob. just cause I have not written in c code for well over 4-5 years</p> <p><strong>UPDATE:</strong> I don't want to post all the code here but so far my hands/second look like the following:</p> <pre> 588 hands/second -- boost::spirit in c++ 60 hands/second -- 1 very long and complicated regex in c++ (all the regexen put together) 33 hands/second -- normal regex style in ruby </pre> <p>I'm currently testing antlr to see if we can go any further but as of right now I'm very very happy with spirit's results.</p> <p>Related question: <a href="http://stackoverflow.com/questions/192957/efficiently-querying-one-string-against-multiple-regexes">Efficiently querying one string against multiple regexes.</a></p>
<p>I would suggest </p> <ul> <li><a href="http://spirit.sourceforge.net/" rel="nofollow">Boost Spirit</a> or </li> <li><a href="http://www.antlr.org/" rel="nofollow">Antlr</a> if the grammar is complex; </li> <li><a href="http://www.boost.org/doc/libs/1_37_0/doc/html/xpressive.html" rel="nofollow">Xpressive</a> if it's a little simpler,</li> <li><a href="http://www.boost.org/doc/libs/1_37_0/libs/tokenizer/index.html" rel="nofollow">Tokenizer</a> and handmade code if it's trivial. </li> </ul> <p>Good luck</p>
In SQL*Plus, how do I change the prompt to show the connected user and database? <p>To show, for example....</p> <pre><code>USER@SID &gt; </code></pre> <p>I thought this was potentially helpful to a few people so I'm going to answer it too!</p>
<p>Amend your $ORACLE_HOME\sqlplus\admin\glogin.sql script - add:</p> <pre><code>set sqlprompt "_user '@' _connect_identifier &gt; " </code></pre> <p>to the end of the file.</p> <p>In Oracle 10g this will change correctly each time you issue a "conn". For clients before 10g it won't change when you do a "conn" but will remain as the username/db you first connected to.</p> <p>You can also use _date for the current date and _privilege for the privilege (eg SYSDBA) of the connected user.</p> <p>Reference:</p> <p><a href="http://www.acs.ilstu.edu/docs/Oracle/server.101/b12170/whatsnew.htm">http://www.acs.ilstu.edu/docs/Oracle/server.101/b12170/whatsnew.htm</a></p>
How do I select multiple sets of attributes within an XML document using XPath? <p>I am having trouble constructing a single XPath statement to return two different sets of attributes. </p> <p>For example take the following XML document:</p> <pre><code>&lt;root&gt; &lt;line name="one" alpha="a1" beta="b1"/&gt; &lt;line name="two" alpha="a2" beta="b2"/&gt; &lt;line name="three" alpha="a3" beta="b3"/&gt; &lt;/root&gt; </code></pre> <p>If I use the following XPath statement:</p> <pre><code>//@alpha </code></pre> <p>It yields the following attribute set:</p> <pre><code>alpha="a1" alpha="a2" alpha="a3" </code></pre> <p>What statement do I use to yield the following attribute set:</p> <pre><code>alpha="a1" alpha="a2" alpha="a3" beta="b1" beta="b2" beta="b3" </code></pre>
<p>By using the <code>|</code> operator in an XPath expression you can select several paths:</p> <pre><code>//@alpha | //@beta </code></pre>
Mutli-threaded application hanging on _dl_sysinfo_int80 <p>I have a multi-threaded application that is hanging on a call to _dl_sysinfo_int80(). According to gdb, all threads are stuck in this call.</p> <p>The top of the stack trace looks like:</p> <pre><code>#0 0x002727a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 #1 0x004f23de in __lll_mutex_lock_wait () from /lib/tls/libpthread.so.0 #2 0x004ef00b in _L_mutex_lock_35 () from /lib/tls/libpthread.so.0 #3 0x092828ac in construction vtable for std::ostream-in-std::basic_stringstream&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; () </code></pre> <p>Any idea what could be causing this?</p>
<p>int 80 is the software interrupt to make a kernel level system call. My guess is that pthread is doing a call in to the kernel that is hanging. There could be any number of reasons for why all of your threads would hang on a mutex like this:<br> - The mutex is locked by another thread that exited without releasing the lock<br> - The mutex is locked by one of the threads that is typing to lock it and wasn't declared recursive<br> - The mutex was never initialized at all<br> - The mutex has been corrupted by a bad pointer, stack problem, some other type of general memory corruption.<br></p>
Is there a way to send optional parameters to an action? <p>Can I send optional parameters (empty strings, null int?'s etc) to an action through a GET request in asp.net mvc? (one sentence question!)</p>
<p>You can do optional parameters with the routing table fairly easily, just specify the defaults in the route of the global.cs file.</p> <p>So for a search page with an optional query and page you would have something like</p> <pre><code>RouteTable.Routes.Add(new Route { Url = "Search/[query]/[page]", Defaults = new { controller="Search", action="Results", page=1 }, RouteHandler = typeof(MvcRouteHandler) }); </code></pre> <p>Default page for your search is then 1.</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" rel="nofollow">This example is found here on Scott Gu's blog.</a></p>
RegDelete cannot delete Registry key in WSH 5.7 <p>Based on the advice provided at <a href="http://www.tweakguides.com/VA_4.html" rel="nofollow">http://www.tweakguides.com/VA_4.html</a> to prevent Windows Vista from "intelligently" rearranging column formats in Windows Explorer, I have written a script to automate the process a little.</p> <pre><code>Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") 'Remove the "filthy" reg keys first. regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU\" WScript.Echo "Deleting " &amp; regKey &amp; VbCrLf WshShell.RegDelete regKey regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\" WScript.Echo "Deleting " &amp; regKey &amp; VbCrLf WshShell.RegDelete regKey 'Then recreate a clean Bags key, with sub-keys and FolderType value. regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\ Windows\Shell\Bags\AllFolders\Shell\FolderType" WScript.Echo "Creating " &amp; regKey &amp; " as 'NotSpecified' REG_SZ " &amp; VbCrLf WshShell.RegWrite regKey, "NotSpecified", "REG_SZ" WScript.Echo "Now define the columns of your preference in Windows Explorer," &amp; VbCrLf WScript.Echo "and click the Apply to Folders button in Folder Options." &amp; VbCrLf </code></pre> <p>But it is refusing to delete the registry key</p> <pre><code>E:\archive\settings\Windows Vista Explorer columns.vbs(9, 1) WshShell.RegDelete: Unable to remove registry key "HKCU\Software\Classes\Local Settings\Software\Mi crosoft\Windows\Shell\BagMRU\". </code></pre> <p>The suggestion is to put trailing "\" to indicate a key, which I did. Any ideas?</p>
<p>Does your registry setting have subkeys? I think you have to delete those before you can delete the key.</p>
Vector or diagram drawing webservice <p>I have a webapp from which I'd like to insert diagrams and images quickly and easily. I expect there is, somewhere out there, a webservice which will take a URL with a parameter that describes the vector graphics or diagram and returns an image.</p> <p>No unlike what google charts does for graphing data.</p> <p>Any resources or ideas on this?</p> <p>If I had to build it myself, do you have some ideas of how I might accomplish that?</p> <p>For instance, does PHP/asp/etc have a graphics library that's capable of rendering simple vector graphics?</p>
<p>Check out <a href="http://raphaeljs.com/" rel="nofollow">Raphael</a>. Done by a bloke here in Australia.</p>
How to dynamically call child class methods in PHP 5? <pre><code>&lt;?php class foo { //this class is always etended, and has some other methods that do utility work //and are never overrided public function init() { //what do to here to call bar-&gt;doSomething or baz-&gt;doSomething //depending on what class is actually instantiated? } function doSomething() { //intentionaly no functionality here } } class bar extends foo { function doSomething() { echo "bar"; } } class baz extends foo { function doSomething() { echo "baz"; } } ?&gt; </code></pre>
<p>You just have to call $this->doSomething(); in your init() method.</p> <p>Due to polymorphism, the correct method of the child object will be called at runtime depending on the class of the child.</p>
How to pass a parameter to a dynamically set Javascript function? <p>Ok, I have one Javascript that creates rows in a table like this:</p> <pre><code> function AddRow(text,rowID) { var tbl = document.getElementById('tblNotePanel'); var row = tbl.insertRow(tbl.rows.length); var cell = row.insertCell(); var textNode = document.createTextNode(text); cell.id = rowID; cell.style.backgroundColor = "gold"; cell.onclick = clickTest; cell.appendChild(textNode); } </code></pre> <p>In the above function I set the cell's "onclick" function to call another Javascript function called "clickTest". My question is, when I assign the "onclick" event to call "clickTest", how do I set parameter information to be sent when the "clickTest" method is called on the cell's "onclick" event? Or, how do I access the cell's ID in the "clickTest" function?</p> <p>Thanks, Jeff</p>
<p>Try this:</p> <pre><code>cell.onclick = function() { clickTest(rowID); }; </code></pre> <p>The idea is that you are binding the onclick handler to the anonymous function. The anonymous function calls clickTest with rowID as the parameter.</p>
Why does ASP.NET webforms need the Runat="Server" attribute? <p>Why do I have to specify <code>runat="server"</code> on all my ASP.NET controls when it is a mandatory attribute and <code>server</code> is the only option available in my limited knowledge of ASP.NET, and I get an error if I don't use it?</p> <p>I do understand that I can optionally use it on my HTML tags, and I do understand the client/server paradigm and what it is actually specifying.</p> <p>Is it a redundant tag that could just be implied by the control being an ASP.NET control, or is there an underlying reason?</p>
<p>I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being <code>runat="server"</code> or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.</p> <p>This conversation was had on Mike Schinkel's <a href="http://mikeschinkel.com/blog/whyrunatserverforaspnetpart2/">Blog</a> between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):</p> <blockquote> <p><em>[...]</em> but the importance of <code>&lt;runat="server"&gt;</code> is more for consistency and extensibility. </p> <p>If the developer has to mark some tags (viz. <code>&lt;asp: /&gt;</code>) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <code>&lt;runat="server"&gt;</code> attribute, this is negated.</p> </blockquote> <p>It continues:</p> <blockquote> <p>If <code>&lt;runat=client&gt;</code> was required for all client-side tags, the parser would need to parse all tags and strip out the <code>&lt;runat=client&gt;</code> part.</p> </blockquote> <p>He continues: </p> <blockquote> <p>Currently, If my guess is correct, the parser simply ignores all text (tags or no tags) unless it is a tag with the <code>runat=server</code> attribute or a “<code>&lt;%</code>” prefix or ssi “<code>&lt;!– #include</code>… <em>(...)</em> Also, since ASP.NET is designed to allow separation of the web designers (foo.aspx) from the web developers (foo.aspx.vb), the web designers can use their own web designer tools to place HTML and client-side JavaScript without having to know about ASP.NET specific tags or attributes.</p> </blockquote>
What is the best way of converting a Microsoft Word document into XHTML? <p>I would like to programatically convert a Microsoft Word document into XHTML. The language of choice is PHP, so I would appreciate any suggestions with PHP.</p> <p>The initial idea is trying to convert the doc file into odt, and then use the <a href="http://odt2xhtml.eu.org/index_en.html" rel="nofollow">Odt2Xhtml</a> PHP class to get it into XHTML format.</p> <p>Any better way to do this?</p>
<p>If you're running Linux one way to go would be to install OpenOffice on the server.</p> <p>Example instructions for a 'headless' (i.e. no UI) install can be found <a href="http://www.oooforum.org/forum/viewtopic.phtml?t=6691">here</a>.</p> <p>You could then use a nice CLI app like <a href="http://dag.wieers.com/home-made/unoconv/">unoconv</a> executed via shell_exec to do your conversions via PHP.</p>
SQL DataReader missing a row in loop <p>When running the following code it leaves out one row. When I do a files.Count it says there are 4 rows but there is no data stored for the 4th row. When I run the stored procedure from within SQL Manager it returns all 4 rows and all the data. Any help?</p> <pre><code> List&lt;File&gt; files = new List&lt;File&gt;(); SqlConnection active_connection = new SqlConnection(m_connection_string); SqlCommand cmd = new SqlCommand(); SqlDataReader dr = null; try { active_connection.Open(); cmd.Connection = active_connection; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "dalsp_Select_Organization_Files"; SqlParameter param; param = cmd.Parameters.Add("@p_organization_guid", SqlDbType.UniqueIdentifier); param.Value = new Guid(organization_guid); param = cmd.Parameters.Add("@p_file_type", SqlDbType.NVarChar, 50); param.Value = file_type; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (dr.HasRows) { while (dr.Read()) { File file = new File(); file.OrganizationGuid = dr["OrganizationGuid"].ToString(); file.FileGuid = dr["FileGuid"].ToString(); file.FileLocation = dr["FileLocation"].ToString(); file.FileName = dr["FileName"].ToString(); file.FileType = (FileTypeEnum)Enum.Parse(typeof(FileTypeEnum), dr["FileType"].ToString()); file.FileExtension = dr["FileExtension"].ToString(); file.FileDescription = dr["FileDescription"].ToString(); file.ThumbnailPath = dr["ThumbnailPath"].ToString(); files.Add(file); } } dr.Close(); dr = null; active_connection.Close(); cmd = null; } catch (Exception) { throw; } finally { if (active_connection.State != ConnectionState.Closed) { active_connection.Close(); active_connection.Dispose(); } } return files; </code></pre>
<p>If you are saying your files collection has 4 items, but the 4 item contains no value, what do you mean by that? Is it null, does the object have no data, or does it throw an index out of range exception?</p> <p>Are you doing a files[4] or something like the following?</p> <pre><code>for(int x = 1; x &lt; files.length; x++) { files[x] } </code></pre> <p>That won't work. Remember 0 based indexing in C#.</p> <p>As a side note, you could do away with your try catch statments by doing something like:</p> <pre><code>using (SqlConnection connection = new SqlConnection(conn_string)) { connection.Open(); using (SqlCommand cmd = new SqlCommand("SELECT * FROM MyTable", connection)) { using (SqlDataReader dr = cmd.ExecuteReader()) { return result; } } } </code></pre> <p>The using statement will guarantee disposal (and therefore the closing) of the reader and connection.</p>
problem with cross-domain ajax calls <p>i have two servers a main site and a static server. i want to get a file's content from ajax in runtime, which is stored in static server. obviously cross domain problem will occur.</p> <p>so what i am trying to do is storing that ajax .js in the static server, so that calling the local file wont be a problem.</p> <p>but after i include that js file from static, still that problem remains...</p> <p>Any solutions?!</p>
<p>n't use X domain Ajax Requests. Create a "proxy" on your own server (domain) then forward the call to the other domain, cache it, check for security issues and send it back to client again...</p>
Spin Control in Delphi <p>I want to use a "spin button control" (also known as an up-down control) in my Delphi Win 32 application (I'm using Delphi 2007). </p> <p>The aim is to have a control that looks like in Microsoft Office:</p> <p></p> <p>I found this on the Microsoft website: <a href="http://msdn.microsoft.com/de-de/library/sfac27cz(VS.80).aspx" rel="nofollow">CSpinButtonCtrl Class</a></p> <p>But I haven't so far found a control that uses this class - here's where I've been searching:</p> <ul> <li>The SpinEdit control in Delphi looks well... not so good, and doesn't seem to use the official Microsoft control</li> <li>The JVCL classes have their own implementation</li> <li>A Google search did not return any results (except some home-brew up/down controls)</li> <li>I couldn't find something in the Jedi API as well</li> </ul> <p>Can somebody please point me to where I can find a Delphi implementation of the common spin control from Microsoft, or how I can do that myself?</p>
<p>Have a look at TUpDown. It wraps the Win32 control.</p>
Linq to SQL update not working using Repository pattern <p>I am using asp.net mvc for an application. I've taken some guidance from Rob Conery's series on the MVC storefront. I am using a very similar data access pattern to the one that he used in the storefront.</p> <p>However, I have added a small difference to the pattern. Each class I have created in my model has a property called IsNew. The intention on this is to allow me to specify whether I should be inserting or updating in the database.</p> <p>Here's some code:</p> <p>In my controller:</p> <pre><code>OrderService orderService = new OrderService(); Order dbOrder = orderService.GetOrder(ID); if (ModelState.IsValid) { dbOrder.SomeField1 = "Whatever1"; dbOrder.SomeField2 = "Whatever2"; dbOrder.DateModified = DateTime.Now; dbOrder.IsNew = false; orderService.SaveOrder(dbOrder); } </code></pre> <p>And then in the SQLOrderRepository:</p> <pre><code>public void SaveOrder(Order order) { ORDER dbOrder = new ORDER(); dbOrder.O_ID = order.ID; dbOrder.O_SomeField1 = order.SomeField1; dbOrder.O_SomeField2 = order.SomeField2; dbOrder.O_DateCreated = order.DateCreated; dbOrder.O_DateModified = order.DateModified; if (order.IsNew) db.ORDERs.InsertOnSubmit(dbOrder); db.SubmitChanges(); } </code></pre> <p>If I change the controller code so that the dbOrder.IsNew = true; then the code works, and the values are inserted correctly.</p> <p>However, if I set the dbOrder.IsNew = false; then nothing happens...there are no errors - it just doesn't update the order.</p> <p>I am using DebuggerWriter here: <a href="http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11" rel="nofollow">http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11</a> to trace the SQL that is being generated, and as expected, when the IsNew value is true, the Insert SQL is generated and executed properly. However, when IsNew is set to false, there appears to be no SQL generated, so nothing is executed.</p> <p>I've verified that the issue here (http://stackoverflow.com/questions/206532/linq-not-updating-on-submitchanges) is not the problem.</p> <p>Any help is appreciated.</p>
<p>In your SaveOrder method you are always creating a new ORDER object. You need to change this so that if order.IsNew is false, it retrieves the existing one from the DB and updates it instead.</p> <pre><code>public void SaveOrder(Order order) { ORDER dbOrder; if (order.IsNew) { dbOrder = new ORDER(); dbOrder.O_ID = order.ID; } else { dbOrder = (from o in db.ORDERS where o.O_ID == order.ID select o).Single(); } dbOrder.O_SomeField1 = order.SomeField1; dbOrder.O_SomeField2 = order.SomeField2; dbOrder.O_DateCreated = order.DateCreated; dbOrder.O_DateModified = order.DateModified; if (order.IsNew) db.ORDERs.InsertOnSubmit(dbOrder); db.SubmitChanges(); } </code></pre>
Have you ever used a genetic algorithm in real-world applications? <p>I was wondering how common it is to find genetic algorithm approaches in commercial code.</p> <p>It always seemed to me that some kinds of schedulers could benefit from a GA engine, as a supplement to the main algorithm.</p>
<p>Genetic Algorithms have been widely used commercially. Optimizing train routing was an early application. More recently fighter planes have used GAs to optimize wing designs. I have used GAs extensively at work to generate solutions to problems that have an extremely large search space.</p> <p>Many problems are unlikely to benefit from GAs. I disagree with Thomas that they are too hard to understand. A GA is actually very simple. We found that there is a huge amount of knowledge to be gained from optimizing the GA to a particular problem that might be difficult and as always managing large amounts of parallel computation continue to be a problem for many programmers.</p> <p>A problem that would benefit from a GA is going to have the following characteristics:</p> <ul> <li>A good way to encode potential solutions</li> <li>A way to compute an a numerical score to evaluate the quality of the solution</li> <li>A large multi-dimensional search space where the answer is non-obvious</li> <li>A good solution is good enough and a perfect solution is not required</li> </ul> <p>There are many problems that could probably benefit from GAs and in the future they will probably be more widely deployed. I believe that GAs are used in cutting edge engineering more than people think however most people (like my company does) guards those secrets extremely closely. It is only long after the fact that it is revealed that GAs were used.</p> <p>Most people that deal with "normal" applications probably don't have much use for them though.</p>
How to make Oracle procedure return result sets <p>SQL Server procedure can return result sets. I have a table <strong>emp(emp__id, emp__name, ...)</strong>. The procedure below will return a list of employees that matched with the name provided.</p> <pre><code>CREATE OR REPLACE PROCEDURE get_employee_by_name ( @name VARCHAR(100) ) AS SELECT emp_id, emp_name FROM emp WHERE emp_name = @name; </code></pre> <p>So in the client code, to get the data I use ADO.NET.</p> <pre><code>SQLDataAdapter adapter = new SQLDataAdapter("get_employee_by_name", cnString); SQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable dt = new DataTable("employee"); adapter.Fill(dt); </code></pre> <p>How can I code equivalently in PL/SQL?</p>
<p>Use a Ref cursor for the Stored Procedure:<br /> <a href="http://www.oradev.com/ref_cursor.jsp" rel="nofollow">http://www.oradev.com/ref_cursor.jsp</a> </p> <p>For the client part use the Oracle Data Provider. You can download it from Oracle and the syntax is similar to the SQLDataAdapter. Something like this:</p> <pre><code>OracleDataAdapter da = new OracleDataAdapter(); da.SelectCommand = new OracleCommand("get_employee_by_name", Connection); OracleParameter prm = da.SelectCommand.Parameters.Add("pName", OracleDbType.VarChar2); prm.Direction = ParameterDirection.Input; prm.Value = "MyName"; prm = da.SelectCommand.Parameters.Add("pResult", OracleDbType.RefCursor); prm.Direction = ParameterDirection.Output; DataTable dt = new DataTable(); da.Fill(dt); </code></pre>
Can I store the generics attribute into an object's field <p>Assuming the following class stub:</p> <pre><code>public class Foo&lt;T&gt; { private Class&lt;T&gt; type; public Foo&lt;T&gt; () {} } </code></pre> <p>Can I store the generic type <code>T</code> into the field <code>type</code> in the constructor, without changing the constructor's signature to "<code>public Foo&lt;T&gt; (Class&lt;T&gt; type)</code>"? </p> <p>If yes, how? If no, why?</p> <p>"<code>type = T</code>" doesn't seem to work.</p>
<p>No - type erasure means that you have to provide <em>something</em> at execution time. You could provide either an instance of <code>T</code> or <code>Class&lt;T&gt;</code> but the class itself will just have every occurrence of T replaced with <code>Object</code>.</p> <p>This kind of thing is one of the biggest disadvantages of Java's generics vs those in .NET. (On the other hand, the variance story is stronger - if more confusing - in Java than in .NET.)</p>
Does the CLR automatically detect if the garbage collector should be run in server mode? <p>From a previous question I have seen that the CLR has workstation and server modes for its garbage collector. I know that these can be set from configuration using the <a href="http://msdn.microsoft.com/en-us/library/ms229357.aspx" rel="nofollow"><code>gcServer</code></a> element.</p> <p><strong>If you don't specify this, does the CLR use some magic to decide for you whether the garbage collector should run in server mode?</strong> Something based on CPU count, or memory profiling maybe?</p>
<p>Certainly not. The CLR runs in concurrent mode unless you explicitly tell it to do otherwise.</p>
How can I access the bookmarks toolbar using only shortcuts in Firefox 3 <p>I am not interested in accessing the bookmarks menu or sidebar. The specific goal that I'm trying to accomplish is to be able to easily navigate (using only the keyboard) through the live bookmarks loaded from stack overflow by means of a feed reader and located on my bookmarks toolbar. </p> <p>Notes:</p> <ol> <li><p>I have found an add-on that supposedly does exactly what I need: <a href="https://addons.mozilla.org/en-US/firefox/addon/3647" rel="nofollow">Bookmark Keys</a>, but unfortunately it doesn't work in firefox 3), and is not being currently maintained.</p></li> <li><p>I'm using WinXP at work and Ubuntu 8.04 at home.</p></li> </ol> <p>Edit: changed bookmark keys "not compatible" with firefox 3 to "not working" in firefox 3</p>
<p>Try this: Get the incompatible Bookmarkkey extension file (disable JS then you should copy link location on the download button), open it with your favorite archive manager (holly cow, it's a zip after all:o), then edit the .RDF file, which is vanilla xml (mozilla folks loves file extension renaming!):</p> <p>and change the maxversion to this one:</p> <p><code>&lt; em:maxVersion>3.0+&lt; /em:maxVersion></code> (Space added in tags for web display)</p> <p>then save your xpi archive and install it in your browser.</p> <p>Curse the lazy extension developers and enjoy!</p>
Does using delegates slow down my .NET programs? <p>Does using delegates slow down my programs? </p> <p>I've been avoiding them because I really have no clue if they make my programs any slower. I know if I cause a (catch) exception, that uses quite a bit of CPU power but I don't know about Delegates and Events and what .NET does to them. </p>
<p>Delegates are very, very fast. Not quite as fast as direct method calls, but not far off. The chances of them becoming a bottleneck are miniscule.</p> <p>(Likewise exceptions, when used properly, <a href="http://stackoverflow.com/questions/161942/how-slow-are-net-exceptions">rarely actually cause a performance issue</a>.)</p> <p>Would using delegates make your code simpler, more readable, and more robust? If so, use them. Measure your performance carefully, and keep an eye on it. Move away from readability for the sake of performance only when the data is clear.</p> <p>I'm sure there are some graphs around showing the speed of delegates vs interfaces vs non-virtual method calls etc - I don't know where they are, but you could always run tests yourself if you're really worried.</p>
Is there a free (LGPL, BSD, etc) implementation of XML editor swing component <p>I need a JComponent thad enables editing xml documents so I can embed it in my application.</p> <p>It doesnt need to bee fancy.</p> <p>Plain text editing and highlighting would bee enough.</p> <p>Thank in advance</p>
<p>Maybe this <a href="http://darwin-it.blogspot.com/2008/09/java-swing-xml-editor-and-tester.html" rel="nofollow">Xml Editor</a> would do:</p> <blockquote> <p>I had to enhance and restructure my XML Editor to make it a "plugable" JPanel.</p> </blockquote> <p>Otherwise, you still have the <a href="http://www.xmlmind.com/xmleditor/_distrib/doc/dev/embed1.html" rel="nofollow">SimpleEditor.java</a> which might be as good.</p> <p><img src="http://www.xmlmind.com/xmleditor/_distrib/doc/dev/resources/SimpleEditor.png" alt="alt text" /></p>
Enabling Auditing feature in SQLServer 2005 <p>Did you ever use SQL Server auditing features on a production db?</p> <p>How did that impact on performances, and are there differences you noticed between different versions of SQL Server.</p> <p>Also how we need to enable the audit features.</p>
<p>The C2 audit mode suffers from a variety of problems, and your question touched on only one of them - performance. C2 auditing has a tremendous performance impact, very high.</p> <p>Setting the performance issue aside, it's very difficult to manage. It's not a set-it-and-forget-it configuration switch. You have to spend quite a bit of time doing configuration, setting up the logging to go to files, and then when you're done, someone else can come behind you and get rid of the audit files pretty easily. There's no way to quickly poll all of your servers and make sure C2 auditing is working correctly, or that someone isn't dropping files.</p> <p>SQL Server 2008 makes compliance much easier. I'd recommend taking a look at the <a href="http://www.microsoft.com/sqlserver/2008/en/us/compliance.aspx" rel="nofollow">SQL Server 2008 Compliance portal</a>, which has an excellent whitepaper on how to configure 2008's new compliance features. 2008's new auditor uses the xEvent handling which has dramatically lower performance requirements and it's much easier to manage. You can use 2008's Policy-Based Management to check your servers, ensure you're auditing, and help get auditing configured again when things break.</p> <p>Unfortunately, one weakness is still control of the audit output files - the bad guys can simply delete the files. Another weakness is a lack of reporting - just because you've got gigs of audit data doesn't mean you can do anything with it. You still have to write your own reports in order to analyze the audit data and find out who's doing what. It's not easy - but it's a lot easier and lower-impact than SQL 2005's C2 auditing.</p>
Boost Spirit crash when used in DLLs <p>I am experiencing a crash while using the Boost.Spirit and Boost.Thread libraries in my application. This only happens if I have used the Spirit parser during the lifetime of the process from the main thread.</p> <p>The crash happens at exit and appears to be related to the clean-up of thread specific storage allocated by the Spirit parser. It is probably crashing due to the sequence of which DLLs are unloaded, as the thread specific memory is allocated inside a DLL that has already been unloaded. The Boost.Thread DLL is however not unloaded untill the application itself exits.</p> <p>Is there a way for me to force Spirit to clean out its thread specific storage, e.g. in my dll-main when i get a process-detach notification?</p> <p>Any solutions/hints would be appreciated.</p> <p>PS! My platform and settings:</p> <ul> <li>Visual Studio 2005</li> <li>BOOST_ALL_DYN_LINK</li> <li>BOOST_SPIRIT_THREADSAFE</li> </ul>
<p>Well I found a workaround. </p> <p>Every place I use the boost::spirit::parse call, I basically spawn a workerthread to run it, while the calling thread is blocking on a join call with the workerthread. Not ideal, but it appears to be working without any sideeffects so far.</p> <p>Still interested in any alternatives as my gut feeling is that a seperate thread shouldn't really be needed.</p>
Which Triplestore for rapid semantic web development? <p>Ease of installation/use is the most important factor here - not performance.</p> <p>Small is OK as large datasets are not expected.</p>
<p>I'd also recommend <a href="http://www.openrdf.org" rel="nofollow">sesame</a>, its lightweight, pretty easy to install, and provides good performance for small datasets. Query performance is far better with Sesame 1.2.x than Sesame 2.x because of the addition of context support to the 2.x series.</p> <p>I've tested sesame installation/deployment with tomcat, resin, and jetty, and it worked easily with all of them. I don't recommend the bindings to RDBMS components such as Postgres or MySQL, at least in the 1.x series, performance was not acceptable, even for prototype applications. The in-memory and native implementations provide good query performance and offer simple persistence, though they lack true transactions.</p> <p><a href="http://jena.sourceforge.net/" rel="nofollow">Jena</a> has a decent API, and a lot more support for databases, reasoners, etc, but has a larger footprint, and is a little more cumbersome to use on the whole.</p>
How to choose returned column name in a SELECT FOR XML query? <p>MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:</p> <pre><code>SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') </code></pre> <p>and that returns a nice recordset:</p> <pre><code>XML_F52E2B61-18A1-11d1-B105-00805F49916B ---------------------------------------- &lt;col1&gt;Foo&lt;/col1&gt;&lt;col1&gt;Bar&lt;/col1&gt; </code></pre> <p>only the column name in the returned recordset is rather nasty!</p> <p>The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID). Unfortunately I cannot use * to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...</p> <p>Is there a way to force the column name in the returned recordset to something more sensible?</p>
<p>That should do:</p> <pre><code>select( SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') ) as myName </code></pre> <p>Not pretty but should give the result that you need</p>
Detecting if an Oracle Database is Installed <p>I was wondering if there was a way to tell if an instance of Oracle on a system has a database installed or not?</p> <p>This is for an installation script, and I need to verify that there is an actual database in place before proceeding with the loading of my own tablespace onto that database. Has anyone tackled this problem before?</p> <p>Cheers</p>
<p>Check for the existence of an ORACLE_HOME. It's also reasonable to expect that this environment should be configured for the installation, so testing the environment variables and exiting with a sensible diagnostic (possibly suggesting they run oraenv) is a good first start. If you have an ORACLE_HOME, ORACLE_SID or other appropriate environment variable set up, you can then check for the existence of an oracle home and test for database connectivity and permissions.</p>
Base64ing Unicode characters <p>Can <a href="http://en.wikipedia.org/wiki/Unicode">Unicode</a> characters be encoded and decoded with <a href="http://en.wikipedia.org/wiki/Base64">Base64</a>?</p> <p>I have attempted to encode the string 'الله', but when I decoded it all I got was '????'.</p>
<p>Base64 converts <em>binary</em> to text. If you want to convert text to a base64 format, you'll need to convert the text to binary using some appropriate encoding (e.g. UTF-8, UTF-16) first.</p>
WPF: Can I restyle a checkbox template, so that the checkindicator is a red cross instead <p>I can´t find a way to restyle the IsChecked indicator of a checkbox. As I can see from the checkbox template there´s no possibilities to restyle the indicator, just the "box" of the checkbox. Does anyone knows if it´s possibly to restyle the IsChecked indicator?</p>
<p>You will have to replace the entire CheckBox control template.</p> <p>Start with the ChekcBox ControlTemplate MSDN example at <a href="http://msdn.microsoft.com/en-us/library/ms752319.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms752319.aspx</a></p> <p>In the example you'll see this element:</p> <pre><code>&lt;Path Width="7" Height="7" x:Name="CheckMark" SnapsToDevicePixels="False" Stroke="{StaticResource GlyphBrush}" StrokeThickness="2" Data="M 0 0 L 7 7 M 0 7 L 7 0" /&gt; </code></pre> <p>This is the indicator, in this sample the indicator is already an X, so change Stroke to Red and You're done.</p> <p>To change the shape of the indicator change the Path's Data property. </p>
Which is the best Maven Eclipse plugin? <p>There is two available Eclipse plugins for Maven :</p> <ul> <li><a href="http://www.eclipse.org/proposals/iam/">Eclipse IAM</a> (old name is Q4E)</li> <li><a href="http://m2eclipse.codehaus.org/">m2eclipse</a></li> </ul> <p>m2eclipse seems to be the oldest but the more robust. Is there any key differences between the two ?</p> <p>Which one should be chosen for a project starting today and why ?</p> <p><strong>UPDATE:</strong> m2eclipse is moving to eclipse.org and will be included in the Indigo release train (Eclipse 3.7). See <a href="http://www.sonatype.com/people/2010/12/m2e-at-eclipse-what-will-this-mean-for-you/">m2e at Eclipse: What will this mean for you?</a> and <a href="http://www.eclipse.org/m2e/">m2eclipse is moving to eclipse.org!</a>. The accepted answer is thus even more correct.</p>
<p>I choose <strong>m2eclipse</strong> since it is stable and have all that I need. Especially ability to resolve dependencies inside workspace.</p> <p>I tried the other one some time ago and didn't like it. It was to buggy so I gave up quickly.</p>
From AS2 to AS3 what is the equvalent of _root? <p>I'm trying to learn Actionscript 2 or 3, with AS2 I eventually figured by trial and error that I could get any named instance and modify it using a string with its name using</p> <pre><code>var theinstance = "titletext"; // actually exctracted from an array _root[theinstance].htmlText = "New text with &lt;b&gt;HTML!&lt;/b&gt;"; </code></pre> <p>but when trying to convert the code to AS3 <code>_root</code> doesn't exist anymore. According to the <a href="http://livedocs.adobe.com/flex/3/langref/migration.html" rel="nofollow">migration doc</a> it is somehow replaced by <code>flash.display.DisplayObject.stage</code> but apparently this is not how to do it:</p> <pre><code>flash.display.DisplayObject.stage[theinstance].htmlText = "New text with &lt;b&gt;HTML!&lt;/b&gt;"; </code></pre> <p>and neither is this:</p> <pre><code>flash.display.DisplayObject.stage.getChildByName(theinstance).htmlText = "New text with &lt;b&gt;HTML!&lt;/b&gt;"; </code></pre> <p>How <em>do</em> I get a child by name in actionscript 3?</p>
<p>Just use either "root" (no underscore) or "stage" depending on exactly what you want to do.</p> <p>However - Why not just store a reference to the textField in the array instead of a string?</p>
What do you call a chart that illustrates class hierarchy? <p>So I have a UML type chart that documents the classes and the hierarchy of a development. Just don't know what you'd call it?</p> <p>Any suggestions?</p>
<p><a href="http://www.developer.com/design/article.php/2206791" rel="nofollow">Class diagram</a> is a nice start ;-).</p>
How to determine if a string is a number in C# <p>I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like <code>"2008-11-20T16:33:21Z"</code> to a <code>DateTime</code> value. Numeric values like <code>"42"</code> and <code>"42.42"</code> must be converted to an <code>Int32</code> value and a <code>Double</code> value respectively. </p> <p>What is the best and most efficient approach to detect if a string is an integer or a number? Are <code>Int32.TryParse</code> or <code>Double.TryParse</code> the way to go? </p>
<p><code>Int.TryParse</code> and <code>Double.TryParse</code> have the benefit of actually returning the number.</p> <p>Something like <code>Regex.IsMatch("^\d+$")</code> has the drawback that you still have to parse the string again to get the value out.</p>
Avg on datetime in Access <p>I am porting some queries from Access to T-SQL and those who wrote the queries used the Avg aggregate function on datetime columns. This is not supported in T-SQL and I can understand why - it doesn't make sense. What is getting averaged?</p> <p>So I was about to start reverse engineering what Access does when it aggregates datetime using Avg, but thought I would throw the question out here first.</p>
<p>I'd imagine that Access is averaging the numeric representation of the dates. You could do similar in T-SQL with the following...</p> <pre><code>select AverageDate = cast(avg(cast(MyDateColumn as decimal(20, 10))) as datetime) from MyTable </code></pre>
Why bundle version control plugin with IDE? <p>I was always wandering why it is a big deal having version control support inside an IDE. </p> <p>I always preferred to use commandline/standalone version of version control of choice, and never found IDE integration helpful.</p> <p>I know it can be helpfull sometimes, for example to automatically keep track of renames, but I was bitten by version control plugins couple of times (especialy Clear Case Eclipse plugin) that I'm now finding it counter productive compared to commanline version, where I have better control.</p> <p>What is your opinion?</p>
<p>Integrated Source Control also helps to only keep the important files under Source control. For example, when I add a new File in Visual Studio, the Plugin (visualSVN) will allow me to add it easily without me having to remember to go outside of my IDE and run the command to add it to the repository. On the other hand, it will automatically ignore temporary files, like the obj/ and bin/ Folders.</p> <p>Essentially: Integrated Version Control that actually works is a great way to keep the repository clean and complete.</p>
What is Cassini's (aka VS Dev Server) stack limit? <p>I'm running into a StackOverflowException (please don't ask, it's not my fault) in IIS6/2k3 which has a limit of 256k, but the exception <em>doesn't happen</em> in the VS debugger. </p> <p>As a matter of understanding I'd love to know, but have failed to google what the stack limit of Cassini is...if indeed it has one?</p>
<p>Have you tried stack-overflowing Cassini on purpose to see at what point it crashes? I'd imagine the stack is immense, though I would expect Cassini to replicate IIS as closely as possible. It's surprising that something that runs in VS wouldn't run in IIS, and I'd even consider <a href="http://blogs.msdn.com/astebner/articles/451329.aspx" rel="nofollow">filing a VS bug with Microsoft</a>, since it seems that the whole point of Cassini is to replicate the functionality of IIS and provide an ideal debugging environment, since any web projects you write in VS will inherently be deployed against IIS.</p> <p>I'm not sure if <a href="http://forums.iis.net/t/1153323.aspx" rel="nofollow">this forum thread</a> was posted by you, or if you've seen it, but he seems to have the exact same problem, in case you're still experiencing it.</p>
How would you construct and interact with a grid like a Sudoku board? <p>What do you think is the best way to implement an interactive grid similar to a Sudoku board for a native iPhone application? I did not see an object to fill this need in the SDK.</p> <p>Should I make a custom control for an individual cell, then initialize as many of them as I need in a grid form?</p> <p><img src="http://www.sudoku.4thewww.com/Grids/grid.jpg" alt="Sudoku grid" /></p> <p>Any and all comments are welcome. Thanks!</p>
<p>For such a completely uniform grid, I would create a subclass of <code>UIView</code> and have it determine which row and column the user has touched using a simple calculation:</p> <pre>int touchedRow = 9 * touch.x / [self bounds].width; int touchedCol = 9 * touch.y / [self bounds].width;</pre> <p>I don't see much benefit in creating 81 individual objects in memory, when one object would suffice.</p>
Accessing Environment Variables from Windows Services <p>I am attempting to write a Windows Service in C#. I need to find the path to a certain file, which is stored in an environment variable. In a regular C# console application, I can achieve that with the following line:</p> <pre><code>string t = System.Environment.GetEnvironmentVariable("TIP_HOME"); </code></pre> <p>If I write that to the console I see that it was successful.</p> <p>Now, if I try that same code in a Windows Service, the string <code>t</code> is empty.</p> <p>Any idea why?</p>
<p>I've no idea if this is useful, but I've found that for every service, there is an option to add environment variables directly to a service.</p> <p>It is done via the registry.</p> <p>Say the key to your service is ...</p> <p>HKLM\SYSTEM\CurrentControlSet\Services\YourService</p> <p>Create a REG_MULTI_SZ called Environment.</p> <p>Now you can add entries like ...</p> <pre><code>Var1=Value1 Var2=Value2 </code></pre> <p>and these will be available to the service code.</p> <p>If you are using the Windows Resource ToolKit to install scripts as a service (instsrv.exe and srvany.exe), then, again, you have the option of setting Environment variables for the service, but most likely it is the wrong one as these would be for srvany.exe.</p> <p>Instead, you use the key ...</p> <p>HKLM\SYSTEM\CurrentControlSet\Services\YourService\Parameters</p> <p>and create a REG_MULTI_SZ called AppEnvironment</p> <p>Set the entries in the same way.</p> <p>And now your script service has it's own environment variables.</p> <p>I'm using these techniques with PHP+WinCache to allow me to set an APP_POOL_ID unique to each service which allows WinCache to share a central cache (based upon APP_POOL_ID) for all "threads" (using WShell to launch non-blocking child "threads" and still share the same WinCache as the launcher, allowing simplistic, inter-process communication).</p> <p>Anyway. I hope this helps somewhat.</p> <p>I think, in the main, you aren't adding unnecessary env_vars to the global environment. You can keep them targetted and unique when you have more than 1.</p> <p>Regards,</p> <p>Richard.</p>
Hibernate Annotation Placement Question <p>I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....</p> <pre><code>@Entity @Table(name="widget") public class Widget { private Integer id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.</p> <p>However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --</p> <pre><code>@Entity @Table(name="widget") public class Widget { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>I've seen examples of both ways. However, when I run this second example I get the following...</p> <pre> java.lang.NullPointerException at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25) at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1) at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source) at java.lang.ThreadLocal.get(Unknown Source) at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33) at com.widget.db.dao.AbstractDao.(AbstractDao.java:12) at com.widget.db.dao.WidgetDao.(WidgetDao.java:9) at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) ... </pre> <p>Here's the skeleton of <code>HibernateSessionFactory</code> (line 25 is marked) ....</p> <pre><code>protected Session initialValue() { SessionFactory sessionFactory = null; try { Configuration cfg = new AnnotationConfiguration().configure(); String url = System.getProperty("jdbc.url"); if (url != null) { cfg.setProperty("hibernate.connection.url", url); } sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { } Session session = sessionFactory.openSession(); // LINE 25 return session; } </code></pre> <p>Anyone have an idea what's going on here?</p>
<p>From a performance and design perspective, using annotations on getters is a better idea than member variables, because the getter setters are called using reflection if placed on the field, than a method. Also if you plan to use validation and other features of hibernate, you'll have all the annotations at one place, rather than scattering them all over the place.</p> <p>My recommendation go with methods not member variables.</p> <p>From the documentation</p> <blockquote> <p>Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.</p> </blockquote>
What is the optimal productivity stack for developers? <p>What is the optimal <a href="http://www.blog.stackingit.com/2008/11/productivity-stack-is-not-about.html" rel="nofollow">productivity stack</a> for developers?</p> <p>When deciding what to include in your personal productivity stack, what criteria do you use?</p>
<p>I haven't ever thought about this so much formally. Mine includes:</p> <ul> <li>Fast typing.</li> <li>IDLE for Python. DrScheme for scheme. </li> <li>For other code: TextPad on Windows, gedit on linux. I don't like vi or emacs. I just like an editor that I can use shift to highlight things. </li> <li>Command line on linux.</li> </ul> <p>Granted, I haven't worked on any large projects recently, so I haven't had the need of anything more powerful yet.</p>
Windows 2008 concurrent TCPIP connections <p>In Windows XP, Microsoft took the decision to limit the number of half open connections in later service packs. Patching tcpip.sys was rumoured to fix this. Does such a limit exist in Windows 2008, and if so, is it configurable?</p>
<p>When Vista SP1 shipped, there was some article about the alignment with Windows Server 2008, and their example was the networking subsystem, and they said something like that it is designed to handle thousands of connections. So I guess, no, they won't limit it to 10 :)</p> <p>I think it was <a href="http://technet.microsoft.com/en-us/library/cc709618.aspx" rel="nofollow">this article</a> (scroll to bottom), though I think I remember it being longer.</p>
Installing Capicom without SelfReg: Wix Custom Actions Not Found (Err 2721) <p>After following the advice in <a href="http://stackoverflow.com/questions/302560/wix-custom-actions-with-wixuiminimal">this question</a> successfully, I added a couple additional lines of code for another custom action. This one is intended to call regsvr32 on the copy of capicom which I've tried to put in the user's system folder. However, I'm getting error 2721, which seems to be a custom action not found error, from what I've seen. Any suggestions? I'm trying to maintain consistency with previous iterations of my installer by calling regsvr, rather than just adding the registry entries during install, which could be a good idea instead. :::shrug:::</p> <pre><code>&lt;Directory Id="SystemFolder" Name="Sys"&gt; ... &lt;component ...&gt; ... &lt;File Id="CapiCom.Dll" LongName="CapiCom.Dll" Name="CAPICOM.DLL" Source=... /&gt; &lt;/component&gt; &lt;/directory&gt; ... &lt;CustomAction Id="REGCAPICOM" ExeCommand='regsvr32.exe "[SystemFolder]capicom.dll"' Return = "ignore" Execute="deferred" /&gt; ... &lt;InstallExecuteSequence&gt; ... &lt;Custom Action="REGCAPICOM" After="InstallFiles" /&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>Edit: Yes, using regsvr32 as an installer is ugly. But when I downloaded the Capicom SDK, that is what MS said to do in order to install it. Searching around has found many people saying that this is a stupid way to do it...but it's also mechanism MS provided. I'll listen to suggestions for a better way. I don't consider it a big deal if Capicom being left behind when my application is uninstalled, considering that it's a standard windows component.</p> <p>Edit: Hmmm. Apparently, one of the things running selfreg on the dll does is to create a random seed to add to the registry. Not sure what mechanism it uses to generate this seed but I suspect it would be considered in poor taste to just generate one myself, especially if I gave all the users the same seed. Not sure.... Apparently if I skip this Capicom does it on its own, so I'm fine.</p>
<p>The Right way:</p> <ul> <li><p>c:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Tools\Deployment\regcap.exe" /O capicom.reg capicom.dll</p></li> <li><p>Run program from Adam Tengen's <a href="http://stackoverflow.com/questions/269423/how-to-generate-wix-xml-from-a-reg-file">post here</a>.</p></li> </ul> <p>Note that Heat (and Tallow, IIRC) do not, as of this posting, work properly on Capicom.</p> <p>The Wrong Way:</p> <pre><code>&lt;CustomAction Id="RegisterCapicom" Directory="SystemFolder" ExeCommand="regsvr32.exe /s &amp;quot;[SystemFolder]Capicom.dll&amp;quot;" Return="check" Execute="deferred" /&gt; ... &lt;InstallExecuteSequence&gt; &lt;Custom Action="RegisterCapicom" After="InstallFiles" /&gt; &lt;/InstallExecuteSequence&gt; </code></pre>
ASP.NET Membership: Login Controls Source Code <p>Is the source code for the common login controls available?</p> <p>Those are the controls which are available under Login section in Toolbox: </p> <ul> <li>Login, </li> <li>LoginView, </li> <li>PasswordRecovery,</li> <li>LoginStatus, </li> <li>LoginName,</li> <li>CreateUserWizard, </li> <li>ChangePassword</li> </ul> <p>Eventually could you point me to a good source of custom implementation of functionality that those controls provide, or some guidance on implementing this functionality without using the mentioned controls.</p> <p>I am using Visual Studio 2005 (.net2)</p> <p>I will be using SQLMembershipProvider as the MembershipProvider but that probably should make no difference.</p>
<p>"the entire framework is available" is not true. :)</p>
Python decorator makes function forget that it belongs to a class <p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
<p>Claudiu's answer is correct, but you can also cheat by getting the class name off of the <code>self</code> argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example:</p> <pre><code>from functools import wraps # use this to preserve function signatures and docstrings def logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_logging class C(object): @logger def f(self): pass C().f() </code></pre> <p>As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say</p> <pre><code>class B(C): pass b = B() b.f() </code></pre> <p>and get the message <code>Entering B.f</code> where you actually want to get the message <code>Entering C.f</code> since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.</p>
How to boost productivity in my Flex/Java stack? <p>I am embarking on a new RIA project with Java on the backend. I'm the only developer, and the app is a line-of-business application. My current stack looks like this:</p> <p>MySQL || Spring(JdbcTemplate for data access) || BlazeDS (remoting) || Flex(Cairngorm)</p> <p>My question is: what changes can I make to improve productivity? Manually coding SQL, server-side entity objects, client-side value objects and all the Cairngorm stuff is obviously a drag, but I'm not sure what higher-level frameworks to introduce.</p> <p>What Flex/Java stack has served you well? </p>
<p><em>Manually coding SQL</em></p> <p><a href="http://www.hibernate.org/" rel="nofollow">Hibernate</a> is an option to cut this out.</p> <p>One thing that may be of interest is Grails with the available Flex Plugin. It's built on Spring, Hibernate and BlazeDS, so it's all there for you. It was unbelieveably easy to get it remoting stored objects and responding to AMF calls. I was using this and then moved over to a RESTful E4X implementation as I found it a lot easier to debug and tweak as I could inspect the server output in a browser and have tighter control over exactly what I returned to my Flex app (lazy loading problems in collections using BlazeDS were a headache at times).</p> <p>Here is a quick tutorial showing how easy the whole Grails + Flex Plugin stack is: <a href="http://marceloverdijk.blogspot.com/2008/01/blazeds-test-drive-sample-in-grails.html" rel="nofollow">BlazeDS in Grails</a></p>
How do I randomly select an item from a list using Python? <p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
<p>Use <a href="https://docs.python.org/2/library/random.html#random.choice"><code>random.choice</code></a>:</p> <pre><code>import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) </code></pre>
Accessing parent elements in an object model efficiently <p>I have a following object model:</p> <pre> - Book -- Chapter 1 --- Page 1 ---- Image 1 ---- Image 2 ---- Text 1 --- Page 2 ... </pre> <p>Resources are way down at the page level. But, I need to know the full path to resources, from the resources' point of view. </p> <p>One way, is to have resources be aware of their parents. </p> <p>So my Image object could have a "parentPage" property, which in turn could have a "parentChapter" property. This way, I could access the complete path via currentImage.parentPage.parentChapter. Is there a better way?</p> <p>A couple of words on why I'd need to know the full path from a resource's point of view. I have an object model that gets walked and rendered on screen. The renderer descends from chapter level all the way down into the element/resource level (this is where the rendering occurs). However to display the resources, I need to know where they live (ie the actual path on disk) and this information is typically specified at the Chapter level.</p> <p>Thanks!</p> <p>-- Edit -- Just to clarify, is this parent.parent approach the best? It forces child objects to know about the parents, which makes me uncomfortable. Coupling?</p>
<p>I'd suggest a tree structure, whereas each of your classes inherits from a tree node.</p> <p>Example in c#:</p> <pre><code>class TreeNode { public TreeNode Parent { get; set; } public List&lt;TreeNode&gt; Children { get; set; } } class Book : TreeNode { ... book attributes ... } ... other classes ... </code></pre> <p>Actually, if you're worried about coupling the thing to ask yourself is it good coupling or bad coupling? If the coupling actually adds value and there is a logical reason to do it, do it. If not, it's wasted code. If you're using a language that supports generics, you can decouple it a little farther:</p> <pre><code>class TreeNode&lt;TParent, TChild&gt; { public TParent Parent { get; set; } public List&lt;TChild&gt; Children { get; set; } } class Book : TreeNode&lt;object, Chapter&gt; { } class Chapter : TreeNode&lt;Book, Page&gt; { } class Page : TreeNode&lt;Chapter, object&gt; { } </code></pre> <p>Hope that helps!</p>
How do I create a web application where I do not have access to the data? <p><em>Premise</em>: The requirements for an upcoming project include the fact that no one except for authorized users have access to certain data. This is usually fine, but this circumstance is not usual. The requirements state that there be no way for even the programmer or any other IT employee be able to access this information. (They want me to store it without being able to see it, ever.)</p> <p>In all of the scenarios I've come up with, I can always find a way to access the data. Let me describe some of them.</p> <p><strong>Scenario I:</strong> Restrict the table on the live database so that only the SQL Admin can access it directly.<br> <strong>Hack 1:</strong> I rollout a change that sends the data to a different table for later viewing. Also, the SQL Admin can see the data, which breaks the requirement.</p> <p><strong>Scenario II:</strong> Encrypt the data so that it requires a password to decrypt. This password would be known by the users only. It would be required each time a new record is created as well as each time the data from an old record was retrieved. The encryption/decryption would happen in JavaScript so that the password would never be sent to the server, where it could be logged or sniffed.<br> <strong>Hack II:</strong> Rollout a change that logs keypresses in javascript and posts them back to the server so that I can retrieve the password. Or, rollout a change that simply stores the unecrypted data in a hidden field that can be posted to the server for later viewing.</p> <p><strong>Scenario III:</strong> Do the same as Scenario II, except that the encryption/decryption happens on a website that we do not control. This magic website would allow a user to input a password and the encrypted or plain-text data, then use javascript to decrypt or encrypt that data. Then, the user could just copy the encrypted text and put the in the field for new records. They would also have to use this site to see the plain-text for old records.<br> <strong>Hack III:</strong> Besides installing a full-fledged key logger on their system, I don't know how to break this one.</p> <p>So, Scenario III looks promising, but it's cumbersome for the users. Are there any other possibilities that I may be overlooking?</p>
<p>If you can have javascript on the page, then I don't think there's anything you can do. If you can see it in a browser, then that means it's in the DOM, which means you can write a script to get it and send it to you after it has been decrypted.</p> <p>Aren't these problems usually solved via controls:</p> <ol> <li>All programmers need a certain level of clearance and background checks</li> <li>They are trained to understand that rolling out code to access the data is a fireable or worse offense</li> <li>Every change in certain areas needs some kind of signoff</li> </ol> <p>For example -- no JavaScript on page without signoff.</p> <p>If you are allowed to add any code you want, then there's always a way, IMO.</p>
Create a makefile for multiple OSes, this make (ext?) doesn't work? <p>I have a working makefile that builds with mingw32. Now i renamed that makefile to Makefile.w32 (source -> <a href="http://pastie.org/319964" rel="nofollow">http://pastie.org/319964</a>)</p> <p>Now i have a Makefile with the following. The problem is, it does not build my source</p> <pre><code>all: make mingw32 clean: @echo "causes an infinite loop -&gt; make mingw32 clean" mingw32: @echo "yeahhhhhhhhh" make Makefile.w32 mingw32-clean: @echo "mingw clean" make Makefile.w32 clean </code></pre> <p>result:</p> <pre><code>&gt; "make" make mingw32 make[1]: Entering directory `/c/nightly/test' yeahhhhhhhhh make Makefile.w32 make[2]: Entering directory `/c/nightly/test' make[2]: Nothing to be done for `Makefile.w32'. make[2]: Leaving directory `/c/nightly/test' make[1]: Leaving directory `/c/nightly/test' </code></pre> <p>It seems to me it doesn't like Makefile.w32 extension. I dont understand why it isn't building. It;s obviously getting to my "make Makefile.w32" line.</p>
<p>"make Makefile.w32" is looking for a <strong>target</strong> named Makefile.w32, not a make file by that name. To run make and tell it to read the make file "Makefile.w32", use the -f switch:</p> <pre><code>make -f Makefile.w32 </code></pre> <p><strong>Edit</strong>: Incidentally, why do you launch a separate instance of make in the "all" target, if all you want is for "all" to depend on the "mingw32" target in the same make file? It'd be better, IMHO, to declare it as a dependent target instead:</p> <pre><code>all: mingw32 </code></pre> <p>Likewise with "clean" and "mingw32-clean":</p> <pre><code>clean: mingw32-clean </code></pre>
Search for a regexp in a java arraylist <pre><code>ArrayList &lt;String&gt; list = new ArrayList(); list.add("behold"); list.add("bend"); list.add("bet"); list.add("bear"); list.add("beat"); list.add("become"); list.add("begin"); </code></pre> <p>There is a way to search for the regexp bea.* and get the indexes like in ArrayList.indexOf ?</p> <p>EDIT: returning the items is fine but I need something with more performance than a Linear search</p>
<p>Herms got the basics right. If you want the Strings and not the indexes then you can improve by using the Java 5 foreach loop:</p> <pre><code>import java.util.regex.Pattern; import java.util.ListIterator; import java.util.ArrayList; /** * Finds the index of all entries in the list that matches the regex * @param list The list of strings to check * @param regex The regular expression to use * @return list containing the indexes of all matching entries */ List&lt;String&gt; getMatchingStrings(List&lt;String&gt; list, String regex) { ArrayList&lt;String&gt; matches = new ArrayList&lt;String&gt;(); Pattern p = Pattern.compile(regex); for (String s:list) { if (p.matcher(s).matches()) { matches.add(s); } } return matches } </code></pre>
ASP.net 2.0 Gridview with Expanding Panel Rows -- How to build Panel "on the fly" <p>I'm currently building a Gridview that has expandable rows. Each row contains a dynamically created Panel of Form elements. Right now, I have a javascript function that expands (or in my case, makes visible) the panel when an Image is clicked on the Gridview row.</p> <p>My question is... is there a more efficient way of doing this. Instead of pulling all my data to begin with and building each new row as I Databind, is there a way to simple create the row with the Panel full of textboxes and dropdownlists on the fly when the user clicks the Expand button?"</p> <p>I'd like to limit the server calls by doing it that way instead of how I'm currently doing it, looping through every row and creating a new panel with form elements and inserting that into a row that is hidden.</p>
<p>Actually, it isn't performing badly since my original SQL query can populate every single row and I have enabled paging on the Gridview. I'm just wondering if they can be built on the fly using PageMethods or some sort of JSON/AJAX solution. I haven't seen anything, but... worth a try in searching for it.</p>
Vector Shape on Stage Appears Over Dynamic Textfield <p>The subject pretty much explains it all. I start on frame one of a MovieClip with just a Bitmap covering the whole stage.</p> <p>Then when a user clicks a button, it goes to frame two and a vector shape is on the stage covering part of the image. At the same time, through code, I place an input Textfield on the stage.</p> <p>Problem is, the dynamically created Textfield is appearing UNDER the vector shape (which was drawn on the stage)! This seems to be a problem that is new to ActionScript 3, as I did not have this problem with Flash CS3 and ActionScript 2.</p> <p>I've tried putting the Textfield on different layers, but to no avail. How do I get the Textfield to appear over the vector shape?</p>
<p>Put the vector shape inside a movieclip. Then call:</p> <pre><code>setChildIndex(myTextField, numChildren - 1); </code></pre>
makefile calling makefile error <p>I have a working make, I have platform code and like several makes for each os in the folder. Right now I have one makefile which works. I renamed it to Makefile.ws and wrote this in Makefile</p> <pre><code>all: make -f Makefile.w32 clean: make -f Makefile.w32 clean </code></pre> <p>I ran it and got this error</p> <pre><code>&gt; "make" make -f Makefile.w32 make[1]: Entering directory `/c/nightly/test' make -f Makefile.w32 make[3]: Makefile.w32: No such file or directory make[3]: *** No rule to make target `Makefile.w32'. Stop. make[2]: *** [all] Error 2 make[1]: *** [build] Error 2 make[1]: Leaving directory `/c/nightly/test' "make": *** [all] Error 2 </code></pre> <p>Oddly enough the clean works perfectly. Then I decided to write "make -f Makefile.w32 mingw32" and that did not work correctly. In fact it made a folder called mingw32 which I thought was very strange.</p> <p>As for the mingw32 rule I just copy build which I suspect is the main/normal rule that is used to build</p> <pre><code>$(BUILD): @[ -d $@ ] || mkdir -p $@ @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile mingw32: @[ -d $@ ] || mkdir -p $@ @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile </code></pre> <p>full .w32 source is here <a href="http://pastie.org/320035" rel="nofollow">http://pastie.org/320035</a></p>
<p>First, what make are you running? Cygwin or MinGW, or something else? </p> <pre><code>make -f Makefile.w32 make[1]: Entering directory `/c/nightly/test' make -f Makefile.w32 make[3]: Makefile.w32: No such file or directory </code></pre> <p>"Entering directory" is a hint. Why is it entering /c/nightly/test? Is there a Makefile.w32 there?</p> <p>As to creating the directory "mingw32", the rule</p> <pre><code>mingw32: @[ -d $@ ] || mkdir -p $@ ... </code></pre> <p>does exactly that. If "mingw32" does not exist, it creates it.</p> <p>It would be easier to help you if you had a shorter example and clearly explain what you want to accomplish and what you expect to happen.</p>
What is the purpose of allocating pages in the pagefile with CreateFileMapping? <p>The function <a href="http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx" rel="nofollow">CreateFileMapping</a> can be used to allocate space in the pagefile (if the first argument is <code>INVALID_HANDLE_VALUE</code>). The allocated space can later be memory mapped into the process virtual address space.</p> <p>Why would I want to do this instead of using just <a href="http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx" rel="nofollow">VirtualAlloc</a>?</p> <p>It seems that both functions do almost the same thing. Memory allocated by VirtualAlloc may at some point be pushed out to the pagefile. Why should I need an API that specifically requests that my pages be allocated there in the first instance? Why should I care where my private pages live?</p> <p>Is it just a hint to the OS about my expected memory usage patterns? (Ie, the former is a hint to swap out those pages more aggressively.)</p> <p>Or is it simply a convenience method when working with very large datasets on 32-bit processes? (Ie, I can use CreateFileMapping to make >4Gb allocations, then memory map smaller chunks of the space as needed. Using the pagefile saves me the work of manually managing my own set of files to "swap" to.)</p> <p>PS. This question is sparked by an article I read recently: <a href="http://blogs.technet.com/markrussinovich/archive/2008/11/17/3155406.aspx" rel="nofollow">http://blogs.technet.com/markrussinovich/archive/2008/11/17/3155406.aspx</a></p>
<p>From the CreateFileMappingFunction:</p> <pre><code>A single file mapping object can be shared by multiple processes. </code></pre> <p>Can the Virtual memory be shared across multiple processes?</p>
How do you spawn a child process in Ruby? <p>I want to offload a block of code in my main process to child process to make it run concurrently. I also want to have the PID of the spawned child process so I can monitor and kill it if necessary.</p>
<p>In addition to Chris' great answer, remember to call <code>Process.wait</code> from your master in order to reap your child process, else you'll leave zombies behind.</p> <p>Example as requested in comments:</p> <pre><code>pid = Process.fork do puts "child, pid #{Process.pid} sleeping..." sleep 5 puts "child exiting" end puts "parent, pid #{Process.pid}, waiting on child pid #{pid}" Process.wait puts "parent exiting" </code></pre>
How to I export a system scope environment variable in bash <p>I need to set a system environment variable from a bash script that would be available outside of the current scope. So you would normally export environment variables like this: </p> <blockquote> <p>export MY_VAR=/opt/my_var</p> </blockquote> <p>But I need the environment variable to be available at a system level though. Is this possible?</p>
<p>Not really - once you're running in a subprocess you can't affect your parent.</p> <p>There two possibilities:</p> <p>1) Source the script rather than run it (see <a href="http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins">source .</a>):</p> <pre> source {script} </pre> <p>2) Have the script output the export commands, and eval that:</p> <pre> eval `bash {script}` OR: eval "$(bash script.sh)" </pre> <p>EDIT: Corrected the second option to be eval rather than source. Opps.</p>
maintaining ids in database that match client software enumerations <p>Lets say I have a table in a sql server 2000 database called TransactionType:</p> <pre><code>CREATE TABLE [dbo].[TransactionType]( [ID] [int] NOT NULL, [Description] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_TransactionType] PRIMARY KEY CLUSTERED ( [ID] ASC ) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>I then have a transaction table with a column called TransactionTypeID, keyed off of the ID column of the TransactionType table.</p> <p>My .net client application is responsible for inserting transaction records and specifying the transaction type. My first thought was to have an enumeration defined, casting the enumeration to an integer and passing that value to the database. The issue is that potentially, someone could go into the database and change one of the IDs in the TransactionType table, making the IDs in the database out of synch with the IDs in the client applications enumeration.</p> <p>So, after my long winded eplanation, my question is, are there design patterns/techniques others use to combat this issue?</p>
<p>You might consider using a coding system that's loosely tied (not enforced) to the child table. Lets say it's a color, your child table can look like the following.</p> <pre><code>ID | Name ------------ GRN | Green PURP| Purple YELL| Yellow RED | Red </code></pre> <p>Now you have an ID that if you displayed without a join, is very usable to a human, and if you need a more accurate/detailed "Name" value, you can join or retrieve it. So obviously when you view the parent entry (let's say it's fruit), you don't need to perform the join. Also, there's never a good reason to change the ID</p> <pre><code>ID | Name | Color ----------------- 1 | Banana | YELL 2 | Apple | RED 3 | Cherry | RED </code></pre> <p>Keep in mind this system should not be used if you plan on adding lots of child types, but if you're only going to have a dozen, it can be a nice shortcut. It's also not a good idea if you plan on having lots of "fruit" because a CHAR/VARCHAR is not an efficient way to WHERE your data. But for 99% of the databases out there, this method will be fine.</p>
PHP function which does syntax color parsing for multiple languages? <p>I'm doing a PHP site which displays code examples in various languages (C#, PHP, Perl, Ruby, etc.). Are there any PHP functions which add syntax coloring for these and other languages? </p> <p>If not, I would at least like to find that one built-in PHP function which does syntax coloring for PHP code, can't find it anymore. Thanks.</p>
<p>Why not do the syntax coloration in the client side?</p> <p>Use <a href="http://code.google.com/p/google-code-prettify/" rel="nofollow">prettify.js</a>, its really versatile, Google Code and StackOverflow use it!</p> <p>Check the <a href="http://google-code-prettify.googlecode.com/svn/trunk/tests/prettify_test.html" rel="nofollow">test page</a> for the supported languages.</p>
How do I imitate the ASP.NET AjaxOptions delegate functions? <p>When using the <code>Ajax.BeginForm()</code> helper in <code>ASP.Net MVC</code>, I can pass options with names of different functions, for example one to run <code>OnBegin</code>, one for <code>OnSuccess</code> etc. How do these work "under the hood"?</p> <p>The reason I'm asking is that I'm extending this to provide a <code>JQuery</code> based alternative, and I need to figure out how to get from having the method names specified in a <code>JSON</code> string to actually calling them.</p> <p>The <code>AjaxOptions</code> class has a method for serializing, in which it wraps the method name in the following way (in this example, the <code>AjaxOptions</code> <code>OnSuccess</code> property is set to <code>mySuccessFunction(p)</code>:</p> <pre>onSuccess: Function.createDelegate(this, mySuccessFunction(p))</pre> <p>I have produced my own <code>JQueryAjaxOptions</code> class, which serializes in the same way (but with some extra options available). So asically, what I have available in my method for posting the form is the above property as part of a json object, and I need to be able to call the function.</p> <p>How can I accomplish this?</p>
<p>I found the answer to my problem:</p> <p>What it really boiled down to, was executing a line of code contained in a string variable. This can easily be done using the 'eval(x)' syntax. The following example works for the onSuccess property:</p> <pre>eval(settings.onSuccess)</pre> <p>Sometimes you just need to think one more step backwards to realize what you're trying to do, and how easy it is =)</p>
How can I reformat form input before POST using Javascript (or Rails)? <p>I have a field in my form labeled "Name" that will contain both the First &amp; Last name.</p> <p>Our existing dynamic server (to which the form is being POSTed to), expects two separate fields (first name, last name). </p> <p>Can I use Javascript to split the user input into two separate variables before the form is posted to the server? How would I do this?</p>
<p>You should not rely on client side parsing whenever possible. If you are sending this form to an app you can't modify, use the Javascript method mentioned above because you have no control over it (but then why not just have a first and last name field). But if you are controller the backend app, perform all your massaging and data validation there.</p> <p>Javascript should only be used to enhance the UI experience, not perform import data manipulation, it can be both a security hole and a point of failure if use Javascript for these important tasks.</p> <p>Also, when manipulating names, keep in mind all the different kinds of formats you will get, such as:</p> <pre><code>John Smith Jr Dr John Smith John Smith Esq. John Smith IV John A Smith </code></pre> <p>So be careful, massaging names is very messy business and the public will enter whatever they want, at the very least, add a small label and ask them to only enter "first and last name" and pray for the best.</p>
How do I improve performance of DataSet.ReadXml if I'm using a schema? <p>I'm have a ADO DataSet that I'm loading from its XML file via ReadXml. The data and the schema are in separate files.</p> <p>Right now, it takes close to 13 seconds to load this DataSet. I can cut this to 700 milliseconds if I don't read the DataSet's schema and just let ReadXml infer the schema, but then the resulting DataSet doesn't contain any constraints.</p> <p>I've tried doing this:</p> <pre><code>Console.WriteLine("Reading dataset with external schema."); ds.ReadXmlSchema(xsdPath); Console.WriteLine("Reading the schema took {0} milliseconds.", sw.ElapsedMilliseconds); foreach (DataTable dt in ds.Tables) { dt.BeginLoadData(); } ds.ReadXml(xmlPath); Console.WriteLine("ReadXml completed after {0} milliseconds.", sw.ElapsedMilliseconds); foreach (DataTable dt in ds.Tables) { dt.EndLoadData(); } Console.WriteLine("Process complete at {0} milliseconds.", sw.ElapsedMilliseconds); </code></pre> <p>When I do this, reading the schema takes 27ms, and reading the DataSet takes 12000+ milliseconds. And that's the time reported <em>before</em> I call EndLoadData on all the DataTables.</p> <p>This is not an enormous amount of data - it's about 1.5mb, there are no nested relations, and all of the tables contain two or three columns of 6-30 characters. The only thing I can figure that's different if I read the schema up front is that the schema includes all of the unique constraints. But BeginLoadData is supposed to turn constraints off (as well as change notification, etc.). So that shouldn't apply here. (And yes, I've tried just setting EnforceConstraints to false.)</p> <p>I've read many reports of people improving the load time of DataSets by reading the schema first instead of having the object infer the schema. In my case, inferring the schema makes for a process that's about 20 times faster than having the schema provided explicitly.</p> <p>This is making me a little crazy. This DataSet's schema is generated off of metainformation, and I'm tempted to write a method that creates it programatically and just deseralizes it with an XmlReader. But I'd much prefer not to.</p> <p>What am I missing? What else can I do to improve the speed here?</p>
<p>I will try to give you a performance comparison between storing data in text plain files and xml files.</p> <p>The first function creates two files: one file with 1000000 records in plain text and one file with 1000000 (same data) records in xml. First you have to notice the difference in file size: ~64MB(plain text) vs ~102MB (xml file).</p> <pre><code>void create_files() { //create text file with data StreamWriter sr = new StreamWriter("plain_text.txt"); for(int i=0;i&lt;1000000;i++) { sr.WriteLine(i.ToString() + "&lt;SEP&gt;" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbb" + i.ToString()); } sr.Flush(); sr.Close(); //create xml file with data DataSet ds = new DataSet("DS1"); DataTable dt = new DataTable("T1"); DataColumn c1 = new DataColumn("c1", typeof(int)); DataColumn c2 = new DataColumn("c2", typeof(string)); dt.Columns.Add(c1); dt.Columns.Add(c2); ds.Tables.Add(dt); DataRow dr; for(int j=0; j&lt; 1000000; j++) { dr = dt.NewRow(); dr[0]=j; dr[1] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbb" + j.ToString(); dt.Rows.Add(dr); } ds.WriteXml("xml_text.xml"); } </code></pre> <p>The second function reads these two files: first it reads the plain text into a dictionary (just to simulate the real world of using it) and after that it reads the XML file. Both steps are measured in milliseconds (and results are written to console):</p> <p><em>Start read Text file into memory<br> Text file loaded into memory in 7628 milliseconds<br> Start read XML file into memory<br> XML file loaded into memory in 21018 milliseconds</em><br></p> <pre><code>void read_files() { //timers Stopwatch stw = new Stopwatch(); long milliseconds; //read text file in a dictionary Debug.WriteLine("Start read Text file into memory"); stw.Start(); milliseconds = 0; StreamReader sr = new StreamReader("plain_text.txt"); Dictionary&lt;int, string&gt; dict = new Dictionary&lt;int, string&gt;(1000000); string line; string[] sep = new string[]{"&lt;SEP&gt;"}; string [] arValues; while (sr.EndOfStream!=true) { line = sr.ReadLine(); arValues = line.Split(sep,StringSplitOptions.None); dict.Add(Convert.ToInt32(arValues[0]),arValues[1]); } stw.Stop(); milliseconds = stw.ElapsedMilliseconds; Debug.WriteLine("Text file loaded into memory in " + milliseconds.ToString() + " milliseconds" ); //create xml structure DataSet ds = new DataSet("DS1"); DataTable dt = new DataTable("T1"); DataColumn c1 = new DataColumn("c1", typeof(int)); DataColumn c2 = new DataColumn("c2", typeof(string)); dt.Columns.Add(c1); dt.Columns.Add(c2); ds.Tables.Add(dt); //read xml file Debug.WriteLine("Start read XML file into memory"); stw.Restart(); milliseconds = 0; ds.ReadXml("xml_text.xml"); stw.Stop(); milliseconds = stw.ElapsedMilliseconds; Debug.WriteLine("XML file loaded into memory in " + milliseconds.ToString() + " milliseconds"); } </code></pre> <p>Conclusion: the XML file size is almost double than the text file size and is loaded three times slower than the text file.</p> <p>XML handling is more convenient (because of the abstraction level) than plain text but it is more CPU/disk consuming.</p> <p>So, if you have small files and is acceptable from the performance point of view, XML data Sets are more than ok. But, if you need performance, I don't know if XML Data set ( with any kind of method available) is faster that plain text files. And basically, it start from the very first reason: XML file is bigger because it has more tags.</p>
Emulate IDispatchEx in C# <p>C# 3.0 Extension methods add extensions to the base Type making calling that method on all <em>instances</em> of that Type legal.</p> <p>Now, JavaScript I know implements IDispatchEx through which it's possible to add methods to a specific instance.</p> <p>So how do I add a set of methods to an 'instance' of a C# class? I know this is a Dynamic vs. Static Languages holy war territory. :) Let me clarify my intention is NOT that.</p> <p>I just want to be able to add a set of events to an interface depending on the class implementing that interface.</p> <p>I was able to do that using Generics </p> <pre><code>inteface ISample&lt;T&gt; { T SupportedEvents; } class Sample : ISample&lt;UIWidgetEvent&gt; { } class Sample2 : ISample&lt;NonVisualUIWidget&gt; { } class UIWidgetEvent { public EventHandler Clicked; } class NonVisualUIWidget {public EventHandler Expired;} class TestSample { public void Test() { new Sample().SupportedEvents.Clicked += ... new Sample2().SupportedEvents.Expired += ... } } </code></pre> <p>Then I didn't like <code>SupportedEvents</code> I want to be able to say </p> <pre><code>new Sample().Clicked +=... </code></pre> <p>Then I thought JavaScript (I know <code>C#</code> is not <code>JS</code> :))... AND <code>IDispatchEx</code>, <code>IL Weaving</code>, <code>Reflection.Emit</code> etc. etc. and thought may be there's a way to do this... [Design time support would be nice but I can live without]</p> <p>Yes, I probably could do this "instance augmentation" with a Visitor pattern. [Not sure if I could get the syntatic sugar though]</p> <p>Comments?</p>
<p>Well, you could create a DynamicMethod instance for your "new" methods, but statically attaching them to an existing instance at runtime wouldn't work due to the fact it plain wouldn't compile. </p> <p>You <em>might</em> (I haven't tried this) be able to emit the opcodes into an in-memory assembly, but that's about as far away from being "Syntactically sweet" as you can get (would involve a lot of reflection and InvokeMember calls, I would think)</p> <p>It also might be worth looking into Extension Methods - although I've never tried attaching events or event-like methods via extension methods...and they are 3.5 only, so that may limit you.</p> <p>The nicest looking, "pure C#" implementation is probably something very similar to what you've already got with the generic/interface setup...</p> <p>Honestly, if you're looking for something with true "dynamic support" like this, I'd do this kind of stuff in a DLR-capable language (like IronPython) and call into it from your C# stuff.</p>
How do I select a single element in jQuery? <p>I have a table structure that looks like:</p> <pre><code>&lt;table&gt; &lt;tr id="row1"&gt; &lt;td&gt; &lt;div&gt;row 1 content1&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 1 content2&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 1 content3&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="row2"&gt; &lt;td&gt; &lt;div&gt;row 2 content1&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 2 content2&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 2 content3&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="row3"&gt; &lt;td&gt; &lt;div&gt;row 3 content1&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 3 content2&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;row 3 content3&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Using jQuery I am trying to select the DIV in the second cell of the third row. I tried the following (amongst other things):</p> <pre><code>var d = $('#row3').children(':eq(1)').children(':eq(0)'); </code></pre> <p>What I get back is an array with a single element (the DIV I'm after) and I have to then access using d[0]. Why is jQuery returning a single element array, I thought using the selector above would return the DIV element directly?</p> <hr> <p><strong><a href="http://stackoverflow.com/questions/307500/how-do-i-select-an-element-in-jquery#307509">@Shog9</a></strong> - Duh...Ok a light just switched on in my brain, I get it now. Cheers.</p>
<p>jQuery always returns a set of elements. Sometimes, the set is empty. Sometimes, it contains only one element. The beauty of this is that you can write code to work the same way regardless of how many elements are matched:</p> <pre><code>$("selector").each(function() { this.style.backgroundColor = "red"; }); </code></pre> <p>Fun!</p>
Tips on making good documentation for developers <p>I'm preparing documentation for an open source project. My target audience are developers.</p> <p>Right now, I'm working on the API, porting and code design sections.</p> <p>Anyone has any tips on making documentation for developers?</p>
<p>Include simple examples that illustrates the intent of the API call in question. Very often, being able to look at code explains things much better then prose can (because of differences in culture, language ability etc).</p>
How do exceptions work (behind the scenes) in c++ <p>I keep seeing people say that exceptions are slow but I never see any proof. So instead of asking if they are I will ask how do exceptions work behind the scene so I can make a decisions of when to use them and if they are slow.</p> <p>From what I know exceptions are the same thing as doing a bunch of return but it also checks when it needs to stop doing the return. How does it check when to do stop? I am taking a guess and saying there is a second stack which holds the type of exception and stack location then does returns until it gets there. I am also guessing the only time that stack is touch is on a throw and every try/catch. AFAICT implementing a similar behaviour with return code would take the same amount of time. But this is all a guess so I want to know.</p> <p>How do exceptions really work?</p>
<p>Instead of guessing, I decided to actually look at the generated code with a small piece of C++ code and a somewhat old Linux install.</p> <pre><code>class MyException { public: MyException() { } ~MyException() { } }; void my_throwing_function(bool throwit) { if (throwit) throw MyException(); } void another_function(); void log(unsigned count); void my_catching_function() { log(0); try { log(1); another_function(); log(2); } catch (const MyException&amp; e) { log(3); } log(4); } </code></pre> <p>I compiled it with <code>g++ -m32 -W -Wall -O3 -save-temps -c</code>, and looked at the generated assembly file.</p> <pre><code> .file "foo.cpp" .section .text._ZN11MyExceptionD1Ev,"axG",@progbits,_ZN11MyExceptionD1Ev,comdat .align 2 .p2align 4,,15 .weak _ZN11MyExceptionD1Ev .type _ZN11MyExceptionD1Ev, @function _ZN11MyExceptionD1Ev: .LFB7: pushl %ebp .LCFI0: movl %esp, %ebp .LCFI1: popl %ebp ret .LFE7: .size _ZN11MyExceptionD1Ev, .-_ZN11MyExceptionD1Ev </code></pre> <p><code>_ZN11MyExceptionD1Ev</code> is <code>MyException::~MyException()</code>, so the compiler decided it needed a non-inline copy of the destructor.</p> <pre><code>.globl __gxx_personality_v0 .globl _Unwind_Resume .text .align 2 .p2align 4,,15 .globl _Z20my_catching_functionv .type _Z20my_catching_functionv, @function _Z20my_catching_functionv: .LFB9: pushl %ebp .LCFI2: movl %esp, %ebp .LCFI3: pushl %ebx .LCFI4: subl $20, %esp .LCFI5: movl $0, (%esp) .LEHB0: call _Z3logj .LEHE0: movl $1, (%esp) .LEHB1: call _Z3logj call _Z16another_functionv movl $2, (%esp) call _Z3logj .LEHE1: .L5: movl $4, (%esp) .LEHB2: call _Z3logj addl $20, %esp popl %ebx popl %ebp ret .L12: subl $1, %edx movl %eax, %ebx je .L16 .L14: movl %ebx, (%esp) call _Unwind_Resume .LEHE2: .L16: .L6: movl %eax, (%esp) call __cxa_begin_catch movl $3, (%esp) .LEHB3: call _Z3logj .LEHE3: call __cxa_end_catch .p2align 4,,3 jmp .L5 .L11: .L8: movl %eax, %ebx .p2align 4,,6 call __cxa_end_catch .p2align 4,,6 jmp .L14 .LFE9: .size _Z20my_catching_functionv, .-_Z20my_catching_functionv .section .gcc_except_table,"a",@progbits .align 4 .LLSDA9: .byte 0xff .byte 0x0 .uleb128 .LLSDATT9-.LLSDATTD9 .LLSDATTD9: .byte 0x1 .uleb128 .LLSDACSE9-.LLSDACSB9 .LLSDACSB9: .uleb128 .LEHB0-.LFB9 .uleb128 .LEHE0-.LEHB0 .uleb128 0x0 .uleb128 0x0 .uleb128 .LEHB1-.LFB9 .uleb128 .LEHE1-.LEHB1 .uleb128 .L12-.LFB9 .uleb128 0x1 .uleb128 .LEHB2-.LFB9 .uleb128 .LEHE2-.LEHB2 .uleb128 0x0 .uleb128 0x0 .uleb128 .LEHB3-.LFB9 .uleb128 .LEHE3-.LEHB3 .uleb128 .L11-.LFB9 .uleb128 0x0 .LLSDACSE9: .byte 0x1 .byte 0x0 .align 4 .long _ZTI11MyException .LLSDATT9: </code></pre> <p>Surprise! There are no extra instructions at all on the normal code path. The compiler instead generated extra out-of-line fixup code blocks, referenced via a table at the end of the function (which is actually put on a separate section of the executable). All the work is done behind the scenes by the standard library, based on these tables (<code>_ZTI11MyException</code> is <code>typeinfo for MyException</code>).</p> <p>OK, that was not actually a surprise for me, I already knew how this compiler did it. Continuing with the assembly output:</p> <pre><code> .text .align 2 .p2align 4,,15 .globl _Z20my_throwing_functionb .type _Z20my_throwing_functionb, @function _Z20my_throwing_functionb: .LFB8: pushl %ebp .LCFI6: movl %esp, %ebp .LCFI7: subl $24, %esp .LCFI8: cmpb $0, 8(%ebp) jne .L21 leave ret .L21: movl $1, (%esp) call __cxa_allocate_exception movl $_ZN11MyExceptionD1Ev, 8(%esp) movl $_ZTI11MyException, 4(%esp) movl %eax, (%esp) call __cxa_throw .LFE8: .size _Z20my_throwing_functionb, .-_Z20my_throwing_functionb </code></pre> <p>Here we see the code for throwing an exception. While there was no extra overhead simply because an exception might be thrown, there is obviously a lot of overhead in actually throwing and catching an exception. Most of it is hidden within <code>__cxa_throw</code>, which must:</p> <ul> <li>Walk the stack with the help of the exception tables until it finds a handler for that exception.</li> <li>Unwind the stack until it gets to that handler.</li> <li>Actually call the handler.</li> </ul> <p>Compare that with the cost of simply returning a value, and you see why exceptions should be used only for exceptional returns.</p> <p>To finish, the rest of the assembly file:</p> <pre><code> .weak _ZTI11MyException .section .rodata._ZTI11MyException,"aG",@progbits,_ZTI11MyException,comdat .align 4 .type _ZTI11MyException, @object .size _ZTI11MyException, 8 _ZTI11MyException: .long _ZTVN10__cxxabiv117__class_type_infoE+8 .long _ZTS11MyException .weak _ZTS11MyException .section .rodata._ZTS11MyException,"aG",@progbits,_ZTS11MyException,comdat .type _ZTS11MyException, @object .size _ZTS11MyException, 14 _ZTS11MyException: .string "11MyException" </code></pre> <p>The typeinfo data.</p> <pre><code> .section .eh_frame,"a",@progbits .Lframe1: .long .LECIE1-.LSCIE1 .LSCIE1: .long 0x0 .byte 0x1 .string "zPL" .uleb128 0x1 .sleb128 -4 .byte 0x8 .uleb128 0x6 .byte 0x0 .long __gxx_personality_v0 .byte 0x0 .byte 0xc .uleb128 0x4 .uleb128 0x4 .byte 0x88 .uleb128 0x1 .align 4 .LECIE1: .LSFDE3: .long .LEFDE3-.LASFDE3 .LASFDE3: .long .LASFDE3-.Lframe1 .long .LFB9 .long .LFE9-.LFB9 .uleb128 0x4 .long .LLSDA9 .byte 0x4 .long .LCFI2-.LFB9 .byte 0xe .uleb128 0x8 .byte 0x85 .uleb128 0x2 .byte 0x4 .long .LCFI3-.LCFI2 .byte 0xd .uleb128 0x5 .byte 0x4 .long .LCFI5-.LCFI3 .byte 0x83 .uleb128 0x3 .align 4 .LEFDE3: .LSFDE5: .long .LEFDE5-.LASFDE5 .LASFDE5: .long .LASFDE5-.Lframe1 .long .LFB8 .long .LFE8-.LFB8 .uleb128 0x4 .long 0x0 .byte 0x4 .long .LCFI6-.LFB8 .byte 0xe .uleb128 0x8 .byte 0x85 .uleb128 0x2 .byte 0x4 .long .LCFI7-.LCFI6 .byte 0xd .uleb128 0x5 .align 4 .LEFDE5: .ident "GCC: (GNU) 4.1.2 (Ubuntu 4.1.2-0ubuntu4)" .section .note.GNU-stack,"",@progbits </code></pre> <p>Even more exception handling tables, and assorted extra information.</p> <p>So, the conclusion, at least for GCC on Linux: the cost is extra space (for the handlers and tables) whether or not exceptions are thrown, plus the extra cost of parsing the tables and executing the handlers when an exception is thrown. If you use exceptions instead of error codes, and an error is rare, it can be <em>faster</em>, since you do not have the overhead of testing for errors anymore.</p> <p>In case you want more information, in particular what all the <code>__cxa_</code> functions do, see the original specification they came from:</p> <ul> <li><a href="http://www.codesourcery.com/public/cxx-abi/">Itanium C++ ABI</a></li> </ul>
Easiest way to extract SharePoint list data to a separate SQL Server table? <p><strong>Edited:</strong> What is the easiest way to <s>scrape</s> extract SharePoint list data to a separate SQL Server table? One condition: you're in a work environment where you don't control the SQL Server behind the SharePoint Server, so you can't just pull from the <em>UserData</em> table. </p> <p>Is there there any utilities that you can use to schedule a nightly extract? </p> <p>Is Microsoft planning any improvement here for "SharePoint 4"?</p> <p><strong>Update Jan 06, 2009:</strong><br /> <a href="http://connectionstrings.com/sharepoint">http://connectionstrings.com/sharepoint</a><br /> For servers where office is not installed you will need:<br /> <a href="http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&amp;displaylang=en">this download</a></p>
<p>There is a SSIS SharePoint task you can use to grab the data info a regular dataflow: <a href="http://www.codeplex.com/SQLSrvIntegrationSrv">http://www.codeplex.com/SQLSrvIntegrationSrv</a></p>
How to remove duplicate values from an array in PHP <p>How can I remove duplicate values from an array in PHP?</p>
<p>Use <a href="http://php.net/array_unique">array_unique()</a>.</p> <p>Example:</p> <pre><code>$array = array(1, 2, 2, 3); $array = array_unique($array); // Array is now (1, 2, 3) </code></pre>
In MVC, when do you use <%= %> and <% %>? <p>In asp.net mvc, when do we use:</p> <p>&lt;%= %></p> <p>and</p> <p>&lt;% %></p> <p>Do we ever need to put a ; (colon) ?</p>
<p><code>&lt;%= %&gt;</code> renders the output (string) of the contained command to the response. <code>&lt;% %&gt;</code> wraps executable statements (logic) in the view to control what gets executed. You don't use semicolons in the <code>&lt;%= %&gt;</code> blocks, but may in the <code>&lt;% %&gt;</code> depending on what statements are included.</p> <p>String rendering:</p> <p><code>&lt;%= Html.Encode( Model. Property ) %&gt;</code></p> <p>Code block:</p> <p><code>&lt;% Html.RenderPartial( "ViewName" ); %&gt;</code></p> <p><strong>EDIT:</strong> Here's a <a href="http://msdn.microsoft.com/en-us/library/k6xeyd4z.aspx" rel="nofollow">link</a> to the reference.</p>
Can I force a display font from inside a formula in Crystal Reports? <p>I have a report with a lot of formulas that translate the word "TRUE" into an "X" and "FALSE" into a blank space.</p> <p>I use these to put an "X" in a checkbox.</p> <p>Sometimes there is text after my checkbox. To avoid slight shifts to the left and right, I print the "X" and the " " in a fixed width font. It is very tedious to manually set the font for each field.</p> <p>Is there a way to specify a display font from inside the formula?</p> <p>Something like this would be nice:</p> <pre><code>DisplayFontName = "Courier New"; //wishful thinking DisplayFontSize = 8; //wishful thinking //this is the code I'm currently using if Uppercase({table.somefield}) = "TRUE" then "X" else " " </code></pre>
<p>No, this is not possible. The context of a formula is the property for which the formula is set only. You cannot access properties of the whole object e.g. a field. Perhaps you could think about using two images suppressed by a formula depending on the value of your field. Then you would get rid of the font problem.</p>
Complex builds in Visual Studio <p>I have a few things that I cannot find a good way to perform in Visual Studio:</p> <ol> <li><p>Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it does not work if I don't know names and/or the number of auto-generated source files. I can easily solve it in <code>GNU make</code> using <code>$(wildcard generated/*.c)</code>. How can I do something similar with Visual Studio?</p></li> <li><p>Can I prevent pre-build/post-build event running if the files do not need to be modified (<code>"make"</code> behaviour)? The current workaround is to write a wrapper script that will check timestamps for me, which works, but is a bit clunky.</p></li> <li><p>What is a good way to locate external libraries and headers installed outside of VS? In *nix case, they would normally be installed in the system paths, or located with <code>autoconf</code>. I suppose I can specify paths with user-defined macros in project settings, but where is a good place to put these macros so they can be easily found and adjusted?</p></li> </ol> <p>Just to be clear, I am aware that better Windows build systems exist (<code>CMake</code>, <code>SCons</code>), but they usually generate VS project files themselves, and I need to integrate this project into existing VS build system, so it is desirable that I have just plain VS project files, not generated ones.</p>
<ol> <li><p>If you need make behavior and are used to it, you can create <a href="http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.80).aspx">visual studio makefile projects</a> and include them in your project.</p></li> <li><p>If you want less clunky, you can write visual studio <a href="http://visualstudiohacks.com/articles/general/customize-your-project-build-process/">macros</a> and custom build events and tie them to specific build callbacks / hooks.</p></li> <li><p>You can try something like <a href="http://workspacewhiz.com/SolutionBuildEnvironmentReadme.html">workspacewhiz</a> which will let you setup environment variables for your project, in a file format that can be checked in. Then users can alter them locally.</p></li> </ol>
Passing data to .NET C# WPF applications/DLLs <p>I have a .NET C# WPF application that I am trying to make into a single-instance application using a Mutex. </p> <p>This .NET application is called by a C++-based DLL using CreateProcessAsUser() and is given parameters via environment variables. </p> <p>Subsequent instances will also be created by the C++ DLL in the same way.</p> <p>Subsequent instances would then need to pass their parameters to the first instance of the application before exiting.</p> <p>The problem is what methods can be used in the .NET application so that the subsequent instances would be able to pass their data to the first instance of the .NET application? The simpler, the better.</p> <p>I have researched some but I hope there are simpler ways.</p> <p>Things I have researched:</p> <ul> <li>Named Pipes </li> <li>.NET Remoting</li> <li>Windows Messaging (Sending WM_COPYDATA to the first instance window)</li> </ul> <p>Since I am just trying to pass 4 strings to the first instance, I am trying to avoid the above mentioned methods because they are somewhat overkill for my problem.</p> <p>The simplest I can think of is to export a function from the .NET application so that the subsequent instances of the .NET application can just call this function on the first instance of the .NET application and pass the data as the parameters of the function. However, is this possible in .NET? I've read that .NET EXE or DLLs could not export functions.</p> <p>Thanks!</p>
<p><em>The simplest I can think of is to export a function from the .NET application and then the subsequent instances can just call this function and pass the parameters to it.</em></p> <p>This is not how this works. You'll load the .NET assembly in the calling process, not magically cross the process boundary and talk to the child. </p> <p>Just have the parent open the child with redirected pipes using the Process class, and have the child read from stdin using Console.Read*</p>
Showing processing message in Python <p>I want to show the processing information or log in the original page when the submitted request is being served until it completes the execution. I thought it would be meaningful to the user to know what is happening behind the request.</p> <p>I don't find a clue to do so though, can you guys help me out as how people are doing like this one below one - for your reference</p> <p><a href="http://www.xml-sitemaps.com/" rel="nofollow">http://www.xml-sitemaps.com/</a></p>
<p>there are two ways i could imagine handling this:</p> <ol> <li><p>have your backend script (python) output the information of a long process to a log of some sort (text file, database, session, etc...) and then have javascript grab the information via ajax and update the current page.</p></li> <li><p>same deal, but instead of ajax just have a meta refresh on the page which would grab the latest updated information.</p></li> </ol>
Procedure to submit iPhone application to App Store? <p>Is it necessary to pay $99 before I can watch the video to submit an iPhone application to the App Store, or it is available free of cost anywhere?</p>
<p>You can join the developer program and watch the video without paying. It's on the home page of the iPhone Dev Centre after you've logged in. <a href="https://deimos.apple.com/WebObjects/Core.woa/BrowsePrivately/adc.apple.com.1579102445.01579102451.1580085281?i=2050284209" rel="nofollow">Direct link</a>.</p> <p>What you can't do without putting down your $99 is get your application on an iPhone or iPod touch (and that includes your own).</p>
Good library/libraries for datastructures in assembler <p>Are there any good libraries (preferably with commented source) for standard datastructures (Linked list, array list, queue, stack etc.) for x86 (or others) in Assembler ? I don't like to reinvent (and debug !) the wheel....</p>
<p>Why not just find a good C library and call it from your asm?</p> <p>Or if you need "inline" functionality:</p> <ul> <li>Compile the functions you want to use into a Hello World program.</li> <li>Disassemble the program.</li> <li>Rewrite the assembly as asm/pre-processor macros.</li> </ul>
Convert a string to a date in C++ <p>I know this may be simple but being C++ I doubt it will be. How do I convert a string in the form 01/01/2008 to a date so I can manipulate it? I am happy to break the string into the day month year constituents. Also happy if solution is Windows only.</p>
<pre><code>#include &lt;time.h&gt; char *strptime(const char *buf, const char *format, struct tm *tm); </code></pre>
Netbeans or Eclipse for C++? <p>I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file management, the build tools are external, so thats irrelevant here, for my comparison.</p> <p>Thus which is a better choice?</p> <p>Note: I know I should be using emacs or vim, but the issue is, my theory at least, that I'm left handed, so I use my right side (design,creativity) of the brain more than the left side (logic, memory), so I just simply cannot use emacs or vim, my brain simply isn't compatible, I tried them many times too, even used emacs for a few months but it drove me crazy...</p> <p>Thanks</p>
<p>I haven't used NetBeans, but Eclipse CDT (C Developer Tools, which includes C++), especially with the latest version, is really quite excellent:</p> <ul> <li>Syntax checking and spell checking</li> <li>Syntax highlighting that distinguishes between library calls and your function calls and between local and member variables and is even applied to code that's #ifdef'ed out</li> <li>Macro expansion that can step you through each level of macro application or show the final result even of very complex Boost Preprocessor macros</li> <li>A file and class outline view that updates dynamically to show where you are in a file. (Commercial IDE's I've used fail to do this.)</li> <li>Powerful, flexible Find/Replace and Find in Files features with complete Perl-style regex support. It's also supposed to be able to do a C/C++ Find in Files that can search based on language semantics (e.g., only find references, not declarations), although this sometimes doesn't work for me.</li> <li>Automatic tracking of TODO and other comment tags</li> <li>Mouseover tips that show the exact declaration of a variable or function, including any comments, instead of just where a variable or function is declared. (Again, commercial IDE's I've used fail to do this.)</li> <li>Support via plugins for Subversion, Doxygen, etc.</li> <li>Some refactoring support - rename, extract constant, extract function, a few others</li> <li>Code reformatter, based on user-definable code styles</li> </ul> <p>You'd asked specifically about its editor; the Eclipse editor is good enough that I use it in preference to the commercial IDE for our product whenever I don't need the commercial IDE's forms designer.</p> <p>Eclipse's debugger integration (using gdb) is tolerable but not great, and its memory usage is high. A few features (like the C/C++ Find in Files) don't work reliably or require reindexing (which is time consuming) for no apparent reason, but the latest version seems more reliable in this regard.</p> <p>Can someone who's used NetBeans fill in how it compares?</p>
Do you use Template Method Pattern in programming languages with closures/delegates/function pointers? <p>I have been going back and forth between C# and Java for the last 8 years. </p> <p>One thing that strikes me is that I have completely stopped using the "Template Method" design pattern in C#. Actually, in C# I Have come to think of this pattern as an anti-pattern. </p> <p><a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Template_method_pattern</a></p> <p>Coming back to Java, I find the pattern is alive and kicking. I still think it looks antique, but realise that there's no other way to do this in java. Java looks antique too ;)</p> <p>Since this is going to come up anyway, Why is it an antipattern ?</p> <ul> <li>A lot of times it uses up your inheritance hierarchy for "the wrong reasons".</li> <li>Base classes have a tendency to become littered with all sorts of unrelated code.</li> <li>It forces you to lock down design, often quite early in the development process. (Premature lock down in a lot of cases)</li> <li>Changing this at a later stage becomes just harder and harder.</li> </ul> <p>So with closures/delegates/function pointers, you normally pass around some function instead of subclassing.</p> <p>So back to the question: </p> <p>If your language has closures/delegates/function, do you use the Template Method, and when?</p>
<p>When I used Java, yes. But for languages with "closures/delegates/function", Lua in my case, no I don't anymore, instead I've been leaning more and more towards <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow">decoration pattern</a> for most of my needs.</p>
How do I make a thread dump in JBoss 4.0.5 on Windows <p><br /> I'm running JBoss 4.0.5 on Windows 2003 x64 and wonder if there is any way to get a dump of all threads? </p> <ul> <li><p>It's stared with FireDaemon so I don't have a console windows in which to ctrl-break.</p></li> <li><p>It's running under java 1.5 so jstack won't work.</p></li> <li><p>I tried some program someone had made called sendsignal.exe, which I think actually crashed JBoss (not certain, but not going to try it again), if this was because JBoss runs under win x64 or because it runs as LocalSystem and I only have access to an "ordinary" user I don't know. It actually worked on my laptop, but it's 32-bit and I'm running as the same user as JBoss there.</p></li> </ul> <p>Someone has any other ideas that might work?</p>
<p>I actually found a better way than what <a href="http://stackoverflow.com/users/3253/gowri">Gowri</a> suggested (after starting to implementing the jsp).</p> <p>There is actually a way to dump the threads from the jmx-console in the Server Info MBean, see <a href="http://www.jboss.org/community/docs/DOC-9804" rel="nofollow">Generate a thread dump with the JMX Console</a></p>
LINQ To SQL Weird Join Issue <p>I have a simple database with two tables. Users and Configurations. A user has a foreign key to link it to a particular configuration.</p> <p>I am having a strange problem where the following query always causes an inner join to the Configuration table regardless of the second parameter value. As far as I can tell, even though the "UserConfiguration =" part of the object initialisation is conditional, LINQ doesn't see that and determines that a relationship is followed in any case.</p> <p>If I actually remove that last initialisation, the whole thing works as expected. It doesn't inner join when loadConfiguration == false and it does join when loadConfiguration == true.</p> <p>Anyone got any ideas about this? Is this syntax just not going to work? The only thought I have now is to wrap the return in a basic if statement - I just wanted to avoid the duplicated lines.</p> <pre><code>public UserAccount GetByUsername(string username, bool loadConfiguration) { using (Database database = new Database()) { if (loadConfiguration) { DataLoadOptions loadOptions = new DataLoadOptions(); loadOptions.LoadWith&lt;User&gt;(c =&gt; c.Configuration); database.LoadOptions = loadOptions; } return (from c in database.Users where c.Username == username select new UserAccount { ID = c.ID, ConfigurationID = c.ConfigurationID, Username = c.Username, Password = c.Password.ToArray(), HashSalt = c.HashSalt, FirstName = c.FirstName, LastName = c.LastName, EmailAddress = c.EmailAddress, UserConfiguration = (loadConfiguration) ? new ApplicationConfiguration { ID = c.Configuration.ID, MonthlyAccountPrice = c.Configuration.MonthlyAccountPrice, TrialAccountDays = c.Configuration.TrialAccountDays, VAT = c.Configuration.VAT, DateCreated = c.Configuration.DateCreated } : null }).Single(); } } </code></pre> <p>Thanks in advance,</p> <p>Martin.</p>
<p>I dont think it will work like that.</p> <p>I suggest splitting it into 2 distinct queries. </p> <p>There are probably better ways, but it would require more 'plumbling'.</p>
Select X Most Recent Non-Consecutive Days Worth of Data <p>Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.</p>
<p>Following the approach <a href="http://stackoverflow.com/questions/308650/select-x-most-recent-non-consecutive-days-worth-of-data#308670">Tony Andrews</a> suggested, here is a way of doing it in T-SQL:</p> <pre><code>SELECT Value, ValueDate FROM Data WHERE ValueDate &gt;= ( SELECT CONVERT(DATETIME, MIN(TruncatedDate)) FROM ( SELECT DISTINCT TOP 5 CONVERT(VARCHAR, ValueDate, 102) TruncatedDate FROM Event ORDER BY TruncatedDate DESC ) d ) ORDER BY ValueDate DESC </code></pre>
Does PageRank mean anything? <p>Is it a measure of anything that a developer or even manager can look at and get meaning from? I know at one time, it was all about the 7, 8, 9, and 10 PageRank. But is it still a valid measure of anything? If so, what can you learn from a PageRank?</p> <p>Note that I'm assuming that you have other measurements that you can analyze.</p>
<p>PageRank is specific to <strong>Google</strong> and is a trademarked proprietary algorithm. </p> <p>There are many variables in the formulas used by Google, but PageRank is primarily affected by the number of links pointing to the page, the number of internal links pointing to the page within the site and the number of pages in the site.</p> <p>Thing you must consider is it's specific to a <strong>web page, not to a web site</strong>. So you need to optimize every pages.</p> <p>Google sends <strong>Googlebot</strong>, its indexing robot, to spider your website, the bot is instructed not to crawl your site too deep unless it has a reasonable amount of PR (PageRank).</p>
.net webservice publishing process question <p>I have a webservice that exists in an asp.net website. When I publish the site to a test server I have to go into the bin folder and into the .svc file for the service and manually change the URL to correctly reflect the test server URL. Is there a better way to handle something like this?</p>
<p>You could always run a build tool to automatically do this for you.</p>
Rewritepath and IIS Integrated Mode <p>I have big issue with url-rewriting for IIS 7.0.</p> <p>I've written simple module for rewriting for my NET3.5/IIS7 web application. Here is a part of the code.</p> <pre><code> public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; if (app.Request.Path.Contains("pagetorewrite.aspx")) HttpContext.Current.RewritePath("~/otherpage.aspx"); } </code></pre> <p>And I register my module in web.config :</p> <pre><code> &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false"/&gt; &lt;modules&gt; &lt;add name="MyModule" type="MyModule" preCondition="" /&gt; </code></pre> <p>Under IIS 7.0 (Vista) using Classic ASP Pipeline it works perfect, but when I change pipeline mode to Integrated, then it stops working. There are no exceptions, errors and anything in debugger/events/logfiles - only message in a browser that page was not found. The stragnest thing is that pagename looks like mispelled or merged from parts of original page and rewrte-to page.</p> <p>I've deployed my code at another computer (also vista -but x64- and iis 7.0) and it works perfect in both modes. It looks that there's an configuration issue or what?</p>
<p>Just a guess: Qualify your type with the assembly name (type="MyModule,MyAssembly")</p>
dotnet: How do you get average character width for a font? <p>Windows Forms:</p> <p>For <code>System.Drawing</code> there is a way to get the font height. </p> <pre><code>Font font = new Font("Arial", 10 , FontStyle.Regular); float fontHeight = font.GetHeight(); </code></pre> <p>But how do you get the other text metrics like average character width?</p>
<p>Use Graphics.MeasureString Method</p> <pre><code>private void MeasureStringMin(PaintEventArgs e) { // Set up string. string measureString = "Measure String"; Font stringFont = new Font("Arial", 16); // Measure string. SizeF stringSize = new SizeF(); stringSize = e.Graphics.MeasureString(measureString, stringFont); // Draw rectangle representing size of string. e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height); // Draw string to screen. e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0)); } </code></pre>
hibernate auto-discovery and generation of of database mappings to POJOs <p>Are there any tools that auto-generate the hibernate POJOs by gathering information from the database?</p> <p>I made a perl script to do this after the schema got changed for the third or fourth time in a project i'm working with and just wondered if there is any established tool that will do this for me as my script is rather crude and needs some tweaking of the generated <code>.java</code> and <code>.hbm.xml</code> files.</p> <p>For example (based on what my script does), having a table <code>statement</code>:</p> <pre><code>Object_Name Type_Name Base_Type Nulls Identity ------------ --------- --------- ----- -------- id id_int int no yes id_user id_tiny tinyint no no value float float no no </code></pre> <p>I would like the program to autogenerate the following java:</p> <pre><code>package com.some.company.schema; import java.io.Serializable; public class Statement implements Serializable { private static final long serialVersionUID = 1227171190L; private Integer id; private User user; private Float value; public void setId(Integer id){ this.id = id; } public Integer getId(){ return this.id; } public void setUser(User user){ this.user = user; } public User getUser(){ return this.user; } public void setValue(Float value){ this.value = value; } public Float getValue(){ return this.value; } } </code></pre> <p>And the corresponding Hibernate mapping file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt; &lt;hibernate-mapping&gt; &lt;class name="com.some.company.schema.Statement" table="statement"&gt; &lt;id name="id" column="id"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;many-to-one name="user" class="com.some.company.schema.User" column="id_user" not-null="true" /&gt; &lt;property name="value" column="value" not-null="true" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
<p>See <a href="https://docs.jboss.org/tools/latest/en/hibernatetools/html/reverseengineering.html" rel="nofollow">hibernate reverse engineering</a></p>
Editing documents seamlessly in a Web Application <p>We have a web application, which involves a lot of documents. In a typical use case, a document will be generated from our web application. The user download the generated document to the local file system and modify it. After this work, the user upload the modified document back to the web application. </p> <p>I need an easier way, to work with the web application and documents. It should be seamlessly. Maybe, there is a way, to edit the document in a webdav folder similar a sharepoint document list and store it right back in the web application, without storing a temporary document on the local file system.</p> <p>But maybe, there are better ideas.</p> <p>P.S: I don't want to use active x controls and it must be a webapplication :-)</p> <p>Thank you for your help. </p>
<p>I don't think this is possible without a plugin. I've used activex in the past, maybe it would be possible to write a cross-platform java applet?</p>
Installing SVN username password issue <p>I'm installing SVN with Apache 2.2 on windows 2003 everything seems good but when I try to login no username/password works</p> <p>Here is some info<br> I load this module in httpd.conf<br> LoadModule auth_basic_module modules/mod_auth_basic.so<br> <br> and in svnserv.conf i have<br> [general]<br> anon-access=read<br> auth-access=write<br> <br> password-db=passwd<br> authz-db=authz<br> <br> in the passwd file<br> [users]<br> harry=harry<br> sally=sally<br> <br> <br> what am I doing wrong or missign?</p>
<p>I think the problem might be that you need to generate the password file using <a href="http://httpd.apache.org/docs/1.3/programs/htpasswd.html" rel="nofollow">htpasswd</a>. Storing unencrypted passwords isn't a good thing!</p>
Problem running a Jar file <p>I've compiled a java project into a Jar file, and am having issues running it.</p> <p>When I run:</p> <pre><code>java -jar myJar.jar </code></pre> <p>I get the following error</p> <pre><code>Could not find the main class: myClass </code></pre> <p>The class file is not in the root directory of the jar so I've tried changing the path of the main class to match the path to the class file and I get the same issue.</p> <p>Should I be flattening the file structure? if so how do I do this. I'm using Ant to build the Jar file if thats of any use.</p> <p><strong>UPDATE</strong> </p> <p>Here is the contents of the jar and the relevant Ant sections, I've changed the name of the firm I work for to "org":</p> <pre><code>META-INF/ META-INF/MANIFEST.MF dataAccessLayer/ dataAccessLayer/databaseTest.class org/ org/eventService/ org/eventService/DatabaseObject.class org/eventService/DatabaseObjectFactory.class org/eventService/DbEventClientImpl$HearBeatMonitor.class org/eventService/DbEventClientImpl.class org/eventService/EmptyQueryListException.class org/eventService/EventHandlerWorkItem.class org/eventService/EventProcessor.class org/eventService/EventTypeEnum.class org/eventService/EventWorkQueue$MonitorThread.class org/eventService/EventWorkQueue$PoolWorker.class org/eventService/EventWorkQueue.class org/eventService/FailedToLoadDriverException.class org/eventService/IConnectionFailureListener.class org/eventService/InvalidEventTypeException.class org/eventService/JdbcInterfaceConnection.class org/eventService/NullArgumentException.class org/eventService/OracleDatabaseObject.class org/eventService/ProactiveClientEventLogger.class org/eventService/ProactiveClientEventLoggerException.class org/eventService/PropertyMap.class org/eventService/SQLServerDatabaseObject.class org/eventService/TestHarness.class org/eventService/Utilities.class </code></pre> <p>And the ant target:</p> <pre><code>&lt;target name="compile" depends="init" description="compile the source "&gt; &lt;javac srcdir="src" destdir="bin" classpathref="project.class.path"/&gt; &lt;/target&gt; &lt;target name="buildjar" description="build jar file" depends="compile"&gt; &lt;mkdir dir="dist"/&gt; &lt;jar destfile="dist/myJar.jar" basedir="bin" includes="**/*.class" &gt; &lt;manifest&gt; &lt;attribute name="Main-Class" value="org.eventService.ProactiveClientEventLogger"/&gt; &lt;/manifest&gt; &lt;/jar&gt; &lt;/target&gt; </code></pre>
<p>In your manifest file, make sure you have the attribute <code>Main-Class</code> set to the name of the class containing your <code>main()</code> method. For example, if the package-qualified name of the class is <code>my.cool.Class</code>, then, in your JAR manifest, <code>Main-Class</code> should be set to <code>my.cool.Class</code>.</p> <p>Also made sure that you have a package declaration in your <code>.java</code> files (for example, in <code>Class.java</code>, make sure you have the proper <code>package my.cool;</code> declaration). Also, make sure your directory hierarchy is set up correctly (<code>my.cool.Class</code> should be in <code>$SRC/my/cool/Class.java</code>).</p>
nVidia SLI Tricks <p>I'm optimizing a directx graphics application to take advantage of nVidia's SLI technology. I'm currently investigating some of the techniques mentioned in their 'Best Practices' web page, but wanted to know what advice/experience any of you have had with this? </p> <p>Thanks!</p>
<p>This is not really an answer to you question, more of a comment on SLI. </p> <p>My understanding is that SLI is only really a cost-effective means of gaining performance when you buy two cards right away, which few people actually do. Many people buy an SLI motherboard and card thinking it will give them a better upgrade path down the road, but the reality is that by the time you get to that point, it is going to be cheaper to buy a new, faster card, than it is to duplicate the one you already have just to get SLI going.</p> <p>Just a thought before you pour too much energy into it. If you have a requirement to support SLI, then that's what you have to do. But personally, I would rather see optimization energy put towards non-SLI implementations.</p>
PCL raster color graphics distorted. Code included: what am I missing? <p>The function below prints a color raster image to a PCL-5 printer. The function was adapted from a 2-color (1bpp) printing function we had that worked perfectly, except for the grainy 2-color printing. The problem is that the image comes out with a large black bar extending from the right of the image to the edge of the page like this:</p> <pre><code> IMAGE######################################### IMAGE#########AREA COMPLETELY BLACK########### IMAGE######################################### </code></pre> <p>The image itself looks perfect, otherwise. </p> <p>Various PCL-to-PDF tools don't show the image at all, which leads me to believe I've forgotten do to something. Appropriate resets (\u001bE\u001b%-12345X) were sent before, and page-feeds after.</p> <p>Any PCL experts out there? I've got the PCL 5 Color Technical Reference Manual, and it's gotten me this far. This last thing is driving me crazy though.</p> <p>*Edit: I now know what command is causing the problem, but I don't know why:</p> <pre><code> stream("\u001b*r0F"); </code></pre> <p>This should keep the image rotated along with the page (portrait, landscape). If I remove this, the problem goes away. I can compensate by rotating the bitmap beforehand, but I really want to know what caused this!</p> <pre><code> static void PrintImage() { // Get an image into memory Image original = Image.FromFile("c:\\temp\\test.jpg"); Bitmap newBitmap = new Bitmap(original, original.Width, original.Height); stream(String.Format("\u001b*p{0:d}x*p{1:d}Y", 1000, 1000));// Set cursor. stream("\u001b*t300R"); // 300 DPI stream(String.Format("\u001b*r{0:d}T", original.Height)); // Height stream(String.Format("\u001b*r{0:d}S", original.Width)); // Width stream("\u001b*r3U"); // 8-bit color palette stream("\u001b*r0F"); // Follow logical page layout (landscape, portrait, etc..) // Set palette depth, 3 bytes per pixel RGB stream("\u001b*v6W\u0000\u0003\u0000\u0008\u0008\u0008"); stream("\u001b*r1A"); // Start raster graphics stream("\u001b*b0M"); // Compression 0 = None, 1 = Run Length Encoding // Not fast, but fast enough. List&lt;byte&gt; colors = new List&lt;byte&gt;(); for (int y2 = 0; y2 &lt; original.Height; y2++) { colors.Clear(); for (int x2 = 0; x2 &lt; original.Width; x2++) { Color c = newBitmap.GetPixel(x2, y2); colors.Add(c.R); colors.Add(c.G); colors.Add(c.B); } stream(String.Format("\u001b*b{0}W", colors.Count)); // Length of data to send streamBytes(colors.ToArray()); // Binary data } stream("\u001b*rB"); // End raster graphics (also tried *rC -- no effect) } </code></pre>
<p>There are a few problems with your code. First off your cursor position code is incorrect, it should read:</p> <pre><code>"\u001b*p{0:d}x1:d}Y", 1000, 1000 </code></pre> <p>This equates to:</p> <pre><code>&lt;esc&gt;*p1000x1000Y </code></pre> <p>you had:</p> <pre><code>&lt;esc&gt;*p1000x*p1000Y </code></pre> <p>When joining PCL commands together you match up the same parameterized value and group and then simply add value + parametrized character + value + parametrized character etc. Ensure that the final parametrized character is a capital letter which signifies the end of the PCL command.</p> <p>Also when defining an image I recommend you also specify the width &amp; hight in decipoints, this should help with the scaling of the image (*r3A) on the page so add this (just after your resolution command should be an okay place for it):</p> <pre><code>Int32 deciHeight = original.Height / (int)original.HorizontalResolution * 720; Int32 deciWidth = original.Width / (int)original.VerticalResolution * 720; stream("\u001b*t{0:d}h{1:d}V", deciHeight, deciWidth)); </code></pre> <p>The other recommendation is to write all of this to file (watch your encodings) and use one of the handful of PCL viewers to view your data vs. always printing it. Should save you some time and a forest or two! I've tried all of them and wold recommend spending the $89 and purchasing <a href="http://www.pagetech.com" rel="nofollow">pclWorks</a>. They also have a complete SDK if you are going to do a lot of PCL. We don't use that as we hardcode all PCL ourselves but it does look good.</p> <p>As for rotation, we've had problems on some device, You could just rotate the the jpg first (original.RotateFlip) an then write it out.</p> <p>I don't have much time today but hope that my comments assist. I can test your code on Monday or Tuesday and work with it and post any further comments.</p> <p>Keep in mind that even though PCL is a standard its support from manufacturer to manufacturer and device to device can be a problem and vastly different. When doing basic things most devices seem okay; however, if you get into macros or complex graphics you will find difference.</p>
Lisp In A Box - Why is it starting a server? <p>I've decided to get back into LISP (haven't used it since my AI classes) to get more comfortable with functional programming in general, so I downloaded Lisp In A Box (which we actually used in a previous class) which comes with CLISP and Emacs.</p> <p>When I run it, it says:</p> <blockquote> <p>Connected on port 1617. Take this REPL, brother, and may it serve you well.</p> </blockquote> <p>What the? So I looked on the Lisp In A Box webpage more closely and found this:</p> <blockquote> <p>SLIME is an integrated development environment for Emacs which interfaces with a Common Lisp implementation over a network socket. Lots of information about SLIME can be found at the SLIME node on CLiki. The manual for SLIME is available in PDF format online. </p> </blockquote> <p>I somewhat understand what SLIME is (some sort of extension to emacs, right?) But why in the world is a text editor starting its own server and connecting to it?</p>
<p>The purpose is so that Lisp will be running in parallel.</p> <p>Slime connects to the session and then you can have the same environment, definitions, etc from many different windows (or machines even). This means that you can start up your application and debug it on the fly, for instance.</p> <p>For further information, look at <a href="http://bc.tech.coop/blog/081209.html">this blog</a>.</p>
How to Establish Inheritance Between Objects in JavaScript? <p>I have the following code that creates two objects (ProfileManager and EmployerManager) where the object EmployerManager is supposed to inherit from the object ProfileManager. However, when I do alert(pm instanceof ProfileManager); it returns false.</p> <pre><code>function ProfileFactory(profileType) { switch(profileType) { case 'employer': return new EmployerManager(); break; } } function ProfileManager() { this.headerHTML = null; this.contentHTML = null; this.importantHTML = null; this.controller = null; this.actions = new Array(); this.anchors = new Array(); } ProfileManager.prototype.loadData = function(action, dao_id, toggleBack) { var step = this.actions.indexOf(action); var prv_div = $('div_' + step - 1); var nxt_div = $('div_' + step); new Ajax.Request(this.controller, { method: 'get', parameters: {action : this.actions[step], dao_id : dao_id}, onSuccess: function(data) { nxt_div.innerHTML = data.responseText; if(step != 1 &amp;&amp; !prv_div.empty()) { prv_div.SlideUp(); } nxt_div.SlideDown(); for(i = 1; i &lt;= step; i++) { if($('step_anchor_' + i).innerHTML.empty()) { $('step_anchor_' + i).innerHTML = this.anchors[i]; } } } } ) } EmployerManager.prototype.superclass = ProfileManager; function EmployerManager() { this.superclass(); this.controller = 'eprofile.php'; this.anchors[1] = 'Industries'; this.anchors[2] = 'Employer Profiles'; this.anchors[3] = 'Employer Profile'; this.actions[1] = 'index'; this.actions[2] = 'employer_list'; this.actions[3] = 'employer_display'; } var pm = new ProfileFactory('employer'); alert(pm instanceof ProfileManager); </code></pre> <p>BTW, this is my very first attempt at Object-Oriented JavaScript, so if you feel compelled to comment on the stupidity of my approach please feel free to do so, but offer suggestions on how to approach the problem better.</p>
<p>I've been using something similar to Dean Edward's Base.js model. <a href="http://dean.edwards.name/weblog/2006/03/base/" rel="nofollow">http://dean.edwards.name/weblog/2006/03/base/</a></p>
Communicating from website to desktop application (not vice-versa) <p>I am designing an application that will have to react to certain website actions, mostly in the same way as the Last.FM client does.</p> <p>The way the Last.FM client works is that it first registers a custom protocol in Windows (<code>lastfm://</code>) after which certain player actions can be triggered via the website by following the links using this protocol. For example, following</p> <pre><code>lastfm://artist//similarartists </code></pre> <p>will direct any Last.FM client running to load similar artists.</p> <p>I would like to implement something similar for my application with my own protocol and client.</p> <ol> <li>Is this a good idea general? </li> <li>Are there any good alternatives to this mechanism of notifying a desktop client from the website?</li> </ol>
<p>I've often wanted to see more applications that do this because the integration between web and local makes for a great experience (if you ignore any spammy related qualms)</p>
inheritance from two parent classes <p>I read about this ages ago but never tried it now I can't remember if this is possible or not. Is it possible to extend a class from two parents on php5 e.g.</p> <p>class_d extends class_c and class_b</p> <p>moreover can you do this if class_c and class_b are themselves extended from class_a ... so you get something like this</p> <pre><code> class_a class_b class_c class_d </code></pre>
<p>multiple inheritance (what you are looking for) is not supported in PHP. </p> <p>You may want to check out <a href="http://www.devshed.com/c/a/PHP/Object-Interaction-in-PHP-Introduction-to-Composition/" rel="nofollow">composition</a> (where one class contains an instance of the parent) or even <a href="http://us.php.net/interfaces" rel="nofollow">interfaces</a> if it applies specifically to your situation. </p>
Declare-and-throw vs. throw-without-being-declared exceptions <p>In Java, what is the difference between the twin methods?</p> <pre><code>public void methodA() throws AnException { //do something throw new AnException(); } public void methodA() { //do the same thing throw new AnException(); } </code></pre> <p>I have a intuition that it has something to do with being a well-designed method (because I put methodA in an interface, declared it the way methodA* does in its implementation and received a warning from Java that "A* cannot override A because A* doesn't throw AnException"). </p> <p>Is this speculation correct? </p> <p>Is there any other subtle connotations in the two ways of doing things?</p>
<p>If AnException is a checked exception (in other words, if it doesn't extend RuntimeException) then methodA won't compile. Checked exceptions must always be declated.</p> <p>If AnException is an unchecked exception (if it does extend RuntimeException), then either is allowed by the java compiler, and either is interpreted equivalently by the java runtime. methodA is still probably still preferred in this case, for the reasons of documentation. The javadoc for your method will show that it might throw AnException. It's good to let users of your method know what Exceptions they should expect.</p>
Mapping a class with multiple collection properties containing the same object type <p>Our system generates emails with user-chosen lists of To / CC / BCC contacts. I wanted to store them as follows in our SQL Server database, here's the simplified database table structure:</p> <pre><code>CREATE TABLE [Contact] ( [ContactID] [int] IDENTITY (1, 1) NOT NULL, [Name] [varchar] (100) NOT NULL, [EmailAddress] [varchar] (100) NOT NULL, CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED ([ContactID]) ) CREATE TABLE [Email] ( [EmailID] [int] IDENTITY (1, 1) NOT NULL, [Subject] [varchar] (500) NOT NULL, [Message] [text] NULL, [DateSent] [datetime] NOT NULL, CONSTRAINT [PK_Email] PRIMARY KEY CLUSTERED ([EmailID]) ) CREATE TABLE [EmailContact] ( [EmailID] [int] NOT NULL, [ContactID] [int] NOT NULL, [Type] [varchar] (4) NOT NULL, CONSTRAINT [PK_EmailContactList] PRIMARY KEY CLUSTERED ( [EmailID], [ContactID], [Type] ), CONSTRAINT [FK_EmailContact_Contact] FOREIGN KEY ([ContactID]) REFERENCES [Contact] ([ContactID]), CONSTRAINT [FK_EmailContact_Email] FOREIGN KEY ([EmailID]) REFERENCES [Email] ([EmailID]) ) </code></pre> <p>This to me looks like a case of a many-to-many relationship between the Email and Contact objects. However, I would like the Email domain object to have 3 separate IList properties for the contacts of each list (To / CC / BCC) such that I could enable the following code to work :</p> <pre><code>testEmail.ToContacts.Add(contact1) testEmail.CCContacts.Add(contact2) testEmail.BCCContacts.Add(contact3) </code></pre> <p>Can this be done without adding an additional domain object (EmailContact)? Do I need to use two many-to-one relationships with an additional domain object like <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2008/07/11/when-to-use-many-to-one-s-vs-many-to-many-with-nhibernate.aspx" rel="nofollow">Billy McCafferty mentions here</a>?</p> <p>Also, how would I represent this my NHibernate mapping file? </p>
<p>According to the article you cite by Billy McCafferty:</p> <blockquote> <p>At first glance, this might imply that you'd have to create a CustomerAddress object in your domain model to reflect this relationship table in the DB; that's not the case with NHibernate. Instead, you'd simply add a many-to-many association to the Customer.hbm.xml which indicates that the CustomerAddresses table should be used as the lookup for managing this many-to-many relationship. </p> </blockquote> <p>Replace McCafferty's "CustomerAddresses" example with your "EmailContacts". According to the article, you WILL need an "EmailContacts" <em>table</em> to represent the many-to-many relationship between emails and contacts, but not an <code>EmailContacts</code> domain object. If you want three separate relationships for To, CC, and BCC, create three join tables: <code>To_EmailAddresses</code>, <code>CC_EmailAddresses</code>, and <code>BCC_EmailAddresses</code>. </p> <p>I'm not totally familiar with NHibernate so I don't know exactly how to update the mapping file, but the article indicates that the file relating to your Email domain object (Email.hbm.xml) would be the one to update. The NHibernate documentation should tell you how to represent a many-to-many relationship in a mapping file.</p>