input
stringlengths
51
42.3k
output
stringlengths
18
55k
How do I ORDER BY an arithmetic express in SQLAlchemy? <p>How do I translate something like this into SQLAlchemy?</p> <pre><code>SELECT (a * b) - (x + y) / z AS result FROM table ORDER BY result </code></pre>
<p>Just pass the label in as a string argument to <code>order_by</code>:</p> <pre><code>result_exp = sqlalchemy.sql.expression.label('result', ((test2_table.c.a * test2_table.c.b) - (test2_table.c.x + test2_table.c.y) / test2_table.c.z)) select([result_exp], from_obj=[test2_table], order_by="result") </code></pre>
How to debug COM object in Visual Studio 6.0 that is created in an ASP page? <p>I have an old C++ COM component which has to stay in Visual Studio 6.0 format. I can't for the life of me figure out how to debug the code in the actual COM component.</p> <p>I'm able to build it in debug mode, add breakpoints and attach it to the dllhost.exe process, but the Visual Studio environment will only show me the disassembly from dllhost.exe and not my source code (It also doesn't stop on the breakpoints).</p> <p>I remember a while ago there was a way to make IIS (or inetinfo.exe) the <em>target</em> of your debug action (i.e. when Visual Studio 6.0 asks you for the executable to launch your dll) and IIS would run in a single process mode. There was a registry key you needed to change, but googling hasn't helped.</p>
<p>If it is a VB6 based COM component, you can open the project in VB6 and run it (a DLL project cannot be run). The project properties has some option whereby it can be asked to run so that it runs &amp; registers itself.</p> <p>Now, try hitting the ASP page, which makes a call to COM component. The breakpoints set in the class files will be hit, as the calls are made from ASP page.</p>
Java get JPanel Components <p>I have a JPanel full of JTextFields...</p> <pre><code>for (int i=0; i&lt;maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); } </code></pre> <p>How do I later get the JTextFields in that JPanel? Like if I want their values with </p> <pre><code>TextField.getText(); </code></pre> <p>Thanks</p>
<p>Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime ) </p> <p>In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here:</p> <pre><code>List&lt;JTextField&gt; list = new ArrayLists&lt;JTextField&gt;(); // your code... for (int i=0; i&lt;maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); list.add( textField ); // keep a reference to those fields. } </code></pre> <p>// Later </p> <pre><code>for( JTextField f : list ) { System.out.println( f.getText() ) ; } </code></pre> <p>Wasn't that easy?</p> <p>Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface.</p> <p>Let's say you want to get the array of texts, instead of </p> <pre><code> public List&lt;JTextField&gt; getFields(); </code></pre> <p>You should consider:</p> <pre><code> public List&lt;String&gt; getTexts(); // get them from the textfields ... </code></pre>
in SQL, or Django ORM, what's the conventional way to have an ordered one-to-many? <p>Say I wanted to have a project, and one-to-many with to-do items, and wanted to re-order the to-do items arbitrarily? </p> <p>In the past, I've added a numbered order field, and when someone wants to change the order, had to update all the items with their new order numbers. This is probably the worst approach, since it's not atomic &amp; required several updates.</p> <p>I notice Django has a multi-valued CommaSeparatedIntegerField which could contain the order by storing the ordered keys to the items in the to-do items table right in one field of the project table.</p> <p>I've pondered a dewey decimal system where if I wanted to take item 3 and put it between 1 and 2 I would change it's order number to 1.5.</p> <p>Something tells me there's an easier option that I'm missing though...</p> <p>How would you give order to a one-to-many relationship?</p>
<p>I hate this problem ... and I run into it all the time.</p> <p>For my most recent Django site we had a Newsletter which contained N Articles and, of course, order was important. I assigned the default order as ascending Article.id, but this failed if Articles were entered in something other than "correct" order.</p> <p>On the Newsletter change_form.html page I added a little bit of jQuery magic using the Interface plugin (<a href="http://interface.eyecon.ro/">http://interface.eyecon.ro/</a>). I show the titles of the associated Articles and the user can drag them around as they like. There is an onChange handler that recomputes the Article.id's in article_order field.</p> <p>Enjoy,<br> Peter</p> <p>For app=content, model=Newsletter, the following is in templates/admin/content/newslettter/change_form.html</p> <pre><code>{% extends 'admin/change_form.html' %} {% block form_top %}{% endblock %} {% block extrahead %}{{ block.super }} &lt;script type="text/javascript" src="/media/js/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/js/interface.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready( function () { $('ol.articles').Sortable( { accept : 'sortableitem', helperclass : 'sorthelper', activeclass : 'sortableactive', hoverclass : 'sortablehover', opacity: 0.8, fx: 200, axis: 'vertically', opacity: 0.4, revert: true, trim: 'art_', onchange: function(list){ var arts = list[0].o[list[0].id]; var vals = new Array(); var a; for (a in arts) { vals[a] = arts[a].replace(/article./, ''); } $('#id_article_order').attr('value', vals.join(',')); } }); } ); &lt;/script&gt; {% endblock %} {% block after_related_objects %} {% if original.articles %} &lt;style&gt; .sortableitem { cursor:move; width: 300px; list-style-type: none; } &lt;/style&gt; &lt;h4&gt;Associated Articles&lt;/h4&gt; &lt;ol class="articles" id="article_list"&gt; {% for art in original.articles %} &lt;li id="article.{{art.id}}" class="sortableitem"&gt;{{art.title}}&lt;/li&gt; {% endfor %} &lt;/ol&gt; {% endif %} {% endblock %} </code></pre>
HTTP 403 Error while accessing web service <p>Im trying to access a web service from a remote computer. I managed to access the web service from the browser. But Im getting HTTP 403 when I try to call the web service from the application.</p> <p>Any idea why?</p>
<p>A <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4" rel="nofollow">403</a> response indicates that the host or software you're connecting with isn't allowed to access the web service. Reasons for this might be:</p> <ul> <li>The remote host you are is being blocked by a firewall</li> <li>You've reached the limit of calls to the web service and they are blocking any further connections</li> <li>You are sending credentials for authentication but the account is banned/disabled</li> <li>The user-agent or some other header in your request is causing the service to reject the connection. Perhaps a missing header?</li> </ul>
Inheriting from ViewPage <p>Is it possible to inherit from both ViewPage and ViewPage&lt;T&gt;?? Or do I have to implement both. Currently this is what I have for ViewPage. Do i need to repeat myself and do the same for ViewPage&lt;T&gt;??</p> <pre><code> public class BaseViewPage : ViewPage { public bool LoggedIn { get { if (ViewContext.Controller is BaseController) return ((BaseController)ViewContext.Controller).LoggedOn; else return false; } } } </code></pre>
<p>Create both versions:</p> <pre><code>public class BaseViewPage : ViewPage { // put your custom code here } public class BaseViewPage&lt;TModel&gt; : BaseViewPage where TModel : class { // code borrowed from MVC source private ViewDataDictionary&lt;TModel&gt; _viewData; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public new ViewDataDictionary&lt;TModel&gt; ViewData { get { if (_viewData == null) { SetViewData(new ViewDataDictionary&lt;TModel&gt;()); } return _viewData; } set { SetViewData(value); } } protected override void SetViewData(ViewDataDictionary viewData) { _viewData = new ViewDataDictionary&lt;TModel&gt;(viewData); base.SetViewData(_viewData); } } </code></pre> <p>then </p> <pre><code>public class MyCustomView : BaseViewPage { } or public class MyCustomView : BaseViewPage&lt;MyCustomViewData&gt; { } </code></pre>
How to stop Gmail from marking mails sent by my web app as spam? <p>I have a simple web application that provides daily financial data. Users subscribe, and we send them an email every day. However, Gmail is marking all of our emails as spam. What should we be looking out for?</p>
<p>Chiefly, to avoid a spam engine classifying your messages as spam you should:</p> <ul> <li>Make sure they aren't spam (i.e. ensure that only users who have really opted in get mailed - make sure you keep an opt-in audit log)</li> <li>Make sure they don't look too much like spam - $$$ MAKE MONEY FAST is not a good subject line</li> <li>Ensure that the sender address is not spoofed and does not appear to be spoofed. Use a domain that you are authorised to send from (add valid SPF records if you like)</li> <li>Not do anything that looks malware-ish (e.g. HTML emails containing scripts, forms, flash etc)</li> </ul> <p>But by and large the main one is:</p> <ul> <li>Do not send them from an IP address which is known for sending spam.</li> </ul> <p>The last point means that YOU CANNOT USE SHARED HOSTING. Almost all shared hosting providers allow the sending of mails which don't conform to any of the above. Shared hosting providers' relays are almost always on lots of blacklists.</p> <p>It only takes one vulnerable web app on your shared hosting for it to turn into a spam gateway - something which you can't afford.</p> <p>EDIT: Oh yes - if you're not setting the envelope-sender, your hosting provider may have it set to something stupid - ensure that you do set it to the same as From: - this makes sure that your messages aren't seen as spoofed</p>
Differences between Python game libraries Pygame and Pyglet? <p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
<p><strong>Pygame: LGPL license</strong></p> <p><em>Pyglet: BSD license</em></p> <p><strong>Pygame relies on SDL libraries heavily</strong></p> <p><em>Pyglet is a pure python library with fewer dependencies, I think it requires better understanding of OpenGL</em></p> <p><strong>Pygame is around here for a long time, a lot of people used it</strong></p> <p><em>Pyglet is a new lib</em></p> <p><strong>Pygame is geared towards game development (cursors, sprites, joystick/gamepad support)</strong></p> <p><em>Pyglet is more general purpose (though it has a Sprite class)</em></p> <p>I found also this discussion on pyglet-users mailing list: <a href="http://www.mail-archive.com/pyglet-users@googlegroups.com/msg00482.html">from pygame+pyopengl to pyglet</a></p> <p>Disclaimer: I did not use either yet, only tried some tutorials ;-)</p>
Java 6 JVM Hang <p>Apologies for the long post, but I wonder if I could get some more eyeballs on this before I submit a bug report to Sun.</p> <p>JVM: 6u11<br> O/S: Windows XP SP3<br> Hardware: AMD Athlon 64 X2 4600+ @ 2.41GHz, with 3.25 GB RAM.</p> <p>I believe I have encountered a fault in the JVM where no thread is given a monitor. In the following thread traces, the monitor <code>&lt;0x12a8f9f8&gt;</code> was acquired by <code>RelayedMessages-0000000001</code>, which ended up waiting on it; that thread was subsequently notified. However, even though all of the threads listed are contending for the monitor, none are getting it.</p> <p>I promise the thread dump is complete for every thread which refers to monitor <code>&lt;0x12a8f9f8&gt;</code>. The dump was obtained using Java VisualVM, three times over a period of 16 hours, and shown to be consistent each time (these threads were unchanged).</p> <p>Does anyone disagree with my assessment that the JVM is failing to deliver the monitor to any of the eligible threads, when it should deliver it to one of them?</p> <pre><code>"RelayedMessages-0000000001" daemon prio=6 tid=0x03694400 nid=0x1750 waiting for monitor entry [0x05e1f000..0x05e1fc94] java.lang.Thread.State: BLOCKED (on object monitor) at java.lang.Object.wait(Native Method) at com.companyremoved.thd.EzWaiter.ezWait(EzWaiter.java:249) - locked &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.waitWithinMessage(IsolatedObject.java:352) - locked &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.system.coms.ComsSender.waitForAvailablePipe(ComsSender.java:219) at com.companyremoved.system.coms.ComsSender.sendObject(ComsSender.java:185) at com.companyremoved.system.coms.ComsSender.processIocMessage(ComsSender.java:98) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:311) - locked &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.iocMessage(IsolatedObject.java:265) at com.companyremoved.ioc.IocTarget.iocMessage(IocTarget.java:138) at com.companyremoved.ioc.IocBinding.iocMessage(IocBinding.java:105) at com.companyremoved.system.coms.ComsSender$Messages.sendObject(ComsSender.java:333) at com.companyremoved.system.coms.ComsSender$Messages.sendObject(ComsSender.java:316) at com.companyremoved.system.coms.RelayedMessage.run(RelayedMessage.java:104) - locked &lt;0x130fe8e0&gt; (a com.companyremoved.system.coms.RelayedMessage) at com.companyremoved.thd.RunQueue.runEntry(RunQueue.java:293) at com.companyremoved.thd.RunQueue.run(RunQueue.java:273) at java.lang.Thread.run(Unknown Source) Locked ownable synchronizers: - None "ScbPipe Writer" daemon prio=6 tid=0x4fff0c00 nid=0xf14 waiting for monitor entry [0x0594f000..0x0594fc14] java.lang.Thread.State: BLOCKED (on object monitor) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:293) - waiting to lock &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.iocMessage(IsolatedObject.java:265) at com.companyremoved.ioc.IocTarget.iocMessage(IocTarget.java:138) at com.companyremoved.coms.stm.ioc.ComsPipe$Receiver.scbPipeDefaultProcessor(ComsPipe.java:403) at com.companyremoved.scb.ScbPipe.processObject(ScbPipe.java:915) - locked &lt;0x131a4ea0&gt; (a java.lang.Object) at com.companyremoved.scb.ScbPipe.writerRun(ScbPipe.java:817) at com.companyremoved.scb.ScbPipe.run(ScbPipe.java:728) at java.lang.Thread.run(Unknown Source) Locked ownable synchronizers: - None "ScbPipe Writer" daemon prio=6 tid=0x4c647400 nid=0xe00 waiting for monitor entry [0x059ef000..0x059efb94] java.lang.Thread.State: BLOCKED (on object monitor) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:293) - waiting to lock &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.iocMessage(IsolatedObject.java:265) at com.companyremoved.ioc.IocTarget.iocMessage(IocTarget.java:138) at com.companyremoved.coms.stm.ioc.ComsPipe$Receiver.scbPipeDefaultProcessor(ComsPipe.java:403) at com.companyremoved.scb.ScbPipe.processObject(ScbPipe.java:915) - locked &lt;0x13188bb8&gt; (a java.lang.Object) at com.companyremoved.scb.ScbPipe.writerRun(ScbPipe.java:817) at com.companyremoved.scb.ScbPipe.run(ScbPipe.java:728) at java.lang.Thread.run(Unknown Source) Locked ownable synchronizers: - None "ScbPipe Writer" daemon prio=6 tid=0x035f7800 nid=0x1130 waiting for monitor entry [0x0726f000..0x0726fc94] java.lang.Thread.State: BLOCKED (on object monitor) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:293) - waiting to lock &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.iocMessage(IsolatedObject.java:265) at com.companyremoved.ioc.IocTarget.iocMessage(IocTarget.java:138) at com.companyremoved.coms.stm.ioc.ComsPipe$Receiver.scbPipeDefaultProcessor(ComsPipe.java:403) at com.companyremoved.scb.ScbPipe.processObject(ScbPipe.java:915) - locked &lt;0x12a8a478&gt; (a java.lang.Object) at com.companyremoved.scb.ScbPipe.writerRun(ScbPipe.java:817) at com.companyremoved.scb.ScbPipe.run(ScbPipe.java:728) at java.lang.Thread.run(Unknown Source) Locked ownable synchronizers: - None "IOC Signals-0000000001" daemon prio=6 tid=0x03673000 nid=0x1434 waiting for monitor entry [0x0415f000..0x0415fd94] java.lang.Thread.State: BLOCKED (on object monitor) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:293) - waiting to lock &lt;0x12a8f9f8&gt; (a com.companyremoved.system.coms.ComsSender) at com.companyremoved.ioc.IsolatedObject.iocMessage(IsolatedObject.java:265) at com.companyremoved.ioc.IocTarget.iocMessage(IocTarget.java:138) at com.companyremoved.ioc.IocBinding.iocMessage(IocBinding.java:105) at com.companyremoved.system.coms.ComsSender$Messages.removePipe(ComsSender.java:302) at com.companyremoved.system.coms.ConnectionController.disconnect(ConnectionController.java:712) at com.companyremoved.system.coms.ConnectionController.shutdown(ConnectionController.java:224) at com.companyremoved.system.coms.ConnectionController.processIocMessage(ConnectionController.java:168) at com.companyremoved.ioc.IsolatedObject.deliver(IsolatedObject.java:311) - locked &lt;0x12a8b798&gt; (a com.companyremoved.system.coms.ConnectionController) at com.companyremoved.ioc.IsolatedObject.access$100(IsolatedObject.java:36) at com.companyremoved.ioc.IsolatedObject$SignalProxy.run(IsolatedObject.java:526) at com.companyremoved.thd.RunQueue.runEntry(RunQueue.java:293) at com.companyremoved.thd.RunQueue.run(RunQueue.java:273) at java.lang.Thread.run(Unknown Source) Locked ownable synchronizers: - None </code></pre>
<p>The provided thread trace is complete with respect to the lock in question. Two other people I work with agree that a JVM fault is clearly indicated, as do the programmers at jProfiler (ej-technologies).</p>
Proper Memory allocation <p>I have the following construction:</p> <pre><code>typedef struct bucket { char *key; ENTRY *data; struct bucket *next; } bucket; typedef struct { size_t size; bucket **table; } hash_table; </code></pre> <p>But I have no idea how to allocate memory for that. I tried: </p> <pre><code>hash_table* ht = malloc(sizeof(hash_table)*101); </code></pre> <p>in order to create a hashtable for 101 entries but it din't work! Can anyone help me? I would really appreciate it!</p>
<p>It doesn't make sense to allocate all 101 (or however many) buckets upfront, you'd typically allocate them one at a time, when inserting new data into the table.</p> <p>It <em>does</em> make sense to pre-allocate the hash array, which will have a fixed size, but that is an <em>array of bucket pointers</em>, not an array of buckets, so some of the answers are wrong.</p> <p>You'd have something like this, to create a an empty hash table, with a fixed-size bucket array:</p> <pre><code>hash_table * hash_table_new(size_t capacity) { size_t i; hash_table *t = malloc(sizeof *t); t-&gt;size = capacity; t-&gt;bucket = malloc(t-&gt;size * sizeof *t-&gt;bucket); for(i = 0; i &lt; t-&gt;size; i++) t-&gt;bucket[i] = NULL; return t; } </code></pre> <p>This code:</p> <ul> <li>Allocates a hash_table structure to hold the table</li> <li>Initializes it's size with indicated capacity</li> <li>Allocates an array of bucket pointers of the proper length</li> <li>Makes sure each bucket pointer is NULL (which cannot properly be done with memset(), as it's not safe to assume that "all bits zero" is the way NULL looks in memory)</li> <li>Uses <code>sizeof</code> whenever possible, but not on types, so no parenthesis</li> <li>Doesn't cast the return value of <code>malloc()</code>, since that is never a good idea in C</li> <li>Doesn't check the return value of malloc(), of course you should do that in real code</li> </ul> <p>A second function would be needed to do an actual hash insert, which will then need to allocate a new bucket, compute the hash value from the key, pick the proper location in the hash table's array, and insert the new entry there.</p>
Runtime error 1004: Application-defined or object-defined error <p>I've been having a major issue... well maybe not major, but I've been trying to figure this out since yesterday lunchtime.<br /> I have the following code:</p> <pre><code>Application.CutCopyMode = False ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _ "Data!R7C1:R5000C40").CreatePivotTable TableDestination:= _ "'[Master-File.xls]Analyse'!R20C14", TableName:="certain_view", DefaultVersion _ -&gt; :=xlPivotTableVersion10 </code></pre> <p>The runtime error is in the line with the arrow, but the entire bit quoted above highlights yellow.</p> <blockquote> <p>Application-defined or object-defined error</p> </blockquote> <p>I am using Excel 2003, VBA. I have these few lines of script in my code five times, and only this bit fails every time. I am trying to create the fifth PivotTable with these lines.</p> <p>I think it might have something to do with the amount of data in memory... yet the Application.Cutopymode = False doesn't fix anyhting.</p>
<p>Fixed it (earlier, Remou pointed out that posting the answer is a good thing).<br /> I messed up a bit.</p> <p>My data was dynamic, on every reload another set. In my testing set, everything went awesomely fine. Then, as I loaded a new set, values changed, labels were added, others were left out... one of my pivot tables became a lot larger. A second one was programmed to be created in a certain cell, but that cell was now part of that larger table.</p> <p>Not a very clear error message, but 'aight, it's fixed.</p> <p>Moral: try to think of every possibility when assigning tables to worksheets.</p>
How do I programmatically check an item in a checkedlistbox in c# <p>I have a checkedlistbox and I want to automatically tick one of the items in it. </p> <p>The CheckedItems collection doesn't allow you to add things to it.</p> <p>Any suggestions?</p>
<p>You need to call <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.setitemchecked.aspx">SetItemChecked</a> with the relevant item.</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.objectcollection.aspx">documentation for CheckedListBox.ObjectCollection</a> has an example which checks every other item in a collection.</p>
JSON object for just an integer <p>Silly question, but I'm unable to figure out..</p> <p>I tried the following in Ruby:</p> <pre><code>irb(main):020:0&gt; JSON.load('[1,2,3]').class =&gt; Array </code></pre> <p>This seems to work. While neither</p> <pre><code>JSON.load('1').class </code></pre> <p>nor this </p> <pre><code>JSON.load('{1}').class </code></pre> <p>works. Any ideas?</p>
<p>I'd ask the guys who programmed the library. AFAIK, <code>1</code> isn't a valid JSON object, and neither is <code>{1}</code> but <code>1</code> is what the library itself generates for the fixnum 1.</p> <p>You'd need to do: <code>{"number" : 1}</code> to be valid json. The bug is that</p> <pre><code>a != JSON.parse(JSON.generate(a)) </code></pre>
How load a PHP page in the same window in jQuery <p>I have a PHP file, Test.php, and it has two functions:</p> <pre><code>&lt;?php echo displayInfo(); echo displayDetails(); ?&gt; </code></pre> <p>JavaScript:</p> <pre><code>&lt;html&gt; ... &lt;script type="text/javascript"&gt; $.ajax({ type:'POST', url: 'display.php', data:'id='+id , success: function(data){ $("#response").html(data); } }); &lt;/script&gt; ... &lt;div id="response"&gt; &lt;/div&gt; &lt;/html&gt; </code></pre> <p>It returns the response from jQuery. The response shows as <code>&lt;a href=Another.php?&gt;Link&lt;/a&gt;</code>. When I click the Another.php link in <code>test.php</code>, it loads in another window. But I need it to load the same <code>&lt;div&gt; &lt;/div&gt;</code> area without changing the content of <code>test.php</code>, since it has <code>displayInfo(), displayDetails()</code>. Or is it possible to load a PHP page inside <code>&lt;div&gt; &lt;/div&gt;</code> elements?</p> <p>How can I tackle this problem?</p>
<p>If I understand correctly, you'd like for the <code>a</code> link to cancel navigation, but fire the AJAX function?</p> <p>In that case:</p> <pre><code>$("#mylink").click(function() { $.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) { $("#response").html(data); }); return false; }); </code></pre>
How to access an Access database using JavaScript? <p>I have to display marks of my students through my site. The database is created using <a href="http://en.wikipedia.org/wiki/Microsoft_Access" rel="nofollow">Microsoft Access</a>. How can I display the marks of each student in a table, as they enter the registration number?</p>
<p>Why do you want to use Javascript? It runs in the browser of the site's visitors, and even if there were a way to have it directly access a database (which there isn't), it would be a horrible security risk, since it would have to contain the DB password, so that each visitor of the site could get full access to the DB.</p> <p>What you need is something that runs on the server and accesses the DB to deliver different pages to the visitor depending on data entered in an HTML form. Typical languages used for this are PHP, Perl, Ruby or ASP.</p> <p>Also note that MS Access is a very poor choice as a DB backend to a web app since it does not support concurrent access from different users.</p> <p>All in all it looks like you need more direct help than this site can provide; try finding a web app specialist in your area.</p>
How to go to main stack <p>I am using alternate stack to handle signals for program in C over linux. When stack overflow occurs, my signal are delivered on to my alternate signal stack not on the main stack.</p> <p>So in this situation I want to dump the <strong>main</strong> stack.... how can I ?</p>
<p>remember the top stack address in main (&amp; of some local variable in that stack frame), and dump from the exception address to that. Be aware, that there are some portability issues (stack grows upward on hp-pa-risc, for example). If the failure was not due to an access into the protected area below the overflowing stack, you have to look at the exception info for the sp which was valid before the signal. The exception info is passed as argument to the signal handler. Again, this is likely to be very cpu and os specific (varies among all unices).</p> <p>regards </p>
internal constructor <p>Yesterday I thought it would be nice to implement my own Trigger in a WPF app. I created a class MyTrigger which inherited TriggerBase. TriggerBase is a public abstract class. So inheritance isn't a problem. But the constructors inside this class are marked internal. The compiler throws an error because the is no valid constructor. Why does anyone create a public class but marks the constructors as internal?</p>
<p>If you want the class to be visible, but only allow it to be subclassed within your own assembly. The subclasses may have public constuctors themselves - or they may be accessed with a factory.</p> <p>I can't comment on whether that's a good design decision for TriggerBase in WPF, but it's at least reasonable in some situations.</p>
Visual Studio 2005 -> 2008/10 Service Installer Project Upgrade issue <p>I've upgraded a [.vdproj MSI generator project built into VS2008] System.Configuration.Install.Installer with a <code>ServiceProcessInstaller</code> and a <code>ServiceInstaller</code> from Visual Studio 2005 to 2008. There are no customisations of consequence to the installer class (i.e., not trying to start or stop services or register children)</p> <p><code>RemovePreviousVersions</code> is set to <code>true</code>, and I'm changing the <code>Version</code> and <code>ProductCode</code>. This triggers an error during the install:</p> <p>"error 1001: the specified service already exists"</p> <p>Googling yields stuff (but not on SO until now):- <a href="http://www.google.ie/search?hl=en&amp;q=%22error+1001%3A+the+specified+service+already+exists%22&amp;meta=" rel="nofollow">Google for "The specified service already exists"</a><br> The most useful one I've seen to date is <a href="http://forums.msdn.microsoft.com/en-US/winformssetup/thread/b2d1bd22-8499-454e-9cec-1e42c03e2557/" rel="nofollow">http://forums.msdn.microsoft.com/en-US/winformssetup/thread/b2d1bd22-8499-454e-9cec-1e42c03e2557/</a> however this doesn't answer the fundamental question:-</p> <p>Given that the user can pick either:<br> a) an install location that's the same<br> or b) an install location that's different<br> what are the minimal code changes would one sensibly make to ensure that the old service gets uninstalled and the new one gets installed? Or is there something other than a code change required to resolve this for the basic scenario of upgrading v1.0.1 to v1.0.2 of the same service with the same name (i.e., signing)</p> <p>(AIUI the strong naming only comes into play if one has a significant uninstall step in the old installer that you dont have in the new one.)</p> <p>I generated a new installer in VS 2008 and it fares no better.</p> <p>For now, my workaround is to stop updating the <code>Version</code> and <code>ProductCode</code>, forcing the user to manually uninstall when they are told they already have a version installed.</p> <p>Addendum thanks to <a href="http://stackoverflow.com/users/40347/divo">divo's</a> probing: While the simplest hack that could possibly work is to say "if install step is called &amp; its an upgrade, call the uninstall step for the service first", I'd like a proper officially blessed answer! (e.g., how does the simple hack cope when the service is being renamed during an upgrade?)</p>
<p>This should answer your question</p> <p><a href="http://stackoverflow.com/questions/451573/how-do-i-eliminate-the-specified-service-already-exists-when-i-install-new-versio/617385">http://stackoverflow.com/questions/451573/how-do-i-eliminate-the-specified-service-already-exists-when-i-install-new-versio/617385</a></p>
Auto Install activeX <p>I'm a web developer and my current task is to build an ActiveX component. </p> <p>It's the first time I have to work with ActiveX and I managed to make an working example.</p> <p>However I cannot make the ActiveX install from a browser. When installing it using visual studio 2008 and running the web page all works as expected, when I don't have it installed I would expect something similar to windows updates asking me if I allow the installation but this does not happen....</p> <p>Here is how I'm placing it in the web page:</p> <pre><code>&lt;object id="myActiveX" name="myActiveX" classid="clsid:A68B19C8-9DB4-49e4-912F-37FB44968528" codebase="http://localhost/myWebSite/install.cab#version=1,0,0,0"&gt;&lt;/object&gt; </code></pre> <p>The guid in the classId matches the guid I created for my class.</p> <p>Can anyone point out what I'm missing? </p> <p>Edit:</p> <p>Forgot to mention this, I have a Setup Project for my ActiveX that generates an .msi and an Setup.exe</p> <p>i have made a cab file with those using a .inf file as so:</p> <pre><code>[version] signature="$CHICAGO$" AdvancedINF=2.0 [Setup Hooks] hook1=hook1 [hook1] run=msiexec.exe /i %EXTRACT_DIR%\Install.msi /qf </code></pre>
<p>You might want to check your IE security settings: By default, unsigned ActiveX controls are ignored.</p> <p>Here's another possibility:</p> <p>Did you mark your control as "Safe for scripting" and "safe for initialization"?</p> <p>I'm not sure this is the issue you're running into since 1) your sample HTML code doesn't show that you're using the control in a script and 2) said HTML snippet doesn't show that you set control properties. However this is a usual trap so if I were you, I'd give a look.</p> <p>IIRC this can be achieved either by implementing the <a href="http://msdn.microsoft.com/en-us/library/aa768224.aspx" rel="nofollow">IObjectSafety</a> interface or using registry settings.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa751977(VS.85).aspx" rel="nofollow">This</a> and this are 2 pointers to get you started.</p>
is it possible to set per-file options for Nedit like you can do for emacs/vim <p>With VIM or Emacs I can put comments in the file that will be VIM's settings for that file:</p> <p><code></p> <pre> /* * Local Variables: * mode: C * c-basic-offset: 4 * c-indentation-style: linux * indent-tabs-mode: nil * default-tab-width: 8 * fill-column: 125 * End: * * vim: et:sw=4:ts=8:si:cindent:cino=\:0,g0,(0: */ </code> </pre> <p>Can the same be done with Nedit?</p>
<p>The short answer is, sadly, no.</p> <p>The longer answer is (as I'm sure you're aware) yes if you wrap the call to nedit in a shell script. The script would need to look at the head of the file you're trying to open for information concerning settings. You could then spit this information out to a file and use the "--import" option to load those settings into nedit.</p> <p>Hope this helps a little.</p> <p>Rob</p>
How to create a file without a Command Prompt window <p>I'm using WinRAR SFX module to create an installation, and use its presetup option to run some preliminary tests.</p> <p>Since wscript can only accept vbs file, and not the script itself, I first run "cmd /c echo {...script code...} > setup.vbs", and then I run "wscript setup.vbs". The run of the first cmd command opens a brief command window, and I would really like to avoid this. I thought of using RunDll32 to write this data, but couldn't find any suitable API to use.</p> <p>Can anyone think of a way to bypass it and create a small file with a small VBScript text without opening a Command Prompt window?</p> <p>Thanks a lot,</p> <p>splintor</p>
<p>Is the script code already in a file? If so,</p> <p>You can use the TYPE command to send the script to a file:</p> <pre><code>TYPE [script_file] &gt; setup.vbs </code></pre> <p>or COPY the script file:</p> <pre><code>COPY [script_file] setup.vbs </code></pre> <p>If the script code is in the body of your <code>cmd</code>, you can use the <code>START</code> command to run the <code>cmd</code> without a window (<code>/b</code> flag):</p> <pre><code>START /B cmd /c echo {...script code...} &gt; setup.vbs </code></pre>
Use type of object in HQL where clause <p>In my domain model I have an abstract class CommunicationChannelSpecification, which has child classes like FTPChannelSpecification, EMailChannelSpecification and WebserviceChannelSpecification. Now I want to create an HQL query which contains a where clause that narrows down the result to certain types of channel specifications. E.g. (in plain English) select all CommunicationChannelSpecifications that whose types occur in the set {FTPChannelSpecification, WebserviceChannelSpecification}.</p> <p>How can this be achieved in HQL? I'm using NHibernate 2.0.1 and a table per subclass inheritance mapping strategy...</p> <p>Thanks!</p> <p>Pascal</p>
<p>Not positive in NHibernate, but in Hibernate, there are two special properties that are always referenced id and class. So, for your particular case, I'd do</p> <pre><code>from CommunicationChannelSpecifications spec where spec.class in (?) </code></pre>
loadVideoById() in YouTube's regular player (not chromeless) <p>I have a YouTube's player in the webpage. I need to change the video played by this player dynamicaly.</p> <p>This is (relatively) easy using YouTube's chromeless player. It has method <a href="http://code.google.com/apis/youtube/chromeless_player_reference.html#loadVideoById"><code>loadVideoById()</code></a> which works perfectly. The problem is, that the chromeless player doesn't have any controls (play/pause, etc.). The <a href="http://code.google.com/apis/youtube/js_api_reference.html#Functions">regular YouTube player</a> has all this, but it doesn't have the <code>loadVideoById()</code> method.</p> <p>Is there any way to include the controls of regular player into chromeless player, or to implement <code>loadVideoById()</code> method in the regular player?</p> <p>Thanks.</p>
<p>You can not do that, cause the calls in the "regular youtube player" have the VideoID in the URL instead as a parameter:</p> <ul> <li>Regular Video: <a href="http://www.youtube.com/v/VIDEO_ID&amp;enablejsapi=1&amp;playerapiid=ytplayer">http://www.youtube.com/v/VIDEO_ID&amp;enablejsapi=1&amp;playerapiid=ytplayer</a></li> <li>Chromeless: <a href="http://www.youtube.com/apiplayer?enablejsapi=1">http://www.youtube.com/apiplayer?enablejsapi=1</a></li> </ul> <p>Instead of that you can easily create your own function that changes the Embbebed SWF, i mean, say that you are using <a href="http://code.google.com/p/swfobject/">swfobject</a> for the "Regular Player", then using <a href="http://code.google.com/p/swfobject/wiki/api#swfobject.createSWF(attObj,_parObj,_replaceElemIdStr)">createSWF function</a> you will be able to replace the previous video for the actual one dynamically.</p> <p>Hope this help you.</p>
How do I convert NSDecimalNumber to NSInteger? <p>OK, I'm using a JSON-enabled Rails web-service to provide data to an iPhone application. I'm finding my Integer values (IDs) are being interpreted by the json-framework as a NSDecimalNumber type. I need it as an integer. How can I get an integer value out of my NSDecimalNumber typed variable? I have tried everything I know, and I'm at my wits end.</p>
<p>I'm not sure about JSON, but:</p> <p>NSDecimalNumber inherits from NSNumber, so you could just use the NSNumber's -integerValue method.</p> <p>Requires 10.5, but shouldn't be an issue.</p>
Find Programming Language Used <p>Whats the easiest way to find out what programming language an application was written in? I would like to know if its vb or c++ or delphi or .net etc from the program exe file.</p>
<p>Try <a href="http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml">PEiD</a></p> <p>of course if they used a packer, some unpacking will need to be done first :)</p>
Oracle SQL - Parsing a name string and converting it to first initial & last name <p>Does anyone know how to turn this string: "Smith, John R"<br> Into this string: "jsmith" ?</p> <p>I need to lowercase everything with lower()<br> Find where the comma is and track it's integer location value<br> Get the first character after that comma and put it in front of the string<br> Then get the entire last name and stick it after the first initial.<br><br> Sidenote - instr() function is not compatible with my version<br><br> Thanks for any help!</p>
<p>Start by writing your own INSTR function - call it my_instr for example. It will start at char 1 and loop until it finds a ','.</p> <p>Then use as you would INSTR.</p>
Entities and calculated properties <p>What is the best practice to implement the following:</p> <ol> <li>we have a classes <code>Order</code> and <code>OrderItem</code> as parent-child. </li> <li>Class <code>OrderItem</code> provides property <code>Cost</code></li> <li>On the OrdersList form we have to see <code>MaxCost</code> column = max(cost) from <code>Items</code> collection</li> </ol> <p>I found only one useful solution here which won't break the DDD concepts: to add a usual property <code>MaxCost</code> to the class <code>Order</code> and to update it each time when items list updates.</p> <p>Is there another way?</p>
<p>Probably, but you have to ask yourself "why?". From the standpoint of the domain, does it "care" if you are recomputing this repeatedly? Or are you letting programmer-domain creep into your problem domain?</p> <p>One other thing --- consider making "max cost of items" part of the collection of OrderItems, and hiding HOW you get it from the rest of the system.</p>
Best solution for turning a website into a pdf <p>The company I work for we have a CBT system we have developed. We have to go through and create books out of the content that is in our system, I have developed a program that goes through and downloads all of the content out of our system and creates a offline version of the different training modules.</p> <p>I created a program that creates PDF documents using the offline version of the CBT. It works by using Websites Screenshot to create a screen shot of the different pages and then using iTextSharp it creates a PDF Document from those images.</p> <p>It seams to be a memory hug and painfully slow. There are 40 CBT Modules that it needs to turn into books. Even though I take every step to clear the memory after each time it creates a book. After about 2 books it crashes because there is no memory left.</p> <p>Is there a better way to do this instead of having to take a screen shot of the pages that will yield the same look of the web page inside the pdf document?</p>
<p>I have searched and demoed and found that <a href="http://www.websupergoo.com/abcpdf-1.htm" rel="nofollow">ABCPdf from WebSuperGoo</a> is the best product for .NET. It is the most accurate and doesn't require a printer driver. It uses IE as the rendering engine, so it looks almost exactly like what you get in IE.</p>
What are "unstacked calls in outer" in Perl's Devel::DProf? <p>I am profiling a Perl application with <code>perl -d:DProf</code>. When running <code>dprofpp</code> on the resulting <code>tmon.out</code> file, I get warnings like these:</p> <pre><code>Compress::Zlib::__ANON__ has 5 unstacked calls in outer Compress::Zlib::AUTOLOAD has -5 unstacked calls in outer </code></pre> <ul> <li>What is an unstacked call?</li> <li>Who or what is "outer"?</li> <li>What do the numbers mean? How can there be a negative number of calls?</li> <li>Should I worry?</li> </ul>
<p>I'll give this a shot:</p> <ul> <li>Unstacked calls indicate that when DProf was analyzing the profile, it encountered more (or fewer) calls on the stack (in the profile) than it expected to, meaning that the profiling data is incorrect.</li> <li>"outer" refers to the internal variable <code>%outer</code> in DProf, which (apparently) tracks the stack counts when analyzing a profile.</li> <li>The numbers indicate how many calls DProf expected to find versus how many it found. 5 means that there are more calls than it expected, -5 means there are 5 fewer. Again, this is because the profile data is corrupt.</li> <li>I wouldn't worry about your code integrity, because AFAIK this is due to bugs in the implementation of DProf itself. It seems DProf got confused when writing the <code>tmon.out</code> file. However, the rest of the results from <code>dprofpp</code> may be unreliable due to this inaccuracy. So, you should worry (a little) about the accuracy of those results.</li> </ul> <p>You may want to look into alternate profiling module, like <a href="http://search.cpan.org/dist/Devel-NYTProf/" rel="nofollow">Devel::NYTProf</a></p>
How do I do "svn st" in AnkhSVN for Visual Studio? -no text- <p>Just installed AnkhSVN and I see the equivalent of "svn up" but I'd prefer to run "svn st" first so that I don't just blindly update.</p>
<p>The next release of AnkhSVN will enable the 'Recent Changes' tab in the pending changes window. This allows the equivalent of 'svn st -u' (It shows outgoing and incoming changes).</p> <p>We are still working on the usability of this view in the <a href="http://ankhsvn.net/daily/" rel="nofollow">daily builds. </p> <p>Input welcome on the AnkhSVN users</a> list.</p>
.Net XmlWriter - unexpected encoding is confusing me <p>Environment is VS2008, .Net 3.5</p> <p>The following C# code (note the specified encoding of UTF8)</p> <pre><code>XmlWriterSettings settings = new XmlWriterSettings (); StringBuilder sb = new StringBuilder(); settings.Encoding = System.Text.Encoding.UTF8; settings.Indent = false; settings.NewLineChars = "\n"; settings.ConformanceLevel = System.Xml.ConformanceLevel.Document; XmlWriter writer = XmlWriter.Create (sb, settings); { // Write XML data. writer.WriteStartElement ("CCHEADER"); writer.WriteAttributeString ("ProtocolVersion", "1.0.0"); writer.WriteAttributeString ("ServerCapabilities", "0x0000000F"); writer.WriteEndElement (); writer.Flush (); } </code></pre> <p>Actually generates the XML (>&lt; omitted because SO barfs on them):</p> <p>?xml version="1.0" encoding="utf-16"?<br> CCHEADER ProtocolVersion="1.0.0" ServerCapabilities="0x0000000F" /</p> <p>Why do I get the wrong encoding generated here ? What am I doing wrong ?</p>
<p>I suspect it's because it's writing to a StringBuilder, which is inherently UTF-16. An alternative to get round this is to create a class derived from StringWriter, but which overrides the Encoding property.</p> <p>I believe I've got one in <a href="http://pobox.com/~skeet/csharp/miscutil">MiscUtil</a> - but it's pretty trivial to write anyway. Something like this:</p> <pre><code>public sealed class StringWriterWithEncoding : StringWriter { private readonly Encoding encoding; public StringWriterWithEncoding (Encoding encoding) { this.encoding = encoding; } public override Encoding Encoding { get { return encoding; } } } </code></pre>
What is MSXML2.ServerXMLHTTP's default Content-Type? <p>In my <a href="http://stackoverflow.com/questions/369226/receiving-xml-from-another-websites-call-to-serverxmlhttp-post-in-classic-asp">previous question</a>, I was accidentally sending token/value pairs with an <code>text/xml</code> Content-Type which resulted in nothing being sent. Tim C's insight into that problem was extremely helpful. Thanks again, Tim!</p> <p>Looking back at the original sending code, I now realize that the setting of the <code>ServerXMLHTTP</code>'s Content-Type to <code>text/xml</code> was a recent and erroneous addition. The sending code I posted in my question looked like this:</p> <pre><code>url = "www.receivingwebsite.com\asp\receivingwebpage.asp" information = "UserName=Colt&amp;PassWord=Taylor&amp;Data=100" Set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP") xmlhttp.Open "POST", url, false xmlhttp.setRequestHeader "Content-Type", "text/xml" xmlhttp.send information </code></pre> <p>The actual sending code is really:</p> <pre><code>url = "www.receivingwebsite.com\asp\receivingwebpage.asp" information = "UserName=Colt&amp;PassWord=Taylor&amp;Data=100" Set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP") xmlhttp.Open "POST", url, false xmlhttp.send information </code></pre> <p>...with no attempt to set the Content-Type before sending.</p> <p>Unfortunately, the problem that originally lead me to ask for help still exists. My receiving classic asp page cannot see the information which is being posted by the <code>ServerXMLHTTP</code> object. The information is not in the request object's <code>querystring</code> or the <code>form</code> array. No matter what I do, I can't find the information but I know that it is being sent because when I change the content-type to <code>application/x-www-form-urlencoded</code>, I can see it in <code>request.form</code> array.</p> <p>So what is the default content-type of the <code>MSXML2.ServerXMLHTTP</code> class? And where is my information when the sending class is using that default content-type?</p> <p>Thanks in advance for any assistance! Peace, Colt Taylor</p>
<p>ASP will only fill the form array if the content type of the POST is "application/x-www-form-urlencoded". Generally ServerXMLHTTP will not set the content type header so if you don't do it manually no content type header is sent.</p> <p>An exception to this is where you pass an XML Document as the parameter to send, in that case ServerXMLHTTP will set content type to "text/xml; charset=UTF-8".</p>
How to Save Record to Relational Tables With Linq To Sql <p>I have three tables like that:</p> <p><strong>Articles</strong> IdArticle Title Content</p> <p><strong>Tags</strong> IdTag TagName</p> <p><strong>ContentTag</strong> IdContentTag Idtag IdContent</p> <p>When user in my site write an article with adding tags and submit, I want to save it to tables above. </p> <p>In traditional ways, I used to use transaction and I could do it. But How can I do it by using linq to sql?</p>
<p>I think you're looking for something like this.</p> <p><a href="http://hookedonlinq.com/LINQtoSql5MinuteOverview.ashx" rel="nofollow">http://hookedonlinq.com/LINQtoSql5MinuteOverview.ashx</a></p>
Tables vs CSS for positioning and design <p><b>Duplicate: <a href="http://stackoverflow.com/questions/30251/tables-instead-of-divs#30271"><a href="http://stackoverflow.com/questions/30251/tables-instead-of-divs#30271">Tables instead of DIVs</a></a> and <a href="http://stackoverflow.com/questions/83073/div-vs-table#83121"><a href="http://stackoverflow.com/questions/83073/div-vs-table#83121">Why not use tables for layout in HTML?</a></a></b></p> <p>I am working on building a web app using ASP .NET MVC (needs to run on IE 7, FF 3.0), does it matter if I were to use tables rather than css for positioning and design?</p> <p><br /> As a developer I haven't had a chance to work with css. </p>
<p>Yes, it matters. The most convincing argument that I've used in favor of CSS over tables is that screen readers (for the visually impaired) trip over tabular layout. That's a good argument by itself, but it gets a whole lot better when you take into account the fact that <em>Google reads your web site just like a screen reader would</em>. If you want Google to have an easier time indexing your site, use CSS for layout. Tables are for tabular data.</p>
Reliable way to see process-specific perf statistics on an IIS6 app pool <p>In perfmon in Windows Server 2003, there are counter objects to get per-process processor time and memory working set statistics. The only problem is that in an environment with multiple application pools, there is no way to reliably identify the correct worker process. In perfmon, they are all called "w3wp", and if there is more than one, they are w3wp, w3wp#1, w3wp#2, and so on. Even these names are unreliable - the number depends on which one started first, and obviously changes when an app pool is recycled because the process is destroyed and restarted.</p> <p>I haven't found any ASP.NET-specific counters, and for some reason, my IIS object doesn't separate instances - there's only one "global" instance.</p> <p>Ultimately, I just want the "% Processor Time" and "Working Set" counters for a specific IIS App Pool. Any suggestions?</p>
<p>We'd always collect the stats for all the w3wp processes, and we would capture PID. This is one of the counters in the Process group.</p> <p>There's a script that site in Server 2003's system32 folder called IISApp.vbs, that will list all the processes and their PIDs. You will need to run this to capture the PID's.</p> <p>I'm sure there has to be a better way but this worked when we needed to do adhoc monitoring.</p>
C# COM DLL: do I use Regasm, or Regsvr32? <p>I am building a C# ActiveX DLL... do I use REGASM or REGSVR32 to register it?</p> <p>How do I register the 64-bit interface vs the 32-bit interface?</p>
<p>You need to use <a href="http://msdn.microsoft.com/en-us/library/tzat5yw6%28v=vs.80%29.aspx"><code>regasm.exe</code></a> to register both the 32 bit and 64 bit interfaces I believe you need to run each of the <code>regasm.exe</code>'s in:</p> <pre><code>C:\Windows\Microsoft.NET\Framework\v2.0.50727 </code></pre> <p>and</p> <pre><code>C:\Windows\Microsoft.NET\Framework64\v2.0.50727 </code></pre> <p>So... in your case you need to run the <code>regasm.exe</code> in the <code>Framework64\v2.0.50727</code> folder.</p> <p>Here's an example we use to register a COM interop DLL for one of our legacy ASP apps:</p> <pre><code>regasm.exe Hosting.DeviceManager.Power.dll /register /codebase /tlb </code></pre>
.NET Processing spawning issues <p>I have an executable that runs instantly from a command prompt, but does not appear to ever return when spawned using System.Diagnostics.Process:</p> <p>Basicly, I'm writing a .NET library wrapper around the Accurev CLI interface, so each method call spawns the CLI process to execute a command.</p> <p>This works great for all but one command:</p> <pre><code> accurev.exe show depots </code></pre> <p>However, when running this from a console, it runs fine, when I call it using a .net process, it hangs...The process spawning code I use is:</p> <pre><code> public static string ExecuteCommand(string command) { Process p = createProcess(command); p.Start(); p.WaitForExit(); // Accurev writes to the error stream if ExitCode is non zero. if (p.ExitCode != 0) { string error = p.StandardError.ReadToEnd(); Log.Write(command + " failed..." + error); throw new AccurevException(error); } else { return p.StandardOutput.ReadToEnd(); } } /// Creates Accurev Process /// &lt;/summary&gt; /// &lt;param name="command"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static Process createProcess(string command) { Log.Write("Executing Command: " + command); ProcessStartInfo startInfo = new ProcessStartInfo(); Process p = new Process(); startInfo.CreateNoWindow = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.Arguments = command; startInfo.FileName = _accurev; p.StartInfo = startInfo; return p; } </code></pre> <p>It hangs at p.WaitForExit().</p> <p>Any advice?</p> <p><strong>EDIT</strong>: Solved!</p> <p>.NET Process's hang if the output buffer overflows, I switched to using an asynchronous read method and everything works:</p> <pre><code> public static string ExecuteCommand(string command) { StringBuilder outputData = new StringBuilder(); Process p = createProcess(command); p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { outputData.AppendLine(e.Data); }; p.Start(); p.BeginOutputReadLine(); p.WaitForExit(); // Accurev writes to the error stream if ExitCode is non zero. if (p.ExitCode != 0) { string error = p.StandardError.ReadToEnd(); Log.Write(command + " failed..." + error); throw new AccurevException(error); } else { return outputData.ToString(); } } </code></pre>
<p>It is seeking for input? In particular, I notice that you are redirecting stdin, but not closing it - so if it is reading from stdin it will hang.</p>
Best practice for graceful replace of read-only SQL Server database <p>I have a read-only database that has cached information which is used to display pages on the site. There are processes that run to generate the database, and those run on a different server. When I need to update the live database, I restore this database to the live server, to a new name and file. Then I drop the live database and rename this one to the original name. Currently I do this with a stored procedure, that kills all connections via 'sp_who' and 'kill', then the drop database command, then 'sp_renamedb'. Now when I kill all connections it will throw an error on the site for people and crawlers currently accessing those pages, is there a better methodology for performing this procedure?</p>
<p>Probably what you want to do is take the live database offline with the command:</p> <pre><code>ALTER DATABASE name SET OFFLINE </code></pre> <p>You can read more <a href="http://www.blackwasp.co.uk/SQLOffline.aspx" rel="nofollow">here</a>, but it says:</p> <blockquote> <p>The above command attempts to take the named database off-line immediately. If a user or a background process is currently connected to the database the command cannot be completed. In this situation, the ALTER DATABASE statement will be blocked and will wait until all connections are closed. This ensures that no transactions are rolled back unexpectedly. During the period of blocking, no new connections to the database will be permitted.</p> </blockquote> <p>Once the database is offline, you should be able to do your restore/rename operations safely and bring it back online when done. You might have to do some playing around to see what is permitted while the database is in the offline state.</p> <p>If you have trouble doing the restore/rename while it's offline, you'll want to bring it back online in single user mode.</p> <p>Connection pooling or other long-running connections may cause problems in this scenario. You may want to set up a script to wait for a period of time after the ALTER DATABASE SET OFFLINE command has been issued (say 15 minutes), and if the database is still not offline yet, you can reissue the command with the WITH NO_WAIT option to force it offline.</p> <p>If that isn't high-powered enough for you, you can also gracefully shutdown SQL Server...that will also wait until all work in the server is done before stopping.</p>
Generics, arrays, and the ClassCastException <p>I think there must be something subtle going on here that I don't know about. Consider the following:</p> <pre><code>public class Foo&lt;T&gt; { private T[] a = (T[]) new Object[5]; public Foo() { // Add some elements to a } public T[] getA() { return a; } } </code></pre> <p>Suppose that your main method contains the following:</p> <pre><code>Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); Double[] d = f.getA(); </code></pre> <p>You will get a CastClassException with the message java.lang.Object cannot be cast to java.lang.Double.</p> <p>Can anyone tell me why? My understanding of ClassCastException is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:</p> <pre><code>Object o = new Double(3.); Double d = (Double) o; // Working cast String s = (String) o; // ClassCastException </code></pre> <p>And it seems I can do this. If <code>a</code> was just a <code>T</code> instead of an array <code>T[]</code>, we can get <code>a</code> and cast it without a problem. Why do arrays break this?</p> <p>Thanks.</p>
<pre><code>Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); </code></pre> <p>When you use this version of the generic class Foo, then for the member variable <code>a</code>, the compiler is essentially taking this line:</p> <pre><code>private T[] a = (T[]) new Object[5]; </code></pre> <p>and replacing <code>T</code> with <code>Double</code> to get this:</p> <pre><code>private Double[] a = (Double[]) new Object[5]; </code></pre> <p>You cannot cast from Object to Double, hence the ClassCastException.</p> <p><strong>Update and Clarification:</strong> Actually, after running some test code, the ClassCastException is more subtle than this. For example, this main method will work fine without any exception:</p> <pre><code>public static void main(String[] args) { Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); System.out.println(f.getA()); } </code></pre> <p>The problem occurs when you attempt to assign <code>f.getA()</code> to a reference of type <code>Double[]</code>:</p> <pre><code>public static void main(String[] args) { Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); Double[] a2 = f.getA(); // throws ClassCastException System.out.println(a2); } </code></pre> <p>This is because the type-information about the member variable <code>a</code> is erased at runtime. Generics only provide type-safety at <em>compile-time</em> (I was somehow ignoring this in my initial post). So the problem is not </p> <pre><code>private T[] a = (T[]) new Object[5]; </code></pre> <p>because at run-time this code is really</p> <pre><code>private Object[] a = new Object[5]; </code></pre> <p>The problem occurs when the result of method <code>getA()</code>, which at runtime actually returns an <code>Object[]</code>, is assigned to a reference of type <code>Double[]</code> - this statement throws the ClassCastException because Object cannot be cast to Double.</p> <p><strong>Update 2</strong>: to answer your final question "why do arrays break this?" The answer is because the language specification does not support generic array creation. <a href="http://forums.sun.com/thread.jspa?threadID=530823">See this forum post for more</a> - in order to be backwards compatible, nothing is known about the type of T at runtime.</p>
How would someone download a website from Google Cache? <p>A friend accidentally deleted his forum database. Which wouldn't normally be a huge issue, except for the fact that he neglected to perform backups. 2 years of content is just plain gone. Obviously, he's learned his lesson.</p> <p>The good news, however, is that Google keeps backups, even if individual site owners are idiots. The bad news is, that traditional crawling robots would choke on the Google Cache version of the website. </p> <p>Is there anything existing that would help trawl the Google Cache, or how would I go about rolling my own?</p>
<p>You may want to consider looking at crawling the archive.org cache as well. If you're in there, it's generally better structured.</p>
.net 2.0 sp1 on Windows 98 <p>I've been searching around for this and cannot seem to find a solid answer. I know the 2.0 version of the .net framework is supported in Windows98, but does that include SP1? </p>
<p>It seems that the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&amp;displaylang=en" rel="nofollow">Microsoft .NET Framework Version 2.0 Redistributable Package (x86)</a> supports Windows 98:</p> <p>Supported Operating Systems: Windows 2000 Service Pack 3; Windows 98; Windows 98 Second Edition; Windows ME; Windows Server 2003; Windows XP Service Pack 2</p> <p>But <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=79BC3B77-E02C-4AD3-AACF-A7633F706BA5&amp;displaylang=en" rel="nofollow">Microsoft .NET Framework 2.0 Service Pack 1 (x86)</a> does not:</p> <p>Supported Operating Systems: Windows 2000 Service Pack 4; Windows Server 2003; Windows XP Service Pack 2</p>
How can I split a string into chunks of two characters each in Perl? <p>How do I take a string in Perl and split it up into an array with entries two characters long each?</p> <p>I attempted this:</p> <pre><code>@array = split(/../, $string); </code></pre> <p>but did not get the expected results.</p> <p>Ultimately I want to turn something like this</p> <pre><code>F53CBBA476 </code></pre> <p>in to an array containing</p> <pre><code>F5 3C BB A4 76 </code></pre>
<pre><code>@array = ( $string =~ m/../g ); </code></pre> <p>The pattern-matching operator behaves in a special way in a list context in Perl. It processes the operation iteratively, matching the pattern against the remainder of the text after the previous match. Then the list is formed from all the text that matched during each application of the pattern-matching.</p>
Why is "array" marked as a reserved word in Visual-C++? <p>Visual Studio syntax highlighting colors this word blue as if it were a keyword or reserved word. I tried searching online for it but the word "array" throws the search off, I get mostly pages explaining what an array is. What is it used for?</p>
<p>It's not a reserved word under ISO standards. Microsoft's <a href="http://en.wikipedia.org/wiki/C%2B%2B/CLI">C++/CLI</a> defines <a href="http://msdn.microsoft.com/en-us/library/ts4c4dw6(VS.85).aspx">array</a> in the <a href="http://msdn.microsoft.com/en-us/library/d87eee3k(VS.85).aspx">cli namespace</a>, and Visual Studio's syntax highlighting will treat it as a reserved word. This usage would be considered a vendor extension and not a part of any international C or C++ standard.</p> <p><a href="http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf">ISO C99</a> Keywords:</p> <pre> auto enum restrict unsigned break extern return void case float short volatile char for signed while const goto sizeof _Bool continue if static _Complex default inline struct _Imaginary do int switch double long typedef else register union </pre> <p>ISO C++98 Keywords:</p> <pre> and double not this and_eq dynamic_cast not_eq throw asm else operator true auto enum or try bitand explicit or_eq typedef bitor export private typeid bool extern protected typename break false public union case float register unsigned catch for reinterpret_cast using char friend return virtual class goto short void compl if signed volatile const inline sizeof wchar_t const_cast int static while continue long static_cast xor default mutable struct xor_eq delete namespace switch do new template </pre>
Two 'self-updating' properties in WPF MVVM <p>Considering you have an MVVM Architecture in WPF like <a href="http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/" rel="nofollow">Josh Smith's examples</a></p> <p>How would you implement two properties 'synced' that update eachother? I have a Price property, and a PriceVatInclusive property in my model. </p> <p>-When the Price changes, I want to see the Vat inclusive price to automatically be 'Price * 1.21'. </p> <p>-Vice versa, when the PriceVatInclusive changes, I want the Price to be 'PriceVatInclusive / 1.21'</p> <p>Any ideas on that?</p> <p>And what if your model is a Entity framework entiry? You can't use the approach above then... no? Should you put calculating code in the ViewMOdel or ... ?</p>
<p>One way:</p> <pre><code> public class Sample : INotifyPropertyChanged { private const double Multiplier = 1.21; #region Fields private double price; private double vat; #endregion #region Properties public double Price { get { return price; } set { if (price == value) return; price = value; OnPropertyChanged(new PropertyChangedEventArgs("Price")); Vat = Price * Multiplier; } } public double Vat { get { return vat; } set { if (vat == value) return; vat = value; OnPropertyChanged(new PropertyChangedEventArgs("Vat")); Price = Vat / Multiplier; } } #endregion #region INotifyPropertyChanged Members protected void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler ev = PropertyChanged; if (ev != null) { ev(this, e); } } public event PropertyChangedEventHandler PropertyChanged; #endregion } </code></pre> <p>If you can derive from DependencyObject, you can use Dependency Properties.</p> <pre><code>public class Sample : DependencyObject { private const double Multiplier = 1.21; public static readonly DependencyProperty VatProperty = DependencyProperty.Register("Vat", typeof(double), typeof(Sample), new PropertyMetadata(VatPropertyChanged)); public static readonly DependencyProperty PriceProperty = DependencyProperty.Register("Price", typeof(double), typeof(Sample), new PropertyMetadata(PricePropertyChanged)); private static void VatPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { Sample sample = obj as Sample; sample.Price = sample.Vat / Multiplier; } private static void PricePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { Sample sample = obj as Sample; sample.Vat = sample.Price * Multiplier; } #region Properties public double Price { get { return (double)GetValue(PriceProperty); } set { SetValue(PriceProperty, value); } } public double Vat { get { return (double)GetValue(VatProperty); } set { SetValue(VatProperty, value); } } #endregion } </code></pre>
Get/Set in the c++ world, faux-pas? <p>I notice that get/set is not the c++ way as far as I can tell by looking at boost/stl, and even reading the writings of some of the top c++ experts.</p> <p>Does anyone use get/set in their c++ class design, and can someone suggest a rule of thumb on where if at all this paradigm belongs in the c++ world?</p> <p>It is obviously very popular in Java, and imitated by c# using Property syntactic sugar.</p> <p>EDIT:</p> <p>Well after reading more about this in one of the links provided in an answer below, I came across at least one argument for keeping the accessors of a member field the same name as the member field. Namely that you could simply expose the member field as public, and instead make it an instance of a class, and then overload the () operator. By using set/get, you'd force clients to not only recompile, but to actually change their code. </p> <p>Not sure I love the idea, seems a bit too fine grained to me, but more details are here:</p> <p><a href="http://www.kirit.com/C%2B%2B%20killed%20the%20get%20%26%20set%20accessors">C++ Killed the Getter/Setter</a></p>
<p>C++ does not have properties like C#. It is possible to write methods with "get" and "set" in the their names, but they don't automatically create properties. So is it good practice to use get and set methods then?</p> <p>Using get and set methods in C++ is not bad for accessing class properties. The STL and boost (which was influenced by the STL) just chose one design -- it's perfectly fine to have a different design for your classes.</p> <p>At my job, we do use get and set. The reason is primarily that it makes it possible to write parsers to automatically wrap the C++ classes by other interfaces -- ActiveX, .NET, LabVIEW, Python, etc.... When using Visual Studio's intellisence (and similar technologies on other IDEs), I find that using get and set methods makes finding what I was easier. So there are times where it is benefficial to use get and set methods.</p> <p>The most important thing is to choose a code style standard for your library and be consistent with it.</p>
Getting started with SLIME and SWANK: Lisp connection closed unexpectedly: connection broken by remote peer <p>I was trying to use the slime-connect function to get access to a remote server with sbcl. I followed all the steps from the slime.mov movie from <a href="http://www.guba.com/watch/30000548671">Marco Baringer,</a> but I got stuck when creating the ssh connection for slime. This is after already starting the swank server on the remote machine. I did it like this:</p> <p><code>ssh -L 4005:127.0.0.1:4005 user@server.com</code></p> <p>And I got this errors, on local SLIME: </p> <p>Lisp connection closed unexpectedly: connection broken by remote peer </p> <p>...and on the remote server: </p> <p>channel 3: open failed: connect failed: Connection refused</p> <p>What could possibly be wrong?</p>
<p>Have you checked that the version of SLIME and SWANK you use are the same? I've had odd things happening when I've used mismatched versions of those two halves of a SLIME session.</p>
Merging Visual Studio solution files <p>Microsoft Visual Studio (2005 and 2008) seems to have fun shuffling the Project IDs (GUIDs) around each time we do a little change in a solution. We found that this little detail leads to frustration each time someone has to merge branches in Source control...</p> <p>We though about coding a little tool to sort those Project ids before Check In. This way, merging would be easier. Is there some option that I missed in Visual Studio Options that would do just that?</p>
<p>Unfortunately it does not look good so far. </p> <p>See this question: <a href="http://stackoverflow.com/questions/372357/merging-vcproj-files-scms-hell#372448">http://stackoverflow.com/questions/372357/merging-vcproj-files-scms-hell#372448</a></p> <p>closed as this appears to be a duplicate.</p>
Adding event handlers by using reflection <p>I am adding dynamically controls to page by using LoadControl and Controls.Add. I need somehow to wrap Init and Load event handlers of this loaded controls into my code. So it should be such order of events <em>SomeMyCode() -> Control.Init() -> AnotherMyCode()</em> and the same for Load <em>SomeMyCode() -> Control.Load() -> AnotherMyCode()</em>.<br/> My idea was to Get List of Control's event handlers for Init and Load events and add first and last event handers with code I should to run. But I cannot figure out how to do this.</p>
<p>You <em>cannot</em> forcibly inject an event handler in front of other handlers already subscribed to an event. If you need method A to be called first, then you'll need to subscribe A first.</p> <p><hr /></p> <p>Re your comment, that is incredibly hacky. First, you can't even rely on an event having a delegate-field backer; it can be an <code>EventHandlerList</code> or other - which don't nevessarily expose handy hooks short of reversing the removal.</p> <p>Second (and more important), it breaks every rule of encapsulation.</p> <p>In general, if you want to be first, the <em>best</em> approach is to override the <code>OnFoo()</code> method. The second-best is to subscribe first.</p>
How do you databind to a System.Windows.Forms.Treeview control? <p>I'm looking at this control, and it seems to be lacking the standard .net "datasource" and "datamember" properties for databinding. Is this control not bindable? I can write some custom function that populates the treeview from a given data source, I suppose, and embed data objects as necessary, but is that the 'best practice'? Or does everyone simply use a 3rd party treeview control? </p>
<p>You are correct in that there is no data binding. The reason being is that TreeViews are hierarchical data structures. That is, not a straight list. As a result the databind option is invalid to say a List structure.</p> <p>Sadly it's creating your own populate methods or buying 3rd party controls (which in the end will have their own populate methods.)</p> <p>Here's a decent MSDN article on <a href="http://msdn.microsoft.com/en-us/library/aa478959.aspx" rel="nofollow">Binding Hierarchical Data</a>.</p>
PHP/CURL/Other - How resource intensive? <p>I am going to have a daemon that will run on a FreeBSD server, which will exchange small amounts of data with a list of URIs every minute.</p> <p>I am thinking to use the curl_multi functions to run them all at once, or in groups, every minute, using a post. I am open to other ideas though. </p> <p>I will have to do some benchmarking later on, but for now, does anyone know how resource intensive it is to make many small posts with curl? </p> <p>Is there a less intensive way to do this? SOAP perhaps? To start, there will only be a few every minute, but it may grow quickly.</p> <p>Thanks!</p>
<p>I'd say that SOAP processing (generating query, sending it, get it processed then getting answer back) may be more resource intensive than just a POST, even "multithreaded". Profiling or benchmarking is probably the only way to be sure anyway.</p>
Do you use the TR 24731 'safe' functions? <p>The ISO C committee (<a href="http://www.open-std.org/JTC1/SC22/WG14/">ISO/IEC JTC1/SC21/WG14</a>) has published <a href="http://www.open-std.org/JTC1/SC22/WG14/www/projects#24731-1">TR 24731-1</a> and is working on <a href="http://www.open-std.org/JTC1/SC22/WG14/www/projects#24731-1">TR 24731-2</a>:</p> <blockquote> <h3>TR 24731-1: Extensions to the C Library Part I: Bounds-checking interfaces</h3> <p>WG14 is working on a TR on safer C library functions. This TR is oriented towards modifying existing programs, often by adding an extra parameter with the buffer length. The latest draft is in document N1225. A rationale is in document N1173. This is to become a Technical Report type 2.</p> <h3>TR 24731-2: Extensions to the C Library - Part II: Dynamic allocation functions</h3> <p>WG14 is working on a TR on safer C library functions. This TR is oriented towards new programs using dynamic allocation instead of an extra parameter for the buffer length. The latest draft is in document N1337. This is to become a Technical Report type 2.</p> </blockquote> <h2>Questions</h2> <ul> <li>Do you use a library or compiler with support for the TR24731-1 functions?</li> <li>If so, which compiler or library and on which platform(s)?</li> <li>Did you uncover any bugs as a result of fixing your code to use these functions?</li> <li>Which functions provide the most value?</li> <li>Are there any that provide no value or negative value?</li> <li>Are you planning to use the library in the future?</li> <li>Are you tracking the TR24731-2 work at all?</li> </ul>
<p>I have been a vocal critic of these TRs since their inception (when it was a single TR) and would never use them in any of my software. They mask symptoms instead of addressing causes and it is my opinion that if anything they will have a negative impact on software design as they provide a false sense of security instead of promoting existing practices that can accomplish the same goals much more effectively. I am not alone, in fact I am not aware of a single major proponent outside of the committee developing these TRs.</p> <p>I use glibc and as such know that I will be spared having to deal with this nonsense, as Ulrich Drepper, lead maintainer for glibc, <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1106.txt">said about the topic</a>:</p> <blockquote> <p>The proposed safe(r) ISO C library fails to address to issue completely. ... Proposing to make the life of a programmer even harder is not going to help. But this is exactly what is proposed. ... They all require more work to be done or are just plain silly.</p> </blockquote> <p>He goes on to detail problems with a number of the proposed functions and has elsewhere indicated that glibc would never support this.</p> <p>The Austin Group (responsible for maintaining POSIX) provided a very critical review of the TR, their comments and the committee responses available <a href="http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1118.htm">here</a>. The Austin Group review does a very good job detailing many of the problems with the TR so I won't go into individual details here.</p> <p>So the bottom line is: I don't use an implementation that supports or will support this, I don't plan on ever using these functions, and I see no positive value in the TR. I personally believe that the only reason the TR is still alive in any form is because it is being pushed hard by Microsoft who has recently proved very capable of getting things rammed though standards committees despite wide-spread opposition. If these functions are ever standardized I don't think they will ever become widely used as the proposal has been around for a few years now and has failed to garner any real community support.</p>
.NET CF 2.0: possible single-threaded reentrancy <p>A simple application is written in CF 2.0. It's single-threaded as far as I'm concerned.</p> <p>Two parts of the application are of interest: an event handler that handles "Barcode scanned" event raised by a class that represents PDA's barcode scanner (provided by manufacturer), and an event handler for Windows.Forms.Timer that runs every 30 seconds.</p> <p>Recently the application suffered from a bug the only possible reason for which, as I can see, is processing Barcode Scanned event right in the middle of Timer_Tick event. I was absolutely sure that this was not possible and that one of the events would wait in the queue until first one is handled completely. Windows.Forms.Timer page in MSDN also assures that it's a regular single-threaded timer. Code triggered by Barcode Scanned changes some pieces of the interface, that causes no exceptions, so I'm assuming it's single-threaded as well. No, we're not using DoEvents or such.</p> <p>Can anybody tell me for sure that such reentrancy is not possible and I should look harder for other possible reasons, or vice versa, that they have suffered from the same problem?</p>
<p>The Windows.Forms timer is going to happen on the UI thread via a call to PostMessage. That is a guarantee. How the "barcode scanned" even comes in is completely up to the developer of the library that's giving you the event. You should certainly <strong>not</strong> assume that it's going to run in the same context as your timer unless you specifically force it to (via a call to Control.Invoke). Even with that I don't believe you can guaranteee a call order.</p> <p>If you think re-entrancy might be a cause, the solution is relatively simply - use a Monitor in both handlers (the timer proc and the event) and lock on the same object. That will rule out the possibility that it's a reentrancy issue. If the problem goes away, you know the cause and already have a fix. If the problem persists then you know for certain that it's not reentrancy and you can focus elsewhere.</p>
Finding the Current Active Window in Mac OS X using Python <p>Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?</p>
<p>This should work:</p> <pre><code>#!/usr/bin/python from AppKit import NSWorkspace activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] print activeAppName </code></pre> <p>Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while.</p> <p>If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.</p>
Check for column name in a SqlDataReader object <p>How do I check to see if a column exists in a <code>SqlDataReader</code> object? In my data access layer, I have create a method that builds the same object for multiple stored procedures calls. One of the stored procedures has an additional column that is not used by the other stored procedures. I want to modified the method to accommodate for every scenario.</p> <p>My application is written in C#.</p>
<p>In the accepted answer, using Exceptions for control logic is considered bad practice and has performance costs.</p> <p>Looping through the fields can have a small performance hit if you use it a lot and you may want to consider caching the results </p> <p>The more appropriate way to do this is:</p> <pre><code>public static class DataRecordExtensions { public static bool HasColumn(this IDataRecord dr, string columnName) { for (int i=0; i &lt; dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; } } </code></pre>
Simple (standalone) Java SOAP web service client from WSDL using Maven <p>I'm looking to generate a simple standalone Java client which will make calls to a SOAP web service, given a wsdl. When I say simple and standalone I mean that once I'm done I want to be able to do something like</p> <pre><code>import my.generated.nonsense; public static void main(String[] args) { Client client = new Client(); client.getSomething(); } </code></pre> <p>I've had great time recently with Maven on some other projects and I want to keep that going, so would aim to use it here. I don't want the tool to generate anything expect the classes that allow me to do the above.</p> <p>Anyone done this recently and can recommend a ws library and Maven plugin? Thanks.</p>
<p>Have a look at CXF and its Maven <a href="http://www.opendocs.net/apache/cxf/2.0/maven-integration-and-plugin.html" rel="nofollow">plug in</a>. CXF would generate code similar to yours (of course web services could fail and you should add exception handling). Have in mind though that SOAP web services is a complicated topic and simplicity in the generated code may not be always desirable. Generating a client with the default settings may not work for some clients. You would then need to tweak the configuration of the code generation and/or add code to handle it. CXF is good both for easy/default clients and more complicated ones.</p>
How do I get the UTC time of "midnight" for a given timezone? <p>The best I can come up with for now is this monstrosity:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone("Australia/Melbourne")) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0) </code></pre> <p>I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.</p> <p>I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.</p> <p>I can't help feeling I'm missing something, any ideas?</p>
<p>I think you can shave off a few method calls if you do it like this:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now(pytz.timezone("Australia/Melbourne")) \ .replace(hour=0, minute=0, second=0, microsecond=0) \ .astimezone(pytz.utc) </code></pre> <p>BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.</p> <p>The reason for this is that neither the datetime constructors nor <code>replace()</code> take DST changes into account.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; now = datetime(2012, 4, 1, 5, 0, 0, 0, tzinfo=pytz.timezone("Australia/Melbourne")) &gt;&gt;&gt; print now 2012-04-01 05:00:00+10:00 &gt;&gt;&gt; print now.replace(hour=0) 2012-04-01 00:00:00+10:00 # wrong! midnight was at 2012-04-01 00:00:00+11:00 &gt;&gt;&gt; print datetime(2012, 3, 1, 0, 0, 0, 0, tzinfo=tz) 2012-03-01 00:00:00+10:00 # wrong again! </code></pre> <p>However, the documentation for <code>tz.localize()</code> states:</p> <blockquote> <p>This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor.</p> </blockquote> <p>Thus, your problem is solved like so:</p> <pre><code>&gt;&gt;&gt; import pytz &gt;&gt;&gt; from datetime import datetime, date, time &gt;&gt;&gt; tz = pytz.timezone("Australia/Melbourne") &gt;&gt;&gt; the_date = date(2012, 4, 1) # use date.today() here &gt;&gt;&gt; midnight_without_tzinfo = datetime.combine(the_date, time()) &gt;&gt;&gt; print midnight_without_tzinfo 2012-04-01 00:00:00 &gt;&gt;&gt; midnight_with_tzinfo = tz.localize(midnight_without_tzinfo) &gt;&gt;&gt; print midnight_with_tzinfo 2012-04-01 00:00:00+11:00 &gt;&gt;&gt; print midnight_with_tzinfo.astimezone(pytz.utc) 2012-03-31 13:00:00+00:00 </code></pre> <p>No guarantees for dates before 1582, though.</p>
How would you attack this polymorphism string building problem <p>Sorry for not so discrptive title, if someone wants to change it go ahead. Also note I have already asked a <a href="http://stackoverflow.com/questions/361742/would-this-be-a-good-case-for-polymorphism">question</a> about this kind of thing but this one is more about how you would attack it because my attack just doesn't seem to feel right.</p> <p>I am having a problem with building a string up to send to an OLE object in the correct order using the polymorphism method in the other question. </p> <p>The OLE object can only take and receive a string, so what I am doing is building a wrapper around all the common commands and providing a more .NET feel for them.</p> <p>The problem I ran into very fast was some of the commands that my wrapper had to send where very long and had optional bits which then suddenly turned a method that was only setting a name into a big string building method with if's just to set a name and of course this happens all over the place because there are a lot of commands.</p> <p>Now in order to have a good wrapper I would like to be able to wrap up the string building process so that I move the string building logic away from the wrapper itself and into a builder object. <br>I tried to attack this by using polymorphism which works well when I have a <strong>builder object</strong> class designed just for building that one type of command string. See other post for details.</p> <p>Sorry for the long post I will cut to the chase now.</p> <p>The main problem is that there is a lot of command strings that have to be built up which means more <strong>builder objects</strong>. <br> So I would really like to have a generic string builder that can build a string from any list of commands but the catch is they have to be in the <strong>correct order</strong> even if the user sets them in the wrong order.</p> <p>How would you approach this?</p>
<p>I think you're over complicating things and will end up creating too many classes.</p> <p>I'd look at the problem as less a string-building one and more of how you'd present a nice interface to a .net caller. Just because there are lots of possible arguments doesn't mean you need to create lots of classes for them, at least if the possible variations within each argument aren't very sophisticated, ie if the value is either there or it's not, and has optional units. Then you get yourself into this mess of needing to know the order the parts of the command need to have, etc. </p> <p>Probably I'd create a class for the possible arguments of the command, let a caller set whichever ones they like, and have that class responsible for generating the string in one big (ugly?) string concatenation.</p> <p>For example I'd start with something like this, and as you go I'd add methods where it makes sense to refactor a little of the string concatenation, depending on the similarity of the different parts of the command.</p> <pre><code>class CommandArgs { private double? _Position_x = null; private double? _Position_y = null; private String _Position_units = null; private double? _Width = null; private String _Width_units = null; private double? _Height = null; private String _Height_units = null; // maybe there's a better tuple-like type for this. public double[] Position { set { if (value.length != 2) throw new ArgumentException("argh!"); _Position_x = value[0]; _Position_y = value[1]; } } public string Position_Units { set { _Position_Units = value; } } public double Width set { _Width = value; } } public double Height set { _Height = value; } } public string Width_Units set { _Width = value; } } public string Height_Units set { _Height = value; } } // .... public override string ToString() { return ( _Position_x != null ? string.Format(" Position ({0},{1})",_Position_x, _Position_y ) : "" ) + ( _Height != null ? string.Format(" Height {0}") + ( _Height_Units != null ? string.Format(" Units {0}", _Height_Units) : "" ) + ( _Width != null ? string.Format(" Width {0}") + ( _Width_Units != null ? string.Format(" Units {0}", _Width_Units) : "" ) // ... ; } } </code></pre> <p>If you prefer you might like to make methods instead of properties, so you can set the value and units at the same time.</p> <p>I'd probably refactor that with the following methods immediately: </p> <pre><code>private string FormatUnits(string units) { return units == null ? "" : string.Format(" Units {0}", units); } private string FormatSingleValueArgument(string argName, object argValue, string units) { if (argValue == null) return ""; return string.Format(" {0} {1}", argName, argValue) + FormatUnits(units); } </code></pre> <p>making that ToString() look like this: </p> <pre><code> return ( _Position_x != null ? string.Format(" Position ({0},{1})",_Position_x, _Position_y ) : "" ) + FormatSingleValueArgument("Height", _Height, _Height_Units) + FormatSingleValueArgument("Width", _Width, _Width_Units) // ... ; </code></pre> <p>then perhaps do a similar method for Position-like arguments, if there are several of them.</p>
Insert Dates in the return from a query where there is none <p>We are building a query to count the number of events per hour, per day. Most days there are hours that do not have any activity and therefore where the query is run the count of activities per hour show up but there are gaps and the query excludes these. We still want to show the hours that do not have activity and display a zero so that zero value can then be charted. The query we using looks like this …</p> <pre><code>select datepart(Year, dev_time) as Year, datepart(Month, dev_time) as Month, datepart(Day, dev_time) as Day, datepart(Hour, dev_time) as Hour, count(tdm_msg) as Total_ACTIVITES from TCKT_ACT where tdm_msg = ‘4162′ and dev_time &gt;= DATEADD(day, - 1, GETDATE()) group by datepart(Year, dev_time) , datepart(Month, dev_time) , datepart(Day, dev_time), datepart(Hour, dev_time) order by datepart(Year, dev_time) asc, datepart(Month, dev_time) asc, datepart(Day, dev_time) asc, datepart(Hour, dev_time) asc </code></pre>
<p>You are going to somehow need a table of days and hours, and then you will have to do an outer join between that table and your query. Here's how I would do it. Note that this solution will only work in SQL Server 2005 and 2008. If you don't have those platforms, you'll have to actually create a table of times in your database from which you can join off of:</p> <pre><code>DECLARE @MinDate DATETIME; SET @MinDate = CONVERT(varchar, GETDATE(), 101); WITH times AS ( SELECT @MinDate as dt, 1 as depth UNION ALL SELECT DATEADD(hh, depth, @MinDate), 1 + depth as depth FROM times WHERE DATEADD(hh, depth, @MinDate) &lt;= GETDATE()) SELECT DATEPART(YEAR, t.dt) as [Year], DATEPART(MONTH, t.dt) as [Month], DATEPART(DAY, t.dt) as [Day], DATEPART(HOUR, t.dt) as [Hour], COUNT(tdm_msg) as Total_ACTIVITES FROM times t LEFT JOIN (SELECT * FROM TCKT_ACT WHERE tdm_msg = '4162' and dev_time &gt;= @MinDate) a ON DATEPART(HOUR, t.dt) = DATEPART(HOUR, a.dev_time) AND MONTH(t.dt) = MONTH(a.dev_time) AND DAY(t.dt) = DAY(a.dev_time) AND YEAR(t.dt) = YEAR(a.dev_time) GROUP BY DATEPART(YEAR, t.dt) , DATEPART(MONTH, t.dt) , DATEPART(DAY, t.dt), DATEPART(HOUR, t.dt) ORDER BY DATEPART(YEAR, t.dt) asc, DATEPART(MONTH, t.dt) asc, DATEPART(DAY, t.dt) asc, DATEPART(HOUR, t.dt) asc OPTION (MAXRECURSION 0); /* Just in case you want a longer timespan later on... */ </code></pre> <p>Note that the WITH statement at the top is called a recursive common table expression, and is a good way of generating sequential tables with relatively small numbers of elements, like you have here. </p>
Can Flash Remoting run through a HTTP (Squid) proxy server <p>I have a network were would like like to deliver data using the Flash Remoting data format over HTTP. We have Squid working as a reverse proxy/accelerator, are there any known problems running this traffic through Squid. We would configure that particular URL to not be cached.</p>
<p>If Squid is not caching that URL or modifying the request or response, I think it's unlikely to cause any problems. That's the point, right? That's a big if though...</p> <p>Just be glad that you control the Squid. That way, if there is a problem, you can change the configuration relatively quickly. Relying on an externally controlled squid to not snarf up your application would be a potential point of failure.</p>
How can I write out or read in a Perl hash of arrays? <p>I have a program in Perl I'm working on where I would need multiple keys, and a way of giving each key multiple values and follow that by being able to both read them in and write them out to an external file depending on if the key matches what the person enters into standard input. I've looked across several sites and have found information somewhat useful in reading in hashes of arrays, but not writing them out, and I would also need to be able able to add to the array in the external file.</p> <p>Is this possible?</p> <p>Edit: Is there a way that it could be done with starter Perl? I'm a beginner. Hashes of arrays seemed like the best way to make it work, but what I really need is a way to show multiple values for the same key while only showing the key once.</p>
<p>Check out <a href="http://search.cpan.org/~ilyam/Data-Dumper-2.121/">Data::Dumper</a>.</p> <p>For instance, this microscopic script:</p> <pre><code>#!/bin/perl -w use strict; use Data::Dumper; my(%hash); $hash{key1} = [ 1, "b", "c" ]; $hash{key2} = [ 4.56, "g", "2008-12-16 19:10 -08:00" ]; print Dumper(\%hash); </code></pre> <p>produces this output, which could clearly be edited:</p> <pre><code>$VAR1 = { 'key2' =&gt; [ '4.56', 'g', '2008-12-16 19:10 -08:00' ], 'key1' =&gt; [ 1, 'b', 'c' ] }; </code></pre> <p>It can also be evaluated to read the data back into the program.</p> <p><hr></p> <p>Extending the example to show reading in as well as printing out...Note that the code is in two main blocks, and the only variable common between the blocks is the name of the file.</p> <pre><code>#!/bin/perl -w use strict; use Data::Dumper; use FileHandle; my $file = "data.out"; { my(%hash); $hash{key1} = [ 1, "b", "c" ]; $hash{key2} = [ 4.56, "g", "2008-12-16 19:10 -08:00" ]; my $str = Data::Dumper-&gt;Dump([ \%hash ], [ '$hashref' ]); print "Output: $str"; my($out) = new FileHandle "&gt;$file"; print $out $str; close $out; } { my($in) = new FileHandle "&lt;$file"; local($/) = ""; my($str) = &lt;$in&gt;; close $in; print "Input: $str"; my($hashref); eval $str; my(%hash) = %$hashref; foreach my $key (sort keys %hash) { print "$key: @{$hash{$key}}\n"; } } </code></pre> <p>The output from that script is:</p> <pre><code>Output: $hashref = { 'key2' =&gt; [ '4.56', 'g', '2008-12-16 19:10 -08:00' ], 'key1' =&gt; [ 1, 'b', 'c' ] }; Input: $hashref = { 'key2' =&gt; [ '4.56', 'g', '2008-12-16 19:10 -08:00' ], 'key1' =&gt; [ 1, 'b', 'c' ] }; key1: 1 b c key2: 4.56 g 2008-12-16 19:10 -08:00 </code></pre> <p><hr></p>
Why is App_Offline failing to work as soon as you it starts loading dlls? <p>Could anyone please help me with this. On the production site app_offline.htm works only till you start uploading dlls. As soon as you start uploading dlls it throws following error"Could not load file or assembly 'SubSonic' or one of its dependencies. <strong>The process cannot access the file because it is being used by another process.</strong> Now this clearly shows that IIS is still trying to serve the aspx page?? Is there anything I am missing here?? Any help would be appreciated. I have spent hours googling but to no avail. Thanks in advance. Manisha</p>
<p>I have heard of people having problems with app_offline.htm if it did not have enough content in the file.</p> <p>Fill it with a couple hundred kb's of Lorem Ipsum text and see if that helps.</p>
How to Check for Image in Cache Using Silverlight <p>I am creating a basic image browsing application using Silverlight. Depending on the user's connection speed, some images may take time to appear once they click on the thumb nail. I would like to show a progress bar while it is being downloaded. I have this part done.</p> <p>However, if the image is already in the cache (viewing a previous image), I'd rather not have the progress bar flash up and then disappear. Is there a way to see if a particular file is in the cache before I display my progress bar?</p>
<p>After thinking about it for a while, I did come up with one solution, though it wasn't what I was originally intending.</p> <p>I am using the WebClient class to get my image file. I attach to the DownloadProgressChanged event. If the image has already been downloaded, then the ProgressPercentage is immediately 100.</p> <p>So instead of making the ProgressBar visibile when I call OpenReadAsync and making it invisible when the Completed event is fired, I set the visibility in the DownloadProgressChanged event handler.</p>
Are there well known algorithms for deducing the "return types" of parser rules? <p>Given a grammar and the attached action code, are there any standard solution for deducing what type each production needs to result in (and consequently, what type the invoking production should expect to get from it)?</p> <p>I'm thinking of an OO program and action code that employs something like c#'s <code>var</code> syntax (but I'm not looking for something that is c# specific).</p> <p>This would be fairly simple if it were not for function overloading and recursive grammars.</p> <p>The issue arises with cases like this:</p> <pre><code>Foo ::= Bar Baz { return Fig(Bar, Baz); } Foo Pit { return Pop(Foo, Pit); } // typeof(foo) = fn(typeof(Foo)) </code></pre>
<p>If you are writing code in a functional language it is easy; standard Hindley-Milner type inference works great. <strong>Do not do this</strong>. In my EBNF parser generator (never released but source code available on request), which supports Icon, c, and Standard ML, I actually <strong>implemented the idea</strong> you are asking about for the Standard ML back end: all the types were inferred. <strong>The resulting grammars were nearly impossible to debug.</strong></p> <p>If you throw <strong>overloading</strong> into the mix, the results are only going to be <strong>harder to debug</strong>. (That's right! This just in! Harder than impossible! Greater than infinity! Past my bedtime!) If you really want to try it yourself you're welcome to <a href="http://www.cs.tufts.edu/~nr/drop/ebnf-dist.icn" rel="nofollow">my code</a>. (You don't; there's a reason I never released it.)</p>
Unix command to find lines common in two files <p>I'm sure I once found a unix command which could print the common lines from two or more files, does anyone know its name? It was much simpler than <code>diff</code>.</p>
<p>The command you are seeking is <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/comm.html"><code>comm</code></a>.</p>
To Disable The BackButton Of Browser Window Using Javascript <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/87422/disabling-back-button-on-the-browser">Disabling Back button on the browser</a> </p> </blockquote> <p>Hi Guys, I need to disable the backbutton of browser window.When I click on backbutton,I need to show one message using alert or other means.Any one can help me </p>
<p>you can't make the user stay on your page, but you can give a yes/no prompt first, though.</p> <p>read around <a href="http://stackoverflow.com/questions/261083/is-there-a-way-to-determine-that-the-browser-window-was-closed">http://stackoverflow.com/questions/261083/is-there-a-way-to-determine-that-the-browser-window-was-closed</a></p>
Why does stdafx.h work the way it does? <p>As usual, when my brain's messing with something I can't figure out myself, I come to you guys for help :)</p> <p>This time I've been wondering why stdafx.h works the way it does? To my understanding it does 2 things:</p> <ul> <li>Includes standard headers which we <em>might</em> (?) use and which are rarely changed</li> <li>Work as a compiler-bookmark for when code is no longer precompiled.</li> </ul> <p>Now, these 2 things seems like two very different tasks to me, and I wonder why they didn't do two seperate steps to take care of them? To me it seems reasonable to have a #pragma-command do the bookmarking stuff and to optionally have a header-file a long the lines of windows.h to do the including of often-used headers... Which brings me to my next point: Why are we forced to include often-used headers through stdafx.h? Personally, I'm not aware of any often used headers I use that I'm not already doing my own includes for - but maybe these headers are necessary for .dll generation?</p> <p>Thx in advance</p>
<p>stdafx.h is ONE way of having Visual studio do precompiled headers. It's a simple to use, easy to automatically generate, approach that works well for smaller apps but can cause problems for larger more complex apps where the fact that it encourages, effectively, the use of a single header file it can cause coupling across components that are otherwise independent. If used <strong><em>just</em></strong> for system headers it tends to be OK, but as a project grows in size and complexity it's tempting to throw other headers in there and then suddenly changing any header file results in the recompilation of everything in the project.</p> <p>See here: <a href="http://stackoverflow.com/questions/290034/is-there-a-way-to-use-pre-compiled-headers-in-vc-without-requiring-stdafxh#293219">http://stackoverflow.com/questions/290034/is-there-a-way-to-use-pre-compiled-headers-in-vc-without-requiring-stdafxh#293219</a> for details of an alternative approach.</p>
How to change font color of disabled input in Firefox <p>When I disable input elements the text is taking the font color: "#000000" in Firefox. This is not happening in IE. Please check the below page in IE and Firefox. Let me know how to give it a gray look as in IE.<br /> <a href="http://shivanand.in/tmp/test.html">test</a></p>
<p>Different browsers style disabled elements differently. Here is how you can control the style of disabled elements in Firefox.</p> <pre><code>[disabled] { color:#ff0000; background-color:#00ff00; } </code></pre>
Finding available LPT (parallel) ports and addresses in Delphi <p>I am doing direct I/O on a parallel port which is fine and necessary for speed. I would like to enumerate the available ports to offer the user a choice of ports at setup time rather than a tedious trawl through device manager to read the address manually. Does anyone know a means of doing this please? Many thanks, Brian</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/aa506006.aspx" rel="nofollow">this Microsoft article</a>, for Win2K and newer, you can find details of parallel-connected devices in the registry at HKLM\SYSTEM\CurrentControlSet\Enum\LPTENUM.</p>
Set folder permissions with C# - convert CreateObject("Wscript.Shell") from vb to C# <p>I'd like to know how to convert this vb script to C#</p> <pre><code>Dim strFolder As String Dim objShell As Object strFolder = "C:\zz" Set objShell = CreateObject("Wscript.Shell") objShell.Run "%COMSPEC% /c Echo Y| cacls " &amp; _ strFolder &amp; _ " /t /c /g everyone:F ", 2, True </code></pre> <p>What I'm trying to do is set permissions to "Everyone" on a newly created folder on the users C:\ drive.</p> <p>I'm using Visual Studio, .Net 1.1</p> <p>Thanks. Iain</p>
<p>It's not possible to upgrade unfortunately - I work for a big company, so would mean updating loads of people - which would be a mission...</p> <p>But - creating a process worked!</p> <pre><code>System.Diagnostics.Process meProc = System.Diagnostics.Process.Start ("cmd.exe", " /c echo y| cacls C:\\zzz /t /c /g everyone:F"); </code></pre> <p>Thanks both of you for your help.</p>
Configuring root directory internal ASP.NET server <p>My ASP.NET always starts like this with the internal server: <a href="http://localhost:50793/Website/" rel="nofollow">http://localhost:50793/Website/</a></p> <p>I use FckEditor which points to <a href="http://localhost:50793/fckeditor" rel="nofollow">http://localhost:50793/fckeditor</a></p> <p>How do I configure the server that it servers my folder "Website" as the root?</p>
<p>Go click on the website project in the solution explorer, then edit the "Virtual path" in the properties window.</p>
How can I render a different controller's action from within a view? <p>I know that within a view I can render an action from the same controller using Html.RenderPartial. However, I need to render the output from an action under a different controller. What is the best way to do this? I would prefer to do this directly within the view, rather than doing it in the controller and saving the output to a ViewData variable.</p>
<p>The best thing to do is use <code>Html.RenderAction</code> which needs a references to the 'Futures' assembly <code>Microsoft.Web.Mvc</code> which <a href="http://stackoverflow.com/questions/334408/where-to-get-microsoftwebmvcdll">there's a question about how to get it</a>.</p> <p>You will also need to add the namespace in your web.config in order to user it in your view: </p> <pre><code>&lt;add namespace="Microsoft.Web.Mvc"/&gt; </code></pre>
Where is a python real project to be used as example for the unit-test part? <p>I'm looking for a python project to use as example to copy the design of the unit test parts.</p> <p>The project should have these features:</p> <ol> <li>its code is almost fully unit tested</li> <li>the code is distributed in many packages, there are more that one level of packages </li> <li>all the test can be run with a single command, for example with <code>python test.py</code></li> </ol> <p>I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't. </p> <p>I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project.</p>
<p>Maybe <a href="http://code.google.com/p/python-nose/" rel="nofollow">Nose</a> itself?</p>
Ajax hyperlinking <p>I have a problem in giving Ajax functionality to a hyperlink. I have files <code>Link.html</code> and <code>GetCustomerdata.php</code>. The main function of the HTML is send the data to <code>getCutomerData.php</code> and shows flash as "success".</p> <p>And also I do not want hyperlinking,</p> <pre><code>&lt;a href="#" </code></pre> <p>Instead I need it in terms of:</p> <pre><code>&lt;a href=GetCustomer.php?id=&lt;format&gt; </code></pre> <p>Is it possible to clear?</p> <h3>Link.Html</h3> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Customer Account Information&lt;/title&gt; &lt;script type="text/javascript"&gt; var url = "GetCustomerData.php?id="; // The server-side script function handleHttpResponse() { if (http.readyState == 4) { if(http.status==200) { var results=http.responseText; document.getElementById('divCustomerInfo').innerHTML = results; } } } function requestCustomerInfo() { var sId =10; document.getElementById("txtCustomerId").value; http.open("GET", url + escape(sId), true); http.onreadystatechange = handleHttpResponse; http.send(null); } function getHTTPObject() { var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject){ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); if (!xmlhttp){ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } } return xmlhttp; } var http = getHTTPObject(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="getCustomerData.php?id=10&amp;onclick="requestCustomerInfo();return false;"&gt;Show Me&lt;/a&gt; &lt;div id="divCustomerInfo"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>...</p> <p>And my PHP file just flashes the suceess message:</p> <h3>getCustomerData.php</h3> <pre><code>&lt;?php echo "Success" ?&gt; </code></pre>
<p>You placed the anchor onclick event inside the href attribute. onclick should be written as a separate attribute:</p> <pre><code>... &lt;a href="getCustomerData.php?id=10" onclick="requestCustomerInfo();return false;"&gt;Show Me&lt;/a&gt; </code></pre> <p>To prevent the link from redirecting the page, you need to stop the click event from executing the link default action. Inside your function call:</p> <pre><code>function requestCustomerInfo(event) { if (!event) var event = window.event; event.preventDefault(); ... } </code></pre>
How to be able to select a portion of the screen? <p>In some screen capture software when you press a key it's possible for the client to select a portion of the screen. How can I implement that in my software written in framework 2.0 .Net?</p> <p>Here is a image of what I would like to do : <a href="http://img341.imageshack.us/img341/3782/portionpb9.png" rel="nofollow">http://img341.imageshack.us/img341/3782/portionpb9.png</a> you see, I can select a portion of the screen. How can I do that?</p> <p>I do not want to know how to take a screenshot... any one?</p>
<p>I know it might not be a solution that you could easily copy&amp;paste but this open source project in C# does have the behavior that your application want : <a href="http://www.codeplex.com/cropper" rel="nofollow">http://www.codeplex.com/cropper</a></p> <p>You might be able to take a piece of their code into you application. Here is a image from code plex :</p> <p><img src="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=cropper&amp;DownloadId=8026" alt="alt text" /></p>
How can I generate multiple classes from xsd's with common includes? <p>Aloha</p> <p>I received a few nice xsd files which I want to convert to classes (using xsd.exe) All the xsd's have the same includes, like this:</p> <pre><code>&lt;xs:include schemaLocation="kstypes.xsd" /&gt; &lt;xs:include schemaLocation="ksparams.xsd" /&gt; </code></pre> <p>When I generate a class for each xsd the types declared in these files are duplicated for each original xsd. Is there any easy way to 1) only generate the types in the included xsd's once and 2) make sure all other classes use these types?</p> <p>-Edoode</p>
<p>Looking over the documentation, it would appear that the 'best' way (not an easy way!) would be to use the /element:<em>elementname</em> command line switch on the second and subsequent files to specify the types you want classes generated for.</p>
Returning Japanese characters via char* in an Excel XLOPER <p>I am retrieving Japanese characters from a data source and I want to return this data to Excel in an XLOPER. I am using a Japanese version of Excel 2003 (hence XLOPERs and not XLOPER12s).</p> <pre><code>wchar_t* pszW = OLE2W(bstrResult); //I have the data I am trying to copy in a CComBSTR ULONG ulSize = ::WideCharToMultiByte( CP_THREAD_ACP, 0, pszW, -1, NULL, 0, NULL, NULL ); if ( ulSize ) { char* tmp = new char[ulSize + 1]; tmp[ulSize]='\0'; ::WideCharToMultiByte( CP_THREAD_ACP, 0, pszW, -1, LPSTR( tmp ), ulSize, NULL, NULL ); pszReturn = tmp; } wchar_t* pwszOut = new wchar_t[bstrResult.Length () + 1]; //now turn it back to test that that the correct code page was used. For debugging purposes only! ::MultiByteToWideChar (CP_THREAD_ACP,0, LPSTR(pszReturn),-1,pwszOut,bstrResult.Length () + 1); //pwszOut and bstrResult look the same in the debugger delete [] pwszOut; </code></pre> <p>The parameter pszReturn is assigned to an XLOPER. The problem I have is that “アフリカの女王” is displayed as “ƒAƒtƒŠƒJ‚Ì—‰¤” in Excel.</p> <p>Manually setting the code page to 932 yields the same results as CP_THREAD_ACP so I think that that part is correct.</p> <p>Any help would be greatly appreciated.</p>
<p><strong><em>User Error!</em></strong></p> <p>The above code is good. The problem is that Excel was using the wrong code page. I hadn't set the language for non-unicode programs to Japanese in Control Panel.</p> <p>The code now works for the English version of Excel too.</p> <p>That was a day and a half well spent...</p>
Will an svn:external subdirectory sync with its HEAD revision upon every 'svn update' to the parent working copy? <p>On <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow">this page in the Subversion manual</a>, it says that "When you commit a change to the svn:externals property, Subversion will synchronize the checked-out items against the changed externals definition when you next run svn update. The same thing will happen when others update their working copies and receive your changes to the externals definition."</p> <p>If you have not specified a revision number for the external, I assume the HEAD revision is used. So, will the subdir managed by the external property update to its HEAD revision each and every time 'svn update' is run against the parent working copy?</p>
<p>Yes, it will be updated as well, that is the main purpose here :)</p>
How to print to a null printer in .NET? <p>I need to write a unit test for a method that will print a document. Is there an easy way to send the output to the Windows equivalent of /dev/null? I'm guessing that having our build server print a document on every check in is going to get expensive quickly. ;)</p> <p>Ideally, this would work on both our build server (which has no default printer) and our development machines (which do), so I'd prefer not to change the default printer.</p> <p>Thanks for all the wonderful answers that will undoubtedly follow this fascinating question.</p>
<p>I do this by creating a Windows printer that prints to the NUL device. This is pretty straightforward though the specifics differ a bit between Windows versions: just create a local printer and specify NUL as the local port, "Generic" as the Manufacturer and "Generic / Text Only" as the printer model.</p>
Are there any plans to officially support Django with IIS? <p>I say properly because everyone I have spoken to in the past said running Django on IIS was a hack. I had it working somewhat but it never did quite right and did feel like a hack. I like python but had to give it up because I could never make Django work with IIS and Django was my excuse to use Python in production web apps. But it was so messy that I could not in good conscience sell it to the group. So, I figured why fight it, just stick to asp.net, IIS, roll your own or use frameworks from MS. Just wondering if anything had changed. BTW, not knocking asp.net. I just wanted to use Python.</p> <p>Thank you.</p> <p>EDIT - Are there any new plans to officially support IIS yet?</p>
<p>Django is WSGI-based framework so as soon as IIS get proper WSGI handling there should be no problem in running Django under this environment. Anything that connects WSGI and IIS will do.</p> <p>Quick googling reveals <a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow">some project on Google Code</a>.</p>
Chained IF structure <p>Imagine this case where I have an object that I need to check a property. However, the object can currently have a null value.</p> <p>How can I check these two conditions in a single "if" condition?</p> <p>Currently, I have to do something like this:</p> <pre><code>if (myObject != null) { if (myObject.Id != pId) { myObject.Id = pId; myObject.Order = pOrder; } } </code></pre> <p>I would like something like this:</p> <pre><code>if (myObject != null &amp;&amp; myObject.Id != pId) </code></pre> <p>I want to evaluate the second condition only if the first was true.</p> <p>Maybe I'm missing something, and that's why I need your help ;-)</p>
<pre><code>if(myObject != null &amp;&amp; myObject.Id != pId) { myObject.Id = pId; myObject.Order = pOrder; } </code></pre> <p><code>&amp;&amp;</code> is a short-circuiting logic test - it only evaluates the right-hand-side if the left-hand-side is true. Contrast to "a &amp; b", which always evaluates both sides (and does a bitwise "and")</p>
Boxing/Unboxing and Nullable? <p>I understand that boxing and unboxing is about casting (real type to object... object to real type). But I do not understand what the MSDN say about it with the Nullable. Here is the text I do not understand:</p> <blockquote> <p>When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable structure initialized to the underlying value. <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx">Source</a></p> </blockquote> <p>When you change your object to a real type, the real type variable that was nullable will be the type of object? I do not get it?</p>
<p>What it's saying is that if you do:</p> <pre><code>int? x = 5; object y = x; // Boxing </code></pre> <p>You end up with a boxed <code>int</code>, not a boxed <code>Nullable&lt;int&gt;</code>. Similarly if you do:</p> <pre><code>int? x = null; // Same as new Nullable&lt;int&gt;() - HasValue = false; object y = x; // Boxing </code></pre> <p>Then y ends up as a null reference.</p>
Can't re-add Service Reference Properly <p>I've got a WCF service up and running on a server. We have a proxy class that we add all service references to, and I tried to add my service reference there. However, it's not exposing all of the methods, specifically the interface, allowing me to create an instance of it (this is VS 2008). However, when I create a new project, and just add the service reference to it, it adds all of the interfaces properly.</p> <p>Any ideas on how to force the original project to re-add the project properly? Is there something in memory that is not getting cleared? I've tried deleting the reference, rebuilding, closing and re-opening the project, but it still comes out the same way.</p> <p>I've also tried deleting the project and re-creating it with no luck there either.</p>
<p>The issue has been resolved. It turns out that if you don't add all the necessary references to the project, then the references needing them will not appear. It turned out that we needed to add System.Drawing as a reference, and then the solution added fine. I wish there was some feedback about this from MS, but if anyone runs into something like this in the future, just remember, you need to add all references...</p>
Can IntelliJ IDEA open more than one editor window for files from the same project? <p>I can split editor panes horizontally or vertically, but it does not seem possible to view code in two separate physical windows. I am aware that Idea can open multiple <strong>projects</strong> in separate windows, but I'd like to be able to do this for two files in a <strong>single</strong> project. </p> <p>One answer suggested unpinning the tab, but I haven't been able to make that work (I'm on Mac OSX if that matters.)</p> <p>This seems like a basic feature in today's world of multi-headed workstations. Before moving to an IDE I used to do this regularly with good old Emacs. Is there some trick I am not aware of to make this happen?</p>
<p>Unfortunately there is no way (as of IDEA 8.0.1) to do what you're asking for. As you pointed out, you can split the editor pane but there is always exactly one editor per IDEA project.</p> <p>UPDATE: As of IDEA 10 (currently the latest is 10.5), the answer is yes, you can :-)</p>
Validating file types by regular expression <p>I have a .NET webform that has a file upload control that is tied to a regular expression validator. This validator needs to validate that only certain filetypes should be allowed for upload (jpg,gif,doc,pdf)</p> <p>The current regular expression that does this is:</p> <pre> <code> ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.doc|.DOC|.pdf|.PDF)$ </code> </pre> <p>However this does not seem to be working...Can anyone give me a little reg ex help?</p> <p>Thanks.</p>
<p>Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):</p> <pre><code>^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$ </code></pre> <p>You can use a tool like <a href="http://www.ultrapico.com/Expresso.htm">Expresso</a> to test your regular expressions.</p>
Why does the BitConverter return Bytes and how can I get the bits then? <p>As input I get an int (well, actually a string I should convert to an int).<br /> This int should be converted to bits.<br /> For each bit position that has a 1, I should get the position.<br /> In my database, I want all records that have an int value field that has this position as value.<br /> I currently have the following naive code that should ask my entity(holding the databaseValue) if it matches the position, but obviously doesn't work correctly:</p> <pre><code>Byte[] bits = BitConverter.GetBytes(theDatabaseValue); return bits[position].equals(1); </code></pre> <p>Firstly, I have an array of byte because there apparantly is no bit type. Should I use Boolean[] ? Then, how can I fill this array? Lastly, if previous statements are solved, I should just return bits[position]</p> <p>I feel like this should somehow be solved with bitmasks, but I don't know where to start..</p> <p>Any help would be appreciated</p>
<p>I suspect <a href="http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx" rel="nofollow">BitArray</a> is what you're after. Alternatively, using bitmasks yourself isn't hard:</p> <pre><code>for (int i=0; i &lt; 32; i++) { if ((value &amp; (1 &lt;&lt; i)) != 0) { Console.WriteLine("Bit {0} was set!", i); } } </code></pre>
SQL Server Agent: How to "sleep"? <p>In a scripting step in a scheduled task in SQL Server Agent 2005, I need to trigger a webscript that is running on a different server. I'm doing this:</p> <pre><code>Dim ie Set ie = CreateObject( "InternetExplorer.Application" ) ie.navigate "...to my dreamscript" ' Wait till IE is ready Do While ie.Busy (1) Loop ie.Quit set ie = Nothing </code></pre> <p>At (1) I would like to "sleep" (e.g. WScript.sleep(..)), but WScript is not available in this environment. Is there another way to "sleep" for a while?</p>
<p>You can write a console applicaton and execute the console app in SQL agent job.</p>
Will Expression Blend relieve me from having to learn xaml? <p>I don't mind learning xaml and I'm sure I need to be familiar somewhat, but when I was first trying out Silverlight 1 with javascript it looked like a tremendous amount of overhead. I decided to wait until tools matured and asp.net was added. Well, asp.net has been added with Silverlight 2.0, and now I want to look at using it. But, xaml, to me, still looks like a lot of work for each small step. My experience with Flash seemed a lot more simpler for the graphics side of things (never liked ActionScript that much.) Will $500 for Blend take care of much of my xaml concerns? Can I use Visual Studio Express with the full version of Microsoft Expression Blend?</p> <p>Do I need Microsoft Expression Studio 2?</p> <p>Thank you.</p>
<p>Just as a profressional web developer can't lean on Dreamweaver's drag-and-drop to avoid learning HTML, you should climb the XAML learning curve. </p> <p>Blend will still help, however- just as many started up the HTML curve by doing some drag-and-drop and studying the resulting HTML code. I did some prototyping with Silverlight 1.1 and Blend helped significantly in my understanding of XAML. It helps to have a "real" project to work on, even if it's a proof of concept. Concentrate on the containment paradigm between Canvas and other elements and you'll pick it up quickly enough. I wouldn't worry too much about the MPATH stuff, do rely on the tool for that.</p>
A couple of questions on the architecture of Ruby <p>I am primarily a fluent .NET developer (as can be seen from the amount of posts and threads I make about .NET), but I thought it would be good to learn RoR.</p> <p>In doing so, I have a few questions about the architecture of the language (Ruby) and the framework (RoR):</p> <p>1) In .NET, every object is derived from System but inherits System.Object. So when I type System., I get a list of namespaces and then in those namespaces, classes and more namespaces.</p> <p>Does Ruby not have this sort of hierarchy?</p> <p>2) In some cases, I don't get the intellisense. For example, I wrote the class as outlined here (<a href="http://wiki.rubyonrails.org/rails/pages/HowToSendEmailsWithActionMailer" rel="nofollow">http://wiki.rubyonrails.org/rails/pages/HowToSendEmailsWithActionMailer</a>) but in the line recipients user.email, nothing comes up when I type "user.".</p> <p>Any idea why?</p> <p>Thank</p>
<p>Dave Thomas (Pragmatic Programmers) has an excellent <a href="http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming" rel="nofollow">screencast series</a> on the Ruby object model/metaprogramming. We watched this in a local Ruby user's group. The series isn't free, but it's not expensive either. You might want to check out the free preview to see if you think it is worth your time.</p> <p>And to give you an answer. Yes, everything in Ruby derives from Object. You can find the docs on this at <a href="http://corelib.rubyonrails.org/" rel="nofollow">http://corelib.rubyonrails.org/</a>. Look for the Object class.</p> <p>I'm not sure why you aren't getting intellisense, partly because you haven't specified your IDE. It's possible that you can't because you've added the method dynamically and no intellisense is available.</p>
How do you manage software serial keys, licenses, etc? <p>My company is trying to find a tool that will track serial keys for software we have purchased (such as Office), as well as software that we write and sell.</p> <p>We want software that will allows us to associate a particular computer with the software on that computer and the serial key(s) and license(s) for that software. We'd also like to track history of the computer, such as when software is removed from a computer and moved to another computer.</p> <p>I've looked around Google and various software sites, but all of the results I've found are for licensing software and creating serial keys, not managing the serial keys that those tools generate. I know this problem has been solved; many companies license software and keep records of the serial keys they generate. So I'm curious if any of you have solved this same problem without writing your own custom software?</p> <p><strong>Edit:</strong> I forgot to mention, I am not asking about the merits of licensing software -- the software we write is not COTS and purchases are controlled at a contractual level. Still, we need to manage how serial keys are generated.</p>
<p>Take a look at SpiceWorks:</p> <p><a href="http://www.spiceworks.com/" rel="nofollow">http://www.spiceworks.com/</a></p> <p>It does a lot more than just inventory / asset management and is free.</p>
Flex: when hiding components in flex <p>When I set a component to visible=false the component hides, but how do I get it to take no space (get the container it belongs to to resize??)</p> <p></p> <pre><code>&lt;mx:HBox width="100%" height="100%"&gt; ... &lt;/mx:HBox&gt; &lt;mx:HBox width="100%" id="boxAddComment" visible="false" &gt; &lt;mx:TextArea id="txtComment"/&gt; &lt;mx:Button label="Spara" click="addComment();"/&gt; &lt;/mx:HBox&gt; </code></pre> <p></p> <p>When boxAddComment is visible=false I want the first HBox to take 100% height.</p>
<p>use the <strong>includeInLayout</strong> property. e.g.</p> <pre> <code> &lt;mx:HBox width=&quot;100%&quot; height=&quot;100%&quot;&gt; ... &lt;/mx:HBox&gt; &lt;mx:HBox width=&quot;100%&quot; id=&quot;boxAddComment&quot; visible=&quot;false&quot; includeInLayout=&quot;false&quot; &gt; &lt;mx:TextArea id=&quot;txtComment&quot;/&gt; &lt;mx:Button label=&quot;Spara&quot; click=&quot;addComment();&quot;/&gt; &lt;/mx:HBox&gt; </code> </pre>
Convert style-laden HTML tables to PDF, in .NET 1.1 <p>I have colleagues working on a .NET 1.1 project, where they obtain XML files from an external party and programmatically instruct iTextSharp to generate PDF content based on the XML data.</p> <p>The tricky part is, within this XML are segments of arbitrary HTML content. These are HTML code users copied and pasted from their Office applications. Still looks ok on a web browser, but when this HTML is fed into iTextSharp's HTMLWorker object to parse and convert into PDF objects, the formatting and alignment run all over the place in the generated PDF document. E.g.</p> <pre><code>&lt;span id="mceBoundaryType" class="portrait"&gt;&lt;/span&gt; &lt;table border="0" cellspacing="0" cellpadding="0" width="636" class="MsoNormalTable" style="margin: auto auto auto 4.65pt; width: 477pt; border-collapse: collapse"&gt; &lt;tbody&gt; &lt;tr style="height: 15.75pt"&gt; &lt;td width="468" valign="bottom" style="padding-right: 5.4pt; padding-left: 5.4pt; padding-bottom: 0in; width: 351pt; padding-top: 0in; height: 15.75pt; background-color: transparent; border: #ece9d8"&gt; &lt;p style="margin: 0in 0in 0pt" class="MsoNormal"&gt; &lt;font face="Times New Roman"&gt;&amp;nbsp;&lt;/font&gt;&lt;/p&gt; &lt;/td&gt; &lt;td colspan="3" width="168" valign="bottom" style="padding-right: 5.4pt; padding-left: 5.4pt; padding-bottom: 0in; width: 1.75in; padding-top: 0in; height: 15.75pt; background-color: transparent; border: #ece9d8"&gt; &lt;p style="margin: 0in 0in 0pt; text-align: center" class="MsoNormal" align="center"&gt; &lt;u&gt;&lt;font face="Times New Roman"&gt;Group&lt;/font&gt;&lt;/u&gt;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>The tags are full of Style attributes, and iTextSharp does not support CSS and interpreting that attribute. What are some alternatives other iTextSharp users have tried to workaround this, or other feasible HTML-to-PDF components?</p>
<p>I have found .NET 2.0-based components like <a href="http://www.html-to-pdf.net/" rel="nofollow">ExpertPDF</a> and <a href="http://www.websupergoo.com/products.htm#pd" rel="nofollow">ABCpdf</a> do a fairly good job interpreting the CSS styles and aligning the tables properly in PDF. Right now I am suggesting to my colleagues the use of a separate .NET 2.0 web service that can use such components, which will be informed by the ASP.NET 1.1 web application to go ahead and scrape a generated web page that is essentially the report in HTML view.</p> <p>UPDATE:</p> <p>This is the answer as it is the recommended approach provided to the application team.</p>
What is the difference between these 2 function syntax types <p>As the title says, whats the difference between</p> <pre><code>MyFunction = function() { } </code></pre> <p>and</p> <pre><code>function MyFunction() { } </code></pre> <p>Nothing?</p> <p><strong>Duplicate:</strong> <a href="http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname</a></p>
<p>The first form is actually a variable with an <strong>anonymous function</strong> assigned to it, the second is a <strong>declared function</strong>. </p> <p>They're <em>almost</em> interchangeable, but have some differences: debuggers have a harder time with anons (because they lack a name) and the JS engine can directly access declared functions wherever they exist in the script, but anons can't be accessed until they have been assigned.</p>
How can I execute a given function on every element of a complicated data structure in Perl? <p>I want to decode all the HTML entities in a complicated data structure. Basically I'm looking for a "super map()" function. Here's what I have so far:</p> <pre><code>sub _html_decode { my $self = shift; my $ref = shift; if (ref($ref) eq "HASH") { $self-&gt;_html_decode_hash($ref) } if (ref($ref) eq "ARRAY") { $self-&gt;_html_decode_array($ref); } } sub _html_decode_array { my $self = shift; my $ref = shift; unless (@$ref) {return;} foreach (0 .. (scalar(@$ref) - 1)) { if (ref($ref-&gt;[$_]) eq "HASH") { $self-&gt;_html_decode_hash($ref-&gt;[$_]); } if (ref($ref-&gt;[$_]) eq "ARRAY") { $self-&gt;_html_decode_array($ref-&gt;[$_]); } else { $ref-&gt;[$_] = decode_entities($ref-&gt;[$_]); } } } sub _html_decode_hash { my $self = shift; my $ref = shift; unless (%$ref) {return;} while (my ($k, $v) = each %$ref) { if (ref($v) eq "HASH") { $self-&gt;_html_decode_hash($v); } if (ref($v) eq "ARRAY") { $self-&gt;_html_decode_array($v) } else { $ref-&gt;{$k} = decode_entities($v); } } } </code></pre>
<p>I think this should do, but I haven't tested it.</p> <pre><code>sub _html_decode { my ($self, $ref) = @_; if (ref($ref) eq "HASH") { for my $value (values %{$ref}) { $self-&gt;_html_decode($value); } } elsif (ref($ref) eq "ARRAY") { for my $value (@{$ref}) { $self-&gt;_html_decode($value); } } else { $_[1] = decode_entities($_[1]); } } </code></pre> <p>I admit the last part isn't pretty though.</p>
Why can't Nginx POST to my Perl backend? <p>EDIT: So I just found out that GET methods indeed work, but POST methods however do not work! That might be significant.</p> <p>So I am on Debian Etch, running Nginx. Nginx does not normally serve cgi/pl files so I have followed a guide to get my backend working.</p> <p><a href="http://technotes.1000lines.net/?p=23" rel="nofollow">http://technotes.1000lines.net/?p=23</a></p> <p>My backend works fine on Apache but I had to install a module working with nginx (lib-www).</p> <p>It now works, but for some reason, POST/GET methods don't work.... To give an example, my backend is set up to accept Product SKU's in the url, and it just adds it to cart when you do it. Now, if I were to directly type in this url with this added value, it works fine, adds it to cart, everything works beautifully....</p> <p>However, when I add a product to the cart, all my product pages are setup to submit to my backend. It submits the exact same value I could type into my browser window, except it does not work (in contrast to just typing it into my url bar which DOES work).</p> <p>Now I'm thinking the perl wrapper code I'm using is slightly wrong or something? It is here:</p> <p><a href="http://technotes.1000lines.net/fastcgi-wrapper.pl" rel="nofollow">http://technotes.1000lines.net/fastcgi-wrapper.pl</a></p> <p>I only made a couple of changes... I merely made a folder that it wants to install the socket in (but maybe it should be going in a different folder all together), and in my nginx conf I basically have it like this:</p> <pre><code>location ~ ^/cgi-bin/.*\.pl$ { gzip off; fastcgi_pass unix:/var/run/nginx/perl_cgi-dispatch.sock; fastcgi_param SCRIPT_FILENAME /www/blah.com$fastcgi_script_name; include fastcgi_params; } </code></pre> <p>My params are the same as they are in the article, and I only have the default mime type setup. Any ideas on why this is not working? I would be willing to provide any extra information you need as well.</p>
<p>This particular fastcgi-wrapper.pl script was modified by Denis S. Filimonov to handle POSTS requests properly. You can read more about it at: <a href="http://www.ruby-forum.com/topic/145858" rel="nofollow">http://www.ruby-forum.com/topic/145858</a></p>
Drop Down Box Not Fully Displayed (All Browsers) <p><img src="http://farm4.static.flickr.com/3200/3116366800_570cc971b9_m.jpg" alt="Screenshot of Drop Down" /></p> <p>This would be my issue I have a drop down that's not displaying fully. I'm not sure even where to start so here's the HTML surronding the drop down and I'll provide the CSS also.</p> <p>HTML</p> <pre><code>&lt;div id="add_item"&gt; &lt;ul class="vert"&gt; &lt;li&gt; &lt;ul class="horz"&gt; &lt;li class="name"&gt; &lt;select style="width: 195px; padding: 0px; margin: 0px;" disabled="disabled"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="0"&gt;0&lt;/option&gt; &lt;/select&gt; &lt;/li&gt; &lt;li class="quantity"&gt; &lt;select style="width: 50px; padding: 0px; margin: 0px;" disabled="disabled"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="0"&gt;0&lt;/option&gt; &lt;/select&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p></p> <p>The reason the code has the drop down as being disabled is because it's dynamic, the surrounding HTML is the same except for having options to choose from and no longer being disabled.</p> <p>CSS</p> <pre><code>div#byitem ul.horz li.name { background:transparent none repeat scroll 0 0; display:block; font-size:11px; font-weight:bold; width:195px; } div#byitem ul.horz { background:transparent none repeat scroll 0 0; clear:left; list-style-type:none; margin:0; padding:0; } div#byitem ul.vert li { background:transparent none repeat scroll 0 0; height:14px; margin:0; padding:0; } div#byitem ul.vert { background:transparent none repeat scroll 0 0; list-style-type:none; margin:0; padding:0; width:540px; } element.style { margin-bottom:0; margin-left:0; margin-right:0; margin-top:0; padding-bottom:0; padding-left:0; padding-right:0; padding-top:0; width:195px; } #content form select { margin:0 0 4px 4px; z-index:1; } html, body, div, p, form, input, select, textarea, fieldset { -x-system-font:none; color:#333333; font-family:Arial,Helvetica,Verdana,sans-serif; font-size:11px; font-size-adjust:none; font-stretch:normal; font-style:normal; font-variant:normal; font-weight:normal; line-height:15px; } * { margin:0; padding:0; } </code></pre> <p>Thanks for any suggestions.</p> <h1>Edit</h1> <p>I've added the CSS for the divs that the drop downs are contained in. Also changing the line height doesn't make a difference. The only difference between the two drop downs (Item and Quantity) is the width. Changing the width on Item doesn't make a difference.</p> <p>Took out the Add another item link as that was suspected to be a problem no change. Also I am doing my development in Firefox I just posted the screenshot from Safari.</p>
<p>It looks like you are setting "line-height:15px;" on "select" elements. Remove that and see if it fixes the issue.</p>
Modifying the window opened by javascript's "window.open()" function <p>Here's my scenario:</p> <p>I have a page containing several links; each link is meant to open another window containing a pdf. The catch is, I can't have that window directly go to the PDF because I do not want to make it apparent to the end user the PDF is located on another domain, and I need to name the PDF differently than how it would regularly show up.</p> <p>So then I have two pages: One is blank, and only contains a frame to be used for displaying the pdfs:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;[PDF]&lt;/title&gt; &lt;/head&gt; &lt;frameset&gt; &lt;frame id="pdfFrame"&gt; &lt;/frameset&gt; &lt;/html&gt; </code></pre> <p>And on the page with the links, I have the following function that calls this page (we'll call the above page "pdf.html"):</p> <pre><code>function OpenWindow(pdfTitle, pdfLocation) { var myWindow = window.open("pdf.html", "", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=700,height=600"); myWindow.document.title = pdfTitle; myWindow.document.getElementById('pdfFrame').src = pdfLocation; } </code></pre> <p>For the most part, this seems to work fine; however, on occasion the pop up window will not be loaded prior to the lines above that setup the title/frame source, and it will crash (or not load properly, at least).</p> <p>My question is, is there a simple way for me to add in some sort of blocking call after opening the window, to wait until we're ready to run this code?</p> <p>Thanks!</p>
<p>You can't really block until it's loaded but you can set an event in the popup, like this:</p> <pre><code>myWindow.onload = function() { document.title = pdfTitle; document.getElementById('pdfFrame').src = pdfLocation; } </code></pre>
Office documents prompt for login in anonymous SharePoint site <p>I have a MOSS 07 site that is configured for anonymous access. There is a document library within this site that also has anonymous access enabled. When an anonymous user clicks on a PDF file in this library, he or she can read or download it with no problem. When a user clicks on an Office document, he or she is prompted with a login box. The user can cancel out of this box without entering a log in, and will be taken to the document.</p> <p>This happens in IE but not FireFox.</p> <p>I see some references to this question on the web but no clear solutions: <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.sharepoint.windowsservices.development&amp;tid=5452e093-a0d7-45c5-8ed0-96551e854cec&amp;cat=en_US_CC8402B4-DC5E-652D-7DB2-0119AFB7C906&amp;lang=en&amp;cr=US&amp;sloc=&amp;p=1">http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.sharepoint.windowsservices.development&amp;tid=5452e093-a0d7-45c5-8ed0-96551e854cec&amp;cat=en_US_CC8402B4-DC5E-652D-7DB2-0119AFB7C906&amp;lang=en&amp;cr=US&amp;sloc=&amp;p=1</a></p> <p><a href="http://www.sharepointu.com/forums/t/5779.aspx">http://www.sharepointu.com/forums/t/5779.aspx</a></p> <p><a href="http://www.eggheadcafe.com/software/aspnet/30817418/anonymous-users-getting-p.aspx">http://www.eggheadcafe.com/software/aspnet/30817418/anonymous-users-getting-p.aspx</a></p>
<p>To disable login prompt opening office documents from SharePoint 2010 do the following settings in web.config</p> <pre><code>&lt;system.webServer&gt; &lt;security&gt; &lt;requestFiltering allowDoubleEscaping="true"&gt; &lt;!-- here's where the magic happens --&gt; &lt;verbs allowUnlisted="true"&gt; &lt;add verb="OPTIONS" allowed="false" /&gt; &lt;add verb="PROPFIND" allowed="false" /&gt; &lt;/verbs&gt; &lt;/requestFiltering&gt; &lt;/security&gt; &lt;/system.webServer&gt; </code></pre>
Java equivalent to PHP's preg_replace_callback <p>I'm in the process of moving an application from PHP to Java and there is heavy use of regular expressions in the code. I've run across something in PHP that doesn't seem to have a java equivalent:</p> <pre><code>preg_replace_callback() </code></pre> <p>For every match in the regex, it calls a function that is passed the match text as a parameter. As an example usage:</p> <pre><code>$articleText = preg_replace_callback("/\[thumb(\d+)\]/",'thumbReplace', $articleText); # ... function thumbReplace($matches) { global $photos; return "&lt;img src=\"thumbs/" . $photos[$matches[1]] . "\"&gt;"; } </code></pre> <p>What would be the ideal way to do this in Java?</p>
<p>Trying to emulate PHP's callback feature seems an awful lot of work when you could just use appendReplacement() and appendTail() in a loop:</p> <pre><code>StringBuffer resultString = new StringBuffer(); Pattern regex = Pattern.compile("regex"); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { // You can vary the replacement text for each match on-the-fly regexMatcher.appendReplacement(resultString, "replacement"); } regexMatcher.appendTail(resultString); </code></pre>
How to restrict client control area in a custom WinForms control <p>I have a custom control that uses a designer I've inherited from ParentControlDesigner to allow child controls to be dropped. I'm not using any internal designers, just straightforward single-parent stuff.</p> <p>This control draws a "header", so I'm trying to do three things:</p> <ol> <li><p>Have child controls dock to the bottom of the header instead of the top of the control, when set to Top or Fill.</p></li> <li><p>Have child controls snap to the bottom of the header when dragging with the mouse, instead of the top of the control.</p></li> <li><p>Prevent controls from being dragged onto the header area, period (I have a feeling this may not be possible).</p></li> </ol> <p>(1) is the most important - I know it's possible because I've seen other controls that do it. (2) would also be a major help. (3) I don't care about that much, it would just be nice to have.</p> <p>Would anyone be able to point me in the right direction on how to implement these rules, <b>without</b> having to resort to a clumsy sub-panel and the InternalControlDesigner methods?</p>
<blockquote> <p>Prevent controls from being dragged onto the header area, period (I have a feeling this may not be possible)</p> </blockquote> <p>Having the control (the control itself, not the designer) override <code>Control.DisplayRectangle.get</code> may help restrict its children.</p>
What's the efficiency and quality of this shuffling algorithm? <p>This recent question about <a href="http://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c">sorting randomly using C#</a> got me thinking about the way I've sometimes shuffled my arrays in Perl.</p> <pre><code>@shuffled = sort { rand() &lt;=&gt; rand() } @array; </code></pre> <p>The proposed solution in the mentioned question is <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle" rel="nofollow">Fisher-Yates shuffle</a>, which works in a linear time.</p> <p>The question is: how efficient is my snippet and is such shuffle "really" random?</p>
<p>I'm not a Perl internals expert, so I don't know how "sort" will work here. However, most sort functions expect consistency in their comparisons, and I would expect them to work unpredictably if the function is itself random. Unfortunately, unpredictability is not the same as randomness, and so I'd have no confidence in your shuffled array. It may tend to put elements in some sort of order, just as a hastily created and complicated recurrence relation may not be random.</p> <p>Rather than analyze the sort function, I'd suggest going with Fisher-Yates.</p> <p>As Knuth said, randomness is too important to be left to chance.</p>