instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>When including a header file in C++, what's the difference between...</p> <ol> <li><p>including the <em>.h</em> part versus not including <em>.h</em> part when wrapping it in <em>&lt;&gt;</em> signs?</p> <p>#include &lt;iostream&gt; vs. #include &lt;iostream.h&gt;</p> </li> <li><p>wrapping the header name in double quotes versus wrapping it in &lt; &gt; signs?</p> <p>#include &lt;iostream.h&gt; vs. #include &quot;iostream.h&quot;</p> </li> </ol>
<p>In short:</p> <p><code>iostream.h</code> is deprecated&mdash;it is the original Stroustrup version. <code>iostream</code> is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases, they will both exist and be different (to support legacy code) and you then must be specific.</p> <p><code>""</code> versus <code>&lt;&gt;</code> simply means check the local directories for the header before going to the library (in most compilers).</p>
<p>The compiler is free to add a missing &quot;.h&quot; (or whatever it wants) to a standard header name in order to determine the name of the actual disk file to read, if the compiler indeed gets standard headers from actual disk files. So the user program can say &quot;#include &lt;iostream&gt;&quot; and the compiler could be smart enough to open up a file named &quot;iostream.h&quot; (or whatever it wants) in some directory it knows about (or is told about via command line switches). The standard does not require the standard header to be in an actual disk file of text with any particular name.</p>
26,337
<p>Since C# is in many ways a direct derivative of Java I wondered whether there was any advantage to learning Java after the fact of having learnt quite a reasonable about about C#?</p> <p><strong>Note:</strong> Please provide clear, direct advice rather than discussion in order to keep in line with SO guidelines.</p>
<p>If you want to program in Java, learn Java. It really is that simple.</p> <p>The patterns, algorithms, and design ideas aren't going to be different enough that learning the language on its own is reward enough.</p> <p>However, Java runs acceptably well on vastly more platforms than does C# (though with mono that's changing) so if you want to dip your toe into platform agnostic code, you might give Java a try. You'll notice it's a bit rougher around the edges, but not like going to C++ or C.</p> <p>-Adam</p>
<p>Absolutely. A lot of jobs want java specifically. Having learnt Java and being able to put it convincingly on your resume means you wont have to wrangle with HR and recruiters who do not have that much clue.</p> <p>And since both are more or less same except in a few places, its a very good return on investment. Not to mention it opens up possiblities of using other frameworks.</p>
15,095
<p>In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement. </p> <p>So what is the best way to store the unit of measurement? I've used a couple of approaches in the past:</p> <p>1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query.</p> <p>2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm".</p> <p>Neither of these feel particularly elegant to me.. can anyone suggest something better?</p>
<p>Have you seen <a href="http://github.com/vigetlabs/constant_cache/tree/master" rel="nofollow noreferrer">constant_cache</a>? It's sort of the combination of the best of 1 and 2 - lookup data is stored in the DB, but it's exposed as class constants on the lookup model and only loaded at application start, so you don't suffer the join penalties constantly. The following example comes from the README:</p> <p>migration:</p> <pre><code>create_table :account_statuses do |t| t.string :name, :description end AccountStatus.create!(:name =&gt; 'Active', :description =&gt; 'Active user account') AccountStatus.create!(:name =&gt; 'Pending', :description =&gt; 'Pending user account') AccountStatus.create!(:name =&gt; 'Disabled', :description =&gt; 'Disabled user account') </code></pre> <p>model:</p> <pre><code>class AccountStatus &lt; ActiveRecord::Base caches_constants end </code></pre> <p>using it:</p> <pre><code>Account.new(:username =&gt; 'preagan', :status =&gt; AccountStatus::PENDING) </code></pre>
<p>Do you need to perform lookups on these values? If not, you could as well store them as a string and parse the string later on in the application that reads the values. While you risk storing unparseable data, you gain speed and reduce DB complexity. Sometimes normalizing a database is not helpful. In the end /something/ within your system needs to know that "cm" is a length measure and "m3" is a room measure and comparing "3cm" to "1m3" doesn't make any sense anyway. So you just as well can put all that knowledge in code.</p> <p>Let's say you are only going to display that data anyway, what is normalizing good for here?</p>
14,629
<p>Is it possible to call a function from PHP using <code>onsubmit</code> from JavaScript? If so could someone give me an example of how it would be done?</p> <pre><code>function addOrder(){ $con = mysql_connect("localhost", "146687", "password"); if(!$con){ die('Could not connect: ' . mysql_error()) } $sql = "INSERT INTO orders ((user, 1st row, 2nd row, 3rd row, 4th row) VALUES ($session-&gt;username,1st variable, 2nd variable, 3rd variable, 4th variable))"; mysql_query($sql,$con) if(mysql_query($sql,$con)){ echo "Your order has been added"; }else{ echo "There was an error adding your order to the databse: " . mysql_error(); } } </code></pre> <p>That's the function I am wanting to call. Its an ordering system, you type in how much of each item you want, hit submit and it <em>should</em> add the order to the table.</p>
<h2>You can not call a PHP function from Javascript...</h2> <p>Javascript is a client language (it's executed on the Web browser, after receiving the web page) while PHP is on the server side (it's executed before the web page is rendered). You have no way to make one call another.</p> <h2>...but you can get the result of an external PHP script</h2> <p>There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.</p> <p>This process is what we call <a href="http://fr.wikipedia.org/wiki/Ajax" rel="noreferrer">AJAX</a>, and it's far easier to do it with a good tool than yourself. Have a look to <a href="http://www.jquery.info/" rel="noreferrer">JQuery</a>, it's powerful yet easy to use Javascript library that has built-in AJAX helpers.</p> <p>An example with JQuery (client side) :</p> <pre><code>$.ajax({ type: "POST", // the request type. You most likely going to use POST url: "your_php_script.php", // the script path on the server side data: "name=John&amp;location=Boston", // here you put you http param you want to be able to retrieve in $_POST success: function(msg) { alert( "Data Saved: " + msg ); // what you do once the request is completed } </code></pre>
<p>Yes, another great and easy tutorial for learning ajax is:</p> <p><a href="http://24ways.org/2005/easy-ajax-with-prototype/" rel="nofollow noreferrer">http://24ways.org/2005/easy-ajax-with-prototype/</a></p> <p>Prototype is another thing I recommend if you havent gone to far with your project and need to revert a lot of functionality.</p> <p><a href="http://www.prototypejs.org/" rel="nofollow noreferrer">http://www.prototypejs.org/</a></p> <p>Good luck!</p>
27,286
<p>I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but:</p> <ul> <li>It is an older version (lacking features I need)</li> <li>I need slightly different compile options than the default.</li> </ul> <p>What is the easiest way of doing it? I am concerned about a couple of things</p> <ul> <li>How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.)</li> <li>How I can I prevent the update system installing the older version in the repo on an update?</li> <li>How I can prevent the system installing a newer version (when its out), overwriting my custom package?</li> </ul>
<p>you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.</p> <p>You can use "uupdate" (<code>apt-get install devscripts</code>) to build a package from source with existing debian sources:</p> <p>Example for libdrm2:</p> <pre><code>apt-get build-dep libdrm2 apt-get source libdrm2 cd libdrm-2.3.1 uupdate ~/Downloads/libdrm-2.4.1.tar.gz cd ../libdrm-2.4.1 dpkg-buildpackage -us -uc -nc </code></pre>
<p><a href="http://tldp.org/HOWTO/html_single/Debian-Binary-Package-Building-HOWTO/" rel="nofollow noreferrer">Here</a> is a tutorial for building a Debian package.</p> <p>Basically, you need to:</p> <ol> <li>Set up your folder structure</li> <li>Create a <strong>control</strong> file</li> <li>Optionally create <strong>postinst</strong> or <strong>prerm</strong> scripts</li> <li>Run dpkg-deb</li> </ol> <p>I usually do all of this in my Makefile so I can just type <strong>make</strong> to spit out the binary and package it in one go.</p>
15,897
<p>I am consuming the Twitter API and want to convert all URLs to hyperlinks. </p> <p>What is the most effective way you've come up with to do this?</p> <p>from</p> <pre><code>string myString = "This is my tweet check it out http://tinyurl.com/blah"; </code></pre> <p>to</p> <pre><code>This is my tweet check it out &lt;a href="http://tinyurl.com/blah"&gt;http://tinyurl.com/&gt;blah&lt;/a&gt; </code></pre>
<p>Regular expressions are probably your friend for this kind of task:</p> <pre><code>Regex r = new Regex(@"(https?://[^\s]+)"); myString = r.Replace(myString, "&lt;a href=\"$1\"&gt;$1&lt;/a&gt;"); </code></pre> <p>The regular expression for matching URLs might need a bit of work.</p>
<p>/cheer for RedWolves</p> <blockquote> <p>from: this.replace(/[A-Za-z]+://[A-Za-z0-9-<em>]+.[A-Za-z0-9-</em>:%&amp;\?/.=]+/, function(m){...</p> <p>see: /[A-Za-z]+://[A-Za-z0-9-<em>]+.[A-Za-z0-9-</em>:%&amp;\?/.=]+/</p> </blockquote> <p>There's the code for the addresses "anyprotocol"://"anysubdomain/domain"."anydomainextension and address", </p> <p>and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper "a href"s where needed.</p> <p>I used jQuery to change the attributes of these links to "target=_blank" easily in my content-loading logic even though the .link method doesn't let you customize them.</p> <p>I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.</p> <p>Maybe a vet will stumble along here and enlighten us.</p>
5,260
<p>Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?</p>
<p>BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:</p> <pre><code>#define MY_BUFFER_SIZE 1024 char mybuffer[MY_BUFFER_SIZE]; int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE); </code></pre>
<p>Your sockets implementation doesn't require the buffer, to be big enough, to hold the entire message for sure, but it might be convenient depending on, what You are doing.</p>
17,288
<p>Is there an easy way in either language to generate a large set of random data quickly so far all the functions I've tried haven't worked too well when I need to generate a group of say 500,000 characters :( Any ideas?</p>
<blockquote> <p>Use UUIDGen.</p> </blockquote> <p>Don't. GUIDs aren't really random. You can actually generate large amounts of data very fast using the <code>System.Random</code> class in VB.NET. 500,000 characters/bytes are no problem:</p> <pre><code>Dim buffer As Byte() = Nothing Array.Resize(buffer, 500000) Call New Random().NextBytes(buffer) My.Computer.FileSystem.WriteAllBytes("filename", buffer, False) </code></pre> <p>This code takes <em>considerably</em> less than one second.</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/ms526809(EXCHG.10).aspx" rel="nofollow noreferrer">UUIDGen</a>. At least the chunks will be bigger.</p>
43,087
<p>I'm <em>considering</em> migrating my c# application from using custom GDI+ drawn controls to a WPF application with custom controls etc. I would like to know what's involved and what to expect.</p> <p>Are there any resources people can recommend that might help? Or indeed any personal experiences that might be beneficial?</p>
<p><em>(I apologize in advance for the long post ... there was just so much I wanted to convey ... I hope it helps you.)</em></p> <p>This is what we are doing now (migrating a Windows Forms application with heavy use of custom (GDI+) drawn controls to WPF). In fact, my role on the team was to build these GDI+ controls ... and now to build the WPF ones.</p> <p>I agree with Bijington that making your application completely 100% WPF from the ground up is the way to go ... if you can convince the powers that be to go that route. However, we ourselves are converting our Windows Forms application in-place, taking advantage of the <a href="http://msdn.microsoft.com/en-us/library/ms742522.aspx" rel="nofollow noreferrer">WPF interop</a> capabilities. There are some limitations, but overall it has been an effective approach (and not as frustrating as I would have expected).</p> <p><strong>What I would suggest is that you take one of your GDI+ controls and build the same control in WPF.</strong> And then, when you are finished, throw it away and do it again. You will invariably learn something during the first effort ... and discover that there is a better way to do it instead. I would start with something small ... a custom button is a good place to begin.</p> <p>Doing the above will give you a taste for what is going to be required for everything else you want to do.</p> <p>One thing I would warn you about is WPF's learning curve, especially if you are coming from a Windows Forms background ... and especially if you are going to be building custom looking controls. As Abe has mentioned, it is a completely different world. WPF definitely brings a lot of power, but that power comes at a cost of learning how to use it. Abe mentions how custom controls in WPF are 'lookless' and that their 'look' can be provided with a ControlTemplate. This is just one of many ways in WPF to provide custom looking pieces of your user interface.</p> <p>Let me enumerate some of those additional ways:</p> <ol> <li>Style an existing control using the styling capabilities of WPF.</li> <li>Take advantage of WPF's content model and/or controls derived from ContentControl. This allow you to stick arbitrary looking 'content' into visuals of a control (e.g. maybe sticking a custom drawn shape into the middle of a button).</li> <li>Compose a control out of other controls/elements by taking advantage of UserControl.</li> <li>Derive from an existing control/class in WPF, extending it's behavior and providing a different default set of visuals.</li> <li>Derive from FrameworkElement, creating a custom WPF element, by overriding some or all of the MeasureOverride, ArrangeOverride, and OnRender methods.</li> <li>And more .... if you can believe it.</li> </ol> <p>In Windows Forms, it was like they gave you a hammer (UserControl) and a screwdriver (Control). However, in WPF ... they have given you the whole toolbox with all 100 tools. And this is part of the reason for the bigger than normal learning curve. However, now you can take that saw that you never had before and use it to saw off the end of a 2x4 instead of using the hammer and/or screwdriver to try and do the same thing.</p> <h3>Resources</h3> <p><em>(The good news is that there are a lot out of resources out there to help you.)</em></p> <ol> <li><strong>Books</strong> <ul> <li>Programming WPF by Chris Sells &amp; Ian Griffiths (in particular, chapter 18)</li> <li>Pro WPF by Matthew MacDonald (in particular, chapter 24)</li> <li>WPF Unleashed by Adam Nathan (in particular, chapter 16)</li> <li>Applications = Code + Markup by Charles Petzold (in particular, chapters 10, 11, &amp; 12)</li> <li>Essential WPF by Chris Anderson (in particular, chapter 3)<br><br> My favorite books are Charles Petzold's book and Adam Nathan's book. However, chapter 18 of Programming WPF by Sells &amp; Griffiths is really great overview of the subject, and in particular coverage of the question: Do I really need a custom control?</li> </ul></li> <li><strong>Forums</strong> <ul> <li>The <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/threads/" rel="nofollow noreferrer">WPF Forum</a></li> <li>StackOverflow<br> Here are two posts in particular that you will want to take a look at (<a href="https://stackoverflow.com/questions/183315/what-are-the-best-resources-for-learning-wpf-net">one</a>, <a href="https://stackoverflow.com/questions/129772/how-to-begin-wpf-development">two</a>).</li> </ul></li> <li><p><strong>MSDN</strong><br> I agree with Bijington that the <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" rel="nofollow noreferrer">MSDN documentation</a> excellent.</p></li> <li><p><strong>Blogs</strong><br> In <a href="https://stackoverflow.com/questions/129772/how-to-begin-wpf-development#154252">one</a> of the two StackOverflow posts that I reference in the Forums section above, I point to a set of blogs on my 'must read' list. In particular, I would especially point to the blogs of <a href="http://blog.pixelingene.com/" rel="nofollow noreferrer">Pavan Podila</a> and <a href="http://work.j832.com/" rel="nofollow noreferrer">Kevin Moore</a>. Kevin Moore used to be the WPF program manger for the WPF controls and he has a nice set of controls called the <a href="http://j832.com/bagotricks/" rel="nofollow noreferrer">WPF Bag-o-Tricks</a> that are useful, but more importantly, controls that you can learn from.</p></li> <li><p><strong>Samples, Samples, and more Samples</strong><br> There are just a ton of samples out there. Almost too many! I would point to <a href="http://www.codeplex.com/familyshow" rel="nofollow noreferrer">Family.Show</a> (it was created as an end-to-end reference sample for WPF) and I would point to the <a href="http://msdn.microsoft.com/en-us/library/ms771633.aspx" rel="nofollow noreferrer">WPF SDK samples</a> and in particular to the <a href="http://msdn.microsoft.com/en-us/library/ms771268.aspx" rel="nofollow noreferrer">Control Customization samples</a> within that section.</p></li> </ol>
<p>This is actually a project i am working on at the moment although I have been lucky enough to be able to start again. If you can do this I would strongly recommend it, obviously keeping the core functionality of the old system/controls but start afresh. It is always nice to start from a base and to know where things went wrong/right previously.</p> <p>Personally i have found the <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" rel="nofollow noreferrer">msdn website</a> extremely useful, if not stackoverflow is a very good place for knowledge. I would be happy to give pointers if you need any.</p> <p>Also if you ever have any questions about databinding this is the place to go: <a href="http://www.beacosta.com/blog/" rel="nofollow noreferrer">bea costa</a> she has covered most stuff there.</p> <p>On an extra note we have experienced a huge improvement in performance with using wpf over GDI.</p>
34,174
<p>I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal.</p> <p>What is the simplest way to implement continuations for Scheme in C?</p>
<p>I remember reading an article that may be of help to you: <em><a href="http://home.pipeline.com/~hbaker1/CheneyMTA.html" rel="noreferrer">Cheney on the M.T.A.</a></em> :-)</p> <p>Some implementations of Scheme I know of, such as <a href="http://sisc.sourceforge.net/" rel="noreferrer">SISC</a>, allocate their call frames on the heap.</p> <p>@ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter. :-P</p>
<p>Use an explicit stack instead.</p>
2,824
<p>Is there a stand-alone GUI designer that can read and write the .form files that NetBeans (Matisse) generates? I like the GUI designer, but I don't want all the overhead of a complete Java IDE just to create and edit .form XML files.</p>
<p>You could check out <a href="http://www.jformdesigner.com/" rel="nofollow noreferrer">JFormDesigner</a>. I know it can import Netbeans .form files, but I'm not sure how it works vice versa. Available both as stand-alone and as plug-in to severals IDEs.</p>
<p>There are probably none available. The form editor has several features that are not trivial to implement, such as custom controls and code.<br> It's simply to complex and not useful enough.</p>
33,056
<p>I had telephone interview question yesterday. The interviewer asked me if I had faced any challenging debugging issue? I told him I once faced a problem debugging someone else's code and it took me 3-4 days to solve that. I used Windbg, symbols and a crash dump to solve the problem.</p> <p>Now is this enough to tell? What is interviewer expecting?</p> <p>I don't know what else to tell, I faced that problem quite some time back and can't explain all details...</p> <p>This question is very very common and I am not sure what the right answer to it?</p> <p>One more question that is very common:</p> <p>Have you worked on multi-threaded applications? How can you find out deadlock? Answer: Well to find deadlock we can look at snapshot of process in memory and can look at threads that are waiting.</p> <p>Then next question: What can you do to avoid deadlock?</p> <ol> <li>Use waitformultipleobjects</li> <li>Maintain sequence of critical sections</li> </ol> <p>What do you guys say?</p>
<p>The general rule for interviews is to use the STAR model (my co-op coordinator is going to be proud here...):</p> <p><b>S</b> - Describe the situation you were in<br /> <b>T</b> - Explain the task, providing enough info so that the interviewer understands the problem.<br /> <b>A</b> - Describe the action you took to solve the problem.<br /> <b>R</b> - What were the results of your actions<br /></p> <p>If you provide a concise answer, not too short or too long, 99.9% of interviewers will be satisfied.</p>
<p>Interview questions (well, the good ones at least) are not concerned about you telling the knowledge you have, its explaining to the interviewer's satisfaction that you actually do know it. </p> <p>So, whilst you could explain the full intricacies of windbg, he won't care. He will care that you know what to do and believes you. You only have to supply enough information to satisfy that. The alternative is to actually debug something in front of him to prove it and interviews never last that long :)</p> <p>So I think (from what you've said) that you know what you're talking about, that you do have that experience, that you could do it again. So lets move on to the next question to find out a little more about what else you know.</p> <p>Sometimes you many answer in a way that's a bit ambiguous, no problem - we'll just ask another one and another until we find out whether we think you're good enough for the role, or not. </p> <p>Interviews are only like exams in that its your working the interviewer is interested in, not the result.</p>
37,212
<p>I'm new to Castle Windsor and am confused about the order in the config file. This is taken from the GettingStarted1 sample. The HttpServiceWatcher class takes an IFailureNotifier implementor in it's constructor. However, no matter how I order the two components that implement this interface -- AlarmFailureNotifier and EmailFailureNotifier -- I always get EmailFailureNotifier. I know you can override which is chosen using parameters and a "service lookup" reference, but I thought that the order of declaration is used when other mechanisms are not.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor" /&gt; &lt;/configSections&gt; &lt;castle&gt; &lt;components&gt; &lt;component id="httpservicewatcher" type="GettingStartedPart1.HttpServiceWatcher, GettingStartedPart1"&gt; &lt;/component&gt; &lt;component id="alarm.notifier" service="GettingStartedPart1.IFailureNotifier, GettingStartedPart1" type="GettingStartedPart1.AlarmFailureNotifier, GettingStartedPart1" /&gt; &lt;component id="email.notifier" service="GettingStartedPart1.IFailureNotifier, GettingStartedPart1" type="GettingStartedPart1.EmailFailureNotifier, GettingStartedPart1" /&gt; &lt;component id="form.component" type="GettingStartedPart1.Form1,GettingStartedPart1" /&gt; &lt;/components&gt; &lt;/castle&gt; &lt;/configuration&gt; </code></pre>
<p>This was resolved with Castle 2.0 (that went RTM early last year).</p> <p>The latest version of Castle is 2.1.1: </p> <p><a href="http://sourceforge.net/projects/castleproject/files/InversionOfControl/2.1/Castle-Windsor-2.1.1.zip/download" rel="nofollow noreferrer">http://sourceforge.net/projects/castleproject/files/InversionOfControl/2.1/Castle-Windsor-2.1.1.zip/download</a></p> <p>Castle's releases are always a bit tricky to find (they need to update their site). I always refer to the Project list:</p> <p><a href="http://www.castleproject.org/castle/projects.html" rel="nofollow noreferrer">http://www.castleproject.org/castle/projects.html</a></p> <p>You want: MicroKernal/Windsor</p>
<p>I don't know which version you're using, but I believe this was a bug some time ago and it has been corrected in the build server version. Try that one and see what happens.</p> <p>Also, you could use default components like this: <a href="http://www.nablasoft.com/alkampfer/index.php/2008/05/27/castle-windsor-and-default-component/" rel="nofollow noreferrer">Castle Windsor and default components</a></p>
49,614
<p>Is there a way to run a regexp-string replace on the current line in the bash?</p> <p>I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line.</p> <p>My current approach is to finish the line, press <kbd>Ctrl</kbd>+<kbd>A</kbd> (to get to the start of the line), insert a # (to comment out the line), press enter and then use the <code>^oldword^newword</code> syntax (<code>^oldword^newword</code> executes the previous command after substituting oldword by newword).</p> <p>But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time).</p> <p>Probably there is some emacs-like key-command for this, that I don't know about.</p> <p>Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).</p>
<p>G'day,</p> <p>What about using vi mode instead? Just enter set -o vi</p> <p>Then you can go to the word you want to change and just do a cw or cW depending on what's in the word?</p> <p>Oops, forgot to add you enter a ESC k to o to the previous line in the command history.</p> <p>What do you normally use for an editor?</p> <p>cheers, Rob</p> <p>Edit: What I forgot to say in my original reply was that you need to think of the vi command line in bash using the commands you enter when you are in "ex" mode in vi, i.e. after you've entered the colon.</p> <p>Worst thing is that you need to move around through your command history using the ancient vi commands of h (to the left) and l (to the right). You can use w (or W) to bounce across words though.</p> <p>Once you get used to it though, you have all sorts of commands available, e.g. entering ESC / my_command will look back through you r history, most recent first, to find the first occurrance of the command line containing the text my_command. Once it has found that, you can then use n to find the next occurrance, etc. And N to reverse the direction of the search.</p> <p>I'd go have a read of the man page for bash to see what's available under vi mode. Once you get over the fact that up-arrow and down-arrow are replaced by ESC k, and then j, you'll see that vi mode offers more than emacs mode for command line editing in bash.</p> <p>IMHO natchurly! (-:</p> <p>Emacs? Eighty megs and constantly swapping!</p> <p>cheers, Rob</p>
<p>G'day,</p> <p>What about using vi mode instead? Just enter set -o vi</p> <p>Then you can go to the word you want to change and just do a cw or cW depending on what's in the word?</p> <p>Oops, forgot to add you enter a ESC k to o to the previous line in the command history.</p> <p>What do you normally use for an editor?</p> <p>cheers, Rob</p> <p>Edit: What I forgot to say in my original reply was that you need to think of the vi command line in bash using the commands you enter when you are in "ex" mode in vi, i.e. after you've entered the colon.</p> <p>Worst thing is that you need to move around through your command history using the ancient vi commands of h (to the left) and l (to the right). You can use w (or W) to bounce across words though.</p> <p>Once you get used to it though, you have all sorts of commands available, e.g. entering ESC / my_command will look back through you r history, most recent first, to find the first occurrance of the command line containing the text my_command. Once it has found that, you can then use n to find the next occurrance, etc. And N to reverse the direction of the search.</p> <p>I'd go have a read of the man page for bash to see what's available under vi mode. Once you get over the fact that up-arrow and down-arrow are replaced by ESC k, and then j, you'll see that vi mode offers more than emacs mode for command line editing in bash.</p> <p>IMHO natchurly! (-:</p> <p>Emacs? Eighty megs and constantly swapping!</p> <p>cheers, Rob</p>
4,788
<p>Two users wanted to share the same database, originally written in MS Access, without conflicting with one another over a single MDB file.</p> <p>I moved the tables from a simple MS Access database to MySQL using its <a href="http://www.mysql.com/products/tools/migration-toolkit/" rel="noreferrer">Migration Toolkit</a> (which works well, by the way) and set up Access to link to those tables via ODBC.</p> <p>So far, I've run into the following:</p> <ul> <li>You can't insert/update/delete rows in a table without a primary key (no surprise there).</li> <li>AutoNumber fields in MS Access must be the primary key or they'll just end up as integer columns in MySQL (natch, why wouldn't it be the PK?)</li> <li>The tables were migrated to MySQL's InnoDB table type, but the Access relationships didn't become MySQL foreign key constraints.</li> </ul> <p>Once the database is in use, can I expect any other issues? Particularly when both users are working in the same table?</p>
<p>I had an application that worked likewise: an MS Access frontend to a MySQL backend. It was such a huge pain that I ended up writing a Win32 frontend instead. From the top of my head, I encountered the following problems:</p> <ul> <li>Development of the ODBC link seems to have ceased long ago. There are various different versions floating around --- very confusing. The ODBC link doesn't support Unicode/UTF8, and I remember there were other issues with it as well (though some could be overcome by careful configuration).</li> <li>You probably want to manually tweak your db schema to make it compatible with MS Access. I see you already found out about the needed surrogate keys (i.e., int primary keys) :-)</li> <li>You should keep in mind that you may need to use pass-through queries to do more sophisticated SQL manipulations of the MySQL database.</li> <li>Be careful with using lots of VBA, as that tends to corrupt your frontend file. Regularly compressing the database (using main menu, Tools | Database utilities | Compress and restore, or something like that --- I'm using the Dutch version) and making <em>lots</em> of backups is necessary.</li> <li>Access tends to cause lots of network traffic. Like, really huge lots. I haven't been able to find a solution for that. Using a network monitor is recommended if you want to keep an eye on that!</li> <li>Access insists on storing booleans as 0/-1. IMHO, 0/+1 makes more sense, and I believe it is the default way of doing things in MySQL as well. Not a huge problem, but if your checkboxes don't work, you should definitely check this.</li> </ul> <p>One possible alternative would be to put the backend (with the data) on a shared drive. I remember this is well-documented, also in the help. You may want to have a look at <a href="http://allenbrowne.com/ser-01.html" rel="noreferrer">some general advice on splitting into a frontend and a backend</a> and <a href="http://allenbrowne.com/ser-13.html" rel="noreferrer">code that automatically reconnects to the backend on startup</a>; I can also send you some more sample code, or post it here.</p> <p>Otherwise, you might also want to consider MS SQL. I don't have experience with that, but I presume it works together with MS Access much more nicely!</p>
<p>If it's only two users, then Access should do just fine if you put the .mdb on a shared drive.</p> <p>Have you tried it first rather than just assume it will be a problem. </p> <p>I believe the recommended max concurrent users for Access is 5 but on occasion I've pushed it past this and never come unstuck.</p> <p>On the other hand I did once use Access as the front end to MySQL in a single user environment (me). It was a singularly unpleasant experience, I can't imagine it would become nicer with two users.</p>
2,767
<p>Using MS Access 2007, I am creating a student management database. I have tables for:</p> <ul> <li>Students </li> <li>Courses</li> <li>CourseSection</li> </ul> <p>What I needed is a way to assign students to a course section. So I created a table that links students and sessions:</p> <ul> <li>StudentsInSection (contains foreign key to students and foreign key to course section)</li> </ul> <p>I would like to create a form that allows me to edit a section and add students from the list of students. I've done lots of relational database work, just never with access. It seems like such a simple thing. Anybody know a good way to do this?</p>
<p>Create a form bound to the StudentsInSection table. If you want to be able to edit the students in the section, the easiest thing to do is to use a combo box with a row source based on the Students table with the bound column of the combo box tied to the student ID in the recordset underlying the StudentsInSection form. This form will be your subform. Set the Default View property of the form to "Datasheet" or "Continuous Forms". Save and close the form.</p> <p>Create a form bound to the CourseSection table. From the Forms list, click and drag the first form based on the StudentsInSection table onto the design area of the CourseSection form.</p> <p>In the property sheet of the new subform control, set the Link Master Fields property to the Section ID of your CourseSection table. In the Link Child Fields property, set the value to the Section ID of your StudentsInSection table. Setting these properties will filter the subform data to match the current value in the parent form as records are navigated.</p>
<p>The easiest thing you can do is create a sub-form off a main form. Base the main form off of Students and base the sub-form off of StudentsSection. On the sub form, add a pull down for selecting the course.</p> <p>That way the StudentSection will get populated with the StudentID (I assume that's your key) from the parent form, and you can set the CourseID when you set the pull down.</p>
38,768
<p>My app is installed via NSIS.</p> <p>I want the installer to install the program for all users.</p> <p>I can do this, by installing to the 'program files' directory.</p> <p>There is a database file (firebird), that all user accounts on the system should share. </p> <p>If I store this database file in the 'program files' directory it will be read only.</p> <p>If I store it in the users APPDATA directory they will each have a different copy, when one user adds data the others wont see it.</p> <p>Option 1 - In my app directory under 'program files' create a 'Data' directory, in my installer make this dir read-writeable by all, that way the user 'program files' virtualisation won't kick in and all users can update the file and see each others changes.</p> <p>Any other options ? </p>
<p>Data for all users should be stored in %ALLUSERSPROFILE%, or call SHGetFolderPath() with the parameter CSIDL_COMMON_APPDATA to get the all users storage area.</p> <p>See <a href="http://www.deez.info/sengelha/2006/02/28/windows-vista-changes/" rel="nofollow noreferrer">http://www.deez.info/sengelha/2006/02/28/windows-vista-changes/</a> for more details.</p>
<p>This is a security hole, see: <a href="http://blogs.msdn.com/oldnewthing/archive/2004/11/22/267890.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2004/11/22/267890.aspx</a></p>
13,941
<p>How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:</p> <pre><code>DECLARE @count int SET @count = 20 SELECT TOP @count * FROM SomeTable </code></pre>
<pre><code>SELECT TOP (@count) * FROM SomeTable </code></pre> <p>This will only work with SQL 2005+</p>
<p>Its also possible to use dynamic SQL and execute it with the exec command:</p> <pre><code>declare @sql nvarchar(200), @count int set @count = 10 set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table' exec (@sql) </code></pre>
21,198
<p>At work we use <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.</p> <p>I've read on several places on the Internet about a major upgrade but couldn't get it to work. Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?</p>
<p>In the newest versions (from the 3.5.1315.0 beta), you can use the <a href="http://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html" rel="noreferrer" title="Major upgrade">MajorUpgrade element</a> instead of using your own.</p> <p>For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded):</p> <pre><code>&lt;MajorUpgrade AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)" AllowSameVersionUpgrades="no" /&gt; </code></pre>
<p>This is what worked for me, even with major <strong>DOWN</strong> grade:</p> <pre><code>&lt;Wix ...&gt; &lt;Product ...&gt; &lt;Property Id="REINSTALLMODE" Value="amus" /&gt; &lt;MajorUpgrade AllowDowngrades="yes" /&gt; </code></pre>
13,935
<p>Well, we have a web app, running over JBoss and we're having an "OutOfMemory" error when trying to insert a lot of rows in several tables of a postgres DB. This is the complete environment for this error:<br/> * JBoss 4.3.x GA<br/> * Java 1.6.0<br/> * Hibernate 3.0<br/> * postgreSQL-8.3 (driver)<br/> About actual code-work environment:<br/> * The heavy part about this is that we're parsing huge amounts of xml documents each one downloaded separately from a specific URL (1 URL = 1 XML). We accomplish that by having an EJB that distributes the generated URLs to a queue, then a pool of MDBs connect using streams and generates the documents (note that we've actually had to raise stack memory due to XML documents size, and we're stuck with having to get all the document in one stream), once the document is generated it goes to another queue where another MDB pool listens.<br/> Those MDBs parse the doc, storing information in several entities (5 at least) that then are persisted in the DB (note that the transaction management is set to <i>"BEAN"</i> and is begun and commited during each MDBs work). Processing URLs sequentially is not an option because of the amount of URLs to be processed, it would take like 2 months or so... lol<br/></p> <p>Trouble is... that we parse and store like 200 URLs or so and start getting out of memory error for postgreSQL. Any ideas??</p> <p>Thanks in advance!!</p> <p>ALSO: It may be of use knowing that this error wasn't coming out before (I did parse a few thousands of that XML befor), only generating documents and parsing some of it into some entities didn't seem to bring trouble. Troubles started when we started to parse more and more of the doc into it's correspondent entities. (Like one entity having a list of "features" [other entity parsed from the same xml])</p>
<p>That sounds like you keep all beans for all 200 documents in memory.</p> <p>Instead of keeping all the data in RAM the whole time, try to get rid of it as quickly as possible.</p> <p>So when you are done with reading the data for some bean, persist it and then forget about it (set the object reference to null) except maybe for the key you need to create references.</p> <p>If you can't do this, use a profiler to make sure that you don't keep a reference to a document after you have parsed it. Usually, you don't need to keep the whole document anywhere after persisting it in the DB. If this is a problem, create a table with references which allows you to link between the documents and just keep the keys in that table in memory (instead of the whole document).</p>
<p>The short answer is more information is required. I suggest using a tool like <a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a> to help understand where memory is being consumed.</p> <p>Based on your described design: Why use two pools? If you just had a pool for the URLs, then worker threads could pull from that pool, parse the URL and create the entity beans, saving them to the DB. </p> <p>It isn't clear why you need the intermediate XML step, which sounds like a probable source of high memory consumption.</p>
48,975
<p>I've got a Subversion repository, and there are a number of users checking things in and out. However, I also need to frequently check in work for other people. I need to track the original author of the work.</p> <p>I was considering creating a property in SVN, like "originalauthor", which could track this. In cases where it was empty, I could use the author. If it was filled in, I could attribute the changes appropriately.</p> <p><em>However</em>, I can't see a way to add a property that won't persist through multiple revisions. Similarly, there doesn't seem to be a way of using commit hooks to guarantee the "originalauthor" property will be removed if there's a commit which doesn't include it.</p> <p>I could always rewrite the password file on the server to allow me to commit under their username and then restore the original password file, but that seems clunky (and doesn't let me track the fact that it was checked in on their behalf). Or I could create an additional user (so for every "User A" there's a "User A Proxy") which I could use to check in changes. Neither of these options seem appealing.</p> <p>Any suggestions, or ideas?</p>
<p>Subversion has two kinds of properties</p> <ul> <li>Properties on a file or directory. These properties are versioned</li> <li>Revision properties. These are specific to the reversion on which they apply.</li> </ul> <p>The first type is only usefull if you want all versions of the file to be marked.</p> <p>To mark a specific path the Subversion project itself adds the original author to the log message in a special format that is read by the contribulyzer script:</p> <pre><code>Patch by: Jan Jansen &lt;jan@example.com&gt; </code></pre> <p>But if you have tooling available (and can assume subversion 1.5+) you could also use</p> <pre><code>svn commit --with-revprop "original-author=Jan Jansen &lt;jan@example.com&gt;" </code></pre> <p>to create a orignal-author revision property.</p> <p>To retrieve the property you can then use svn log as:</p> <pre><code>svn log &lt;...&gt; --with-revprop original-author </code></pre>
<p>Why not have a separate branch for all the other users (who need proxies) and then when you review them (I assume you check in on their behalf because they are not allowed to do so) then you promote to the trunk?</p> <p>I am not sure why the other users are not allowed to check in on their own. PErhaps if you explain that we can provide better answers.</p>
37,957
<p>I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.</p> <p>Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.</p>
<p>I do not know if that would work with a DataGridView column but it works with ComboBoxes:</p> <pre><code>comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)); </code></pre> <p>and:</p> <pre><code>MyEnum value = (MyEnum)comboBox1.SelectedValue; </code></pre> <p>UPDATE: It works with DataGridView columns too, just remember to set the value type.</p> <pre><code>DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn(); col.Name = "My Enum Column"; col.DataSource = Enum.GetValues(typeof(MyEnum)); col.ValueType = typeof(MyEnum); dataGridView1.Columns.Add(col); </code></pre>
<p>Or, if you need to do some filtering of the enumerator values, you can loop through <code>Enum.GetValues(typeof(EnumeratorName))</code> and add the ones you want using:</p> <pre><code>dataGridViewComboBoxColumn.Items.Add(EnumeratorValue) </code></pre> <p>As an aside, rather than using a DataTable, you can set the DataSource of the DataGridView to a BindingSource object, with the DataSource of the BindingSource object set to a <code>BindingList&lt;Your Class&gt;</code>, which you populate by passing an <code>IList</code> into the constructor.</p> <p>Actually, I'd be interested to know from anyone if this is preferable to using a DataTable in situations where you don't already have one (i.e. it is returned from a database call).</p>
8,038
<p>I work in the technical department of a design agency. We use XP to manage our department's software development. I have been asked to give a short presentation describing Scrum and whether it would be suitable, in a broader context, for managing <em>client project work</em>.</p> <p>Scrum would be applied to cross functional teams containing graphic designers, information architects, content editors, user experience engineers, web designers and software developers.</p> <p><strong>What benefits could scrum bring to this sort of team?</strong></p>
<p>Based on my experience, I would say the key features of Scrum are:</p> <ul> <li>High visibility of progress.</li> <li>Regular feedback from customer.</li> <li>Predictable rhythm.</li> <li>Measurable productivity (via burndown, velocity, etc.).</li> <li>Cross-functional, self-organising teams.</li> <li>Inspect and adapt.</li> <li>Low bureaucratic overhead (meetings, documentation, etc.).</li> <li>Emphasis on face-to-face communication.</li> </ul> <p>And these features lead to the <em>following benefits</em>:</p> <ul> <li>Project can respond easily to change.</li> <li>Problems are identified early.</li> <li>Customer gets most beneficial work first.</li> <li>Work done will better meet the customers needs.</li> <li>Improved productivity.</li> <li>Ability to maintain a predictable schedule for delivery.</li> </ul>
<p>Team Spirit High visibility of progress. Frequent demonstration and early feedback from stakeholders Problems are identified early Quality of product and Improved productivity Higher customer satisfaction</p>
25,574
<p>This is an SQL problem I can't wrap my head around in a simple query Is it possible?</p> <p>The data set is (letters added for ease of understanding):</p> <pre><code>Start End 10:01 10:12 (A) 10:03 10:06 (B) 10:05 10:25 (C) 10:14 10:42 (D) 10:32 10:36 (E) </code></pre> <p>The desired output is:</p> <pre><code>PeriodStart New ActiveAtEnd MinActive MaxActive 09:50 0 0 0 0 10:00 3 (ABC) 2 (AC) 0 3 (ABC) 10:10 1 (D) 2 (CD) 1 (C) 2 (AC or CD) 10:20 0 1 (D) 1 (C) 2 (CD) 10:30 1 (E) 1 (D) 1 (D) 2 (DE) 10:40 0 0 0 1 (D) 10:50 0 0 0 0 </code></pre> <p>So, the query needed is a summary of the first table, calculating the minimum overlapping time periods (Start-End) and the maximum overlapping time periods (Start-End) from the first table within a 10 minute period.</p> <p>'New' is the number of rows with a Start in the summary period. 'ActiveAtEnd' is the number of rows active at the end of the summary period.</p> <p>I'm using Oracle, but I'm sure a solution can be adjusted. Stored procedures not allowed - just plain SELECT/INSERT (views are allowed). Its also OK to run one SQL command per 10 minute output (as once populated, that will be how it keeps up to date.</p> <p>Thanks for any ideas, including 'not possible' ;-)</p>
<p>Assuming you also have (or Create) a table named @Times with one record for each ten minute start time, How about...</p> <pre><code> Select T.Start, (Select Count(*) From testTab Where Start Between T.Start And DateAdd(minute, 10, T.Start)) New, (Select Count(*) From testTab Where Start &lt; DateAdd(minute, 10, T.Start) And EndDt &gt; DateAdd(minute, 10, T.Start)) ActiveAtEnd, (Select Max(Cnt) From (Select Count(Distinct T.Which) Cnt From (Select Distinct Start From testTab Where Start Between T.Start And DateAdd(minute, 10, T.Start) Union Select T.Start Union Select DateAdd(minute, 10, T.Start)) Z Left Join testTab T On Z.Start Between T.Start And T.EndDt Group By Z.Start) ZZ ) MaxActive, (Select Min(Cnt) From (Select Count(Distinct T.Which) Cnt From (Select Distinct Start From testTab Where Start Between T.Start And DateAdd(minute, 10, T.Start) Union Select T.Start Union Select DateAdd(minute, 10, T.Start)) Z Left Join testTab T On Z.Start Between T.Start And T.EndDt Group By Z.Start) ZZ ) MinActive From @Times T </code></pre> <p>I Created this table in SQL Server as a Table variable, using</p> <pre><code>Declare @Times Table (Start datetime Primary key Not Null) Declare @Start DateTime Set @Start = '1 Nov 2008 10:00' While @Start &lt; '1 Nov 2008 11:00' begin Insert @Times(Start) values(@Start) Set @Start = DateAdd(minute, 10, @Start) End </code></pre> <p>If you are using another product, use a temp table instead... but this approach does need a table with one record for each ten minute "period" as a hook to run against...</p> <p>with the following data, this query generates output as follows:</p> <pre><code>start endDt Which ----------------------- ----------------------- ----- 2008-11-01 10:01:00.000 2008-11-01 10:12:00.000 A 2008-11-01 10:03:00.000 2008-11-01 10:06:00.000 B 2008-11-01 10:05:00.000 2008-11-01 10:25:00.000 C 2008-11-01 10:14:00.000 2008-11-01 10:42:00.000 D 2008-11-01 10:32:00.000 2008-11-01 10:36:00.000 E 2008-11-01 10:22:00.000 2008-11-01 10:51:00.000 F 2008-11-01 10:22:00.000 2008-11-01 10:23:00.000 G Start New ActiveAtEnd MaxActive MinActive ----------------------- ----------- ----------- ----------- ----------- 2008-11-01 10:00:00.000 3 2 3 0 2008-11-01 10:10:00.000 1 2 2 2 2008-11-01 10:20:00.000 2 2 4 2 2008-11-01 10:30:00.000 1 2 3 2 2008-11-01 10:40:00.000 0 1 2 1 2008-11-01 10:50:00.000 0 0 1 0 </code></pre> <p>Warning: Null value is eliminated by an aggregate or other SET operation.</p>
<p>The New and ActiveAtEnd are fairly straightforward (assuming the the period's start and end being stored in temporary variables): </p> <pre><code>select @periodStart PeriodStart , @periodEnd PeriodEnd , n.[new] , ae.ActiveAtEnd from ( select count(*) [new] from @times where [start] &gt;= @periodStart and [start] &lt; @PeriodEnd ) n cross join ( select count(*) [ActiveAtEnd] from @times where [start] &lt; @PeriodEnd and [end] &gt;= @PeriodEnd ) ae </code></pre> <p>The Max and Min Actives are harder. You can presume a minute's granularity, so you would need to explode out active period at that granularity to be able to probe into each slice. </p> <p>I'm not sure that that's possible in a single query. </p>
38,723
<p>How can i make the inner table to overlap the parent div with 5 px while resizing?</p> <p>my current solution:</p> <pre><code>&lt;div id="crop"&gt; &lt;table style="width:105%; height:105%;"&gt; //table cells &lt;/table&gt; &lt;/div&gt; </code></pre> <p>problem is that it gets smaller when resizing... </p> <p>how can I make it constantly overlap with 5px;</p>
<p>The folling seems to work nicely in FF3, Chrome and IE7. Though using expressions in CSS styles for IE is not ideal.</p> <p>You should see that when rendered, the blue "outer" div is displayed within the "inner" div. The "inner" div will be red for browsers other than IE where it will be green instead.</p> <p>Also note, in this example I had to subtract 2px from the height of the "inner" div to adjust for the top and bottom borders.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #outer { position: relative; border: solid 1px blue; height: 100px; } #inner { position: absolute; border: solid 1px red; top: -5px; left: -5px; bottom: -5px; right: -5px; } &lt;/style&gt; &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; #inner { border: solid 1px green; height: 108px; width: expression(document.getElementById("outer").clientWidth + 10); } &lt;/style&gt; &lt;![endif]--&gt; &lt;/head&gt; &lt;body&gt; &lt;table width="100%"&gt; &lt;colgroup&gt; &lt;col /&gt; &lt;col width="100" /&gt; &lt;col width="200" /&gt; &lt;/colgroup&gt; &lt;tr&gt; &lt;td&gt; &lt;div id="outer"&gt; &lt;div id="inner"&gt; &lt;table border="1"&gt; &lt;tr&gt;&lt;td&gt;A&lt;/td&gt;&lt;td&gt;B&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;C&lt;/td&gt;&lt;td&gt;D&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt;Alpha&lt;/td&gt; &lt;td&gt;Beta&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;One&lt;/td&gt; &lt;td&gt;Two&lt;/td&gt; &lt;td&gt;Three&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Have you tried the following:</p> <pre><code>table { position: relative; top: 5px; left: 5px; margin-top: -5px; margin-left: -5px; } </code></pre> <p>This table will overlap the div with 5px at the right hand side and at the bottom. Margins are added to make the table fill the left hand side and top. Just omit the margins if you want the whole table to offset. You'd probably have to add some style to the div or content above the table, to keep the div from collapsing. </p> <p>Here's a full example:</p> <pre><code>&lt;style type="text/css"&gt; #container { background-color: red; //color added for illustration } #data { background-color: blue; //color added for illustration position: relative; top: 5px; left: 5px; margin-top: -5px; margin-left: -5px; } &lt;/style&gt; &lt;!-- ... --&gt; &lt;div id="container"&gt; some text to make the div visible at the top &lt;table id="data"&gt; &lt;!-- rows --&gt; &lt;/table&gt; &lt;/div&gt; </code></pre>
44,660
<p>All front-end developers know the pain of coding for Firefox, then viewing our then mangled pages in IE6. IE6 is still widely used (it is, however disappearing <a href="http://www.w3schools.com/browsers/browsers_stats.asp" rel="nofollow noreferrer">slowly but surely</a>... in a year and a half from the writing of this, it will be irrelevant as usage will be less than 1%) We usually used IE conditional comments to create separate CSS files for IE to render correctly. It would be great if there was a tool like Firebug for IE6. Firebug "lite" exists but it seems to be very beta and the new IE8 has an excellent built in developer tool that in many ways is better than firebug) What's the best tool for IE6? </p>
<p>As far as I know <a href="http://www.debugbar.com/" rel="nofollow noreferrer">Debugbar</a> is currently the most sophisticated debugging tool for IE. It's definitely better than IE developer, but it's still not quite as slick as firebug.</p>
<p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=18359" rel="nofollow noreferrer">Internet Explorer Developer Toolbar</a> seems to be the best option.</p>
11,030
<p>When writing fairly typical Mac code in an OS X 10.5+ environment, what are the disadvantages to using garbage collection?</p> <p>So far everything else I've written has been either 10.4 compatible or on the iPhone, so I've become fairly comfortable with retain/release, but now that I'm working on a larger project that's 10.5 only I'm wondering if there are any downsides to just going ahead and using the Objective-C 2.0 garbage collector.</p> <p>What do you guys think?</p>
<p>If you are writing new Cocoa code and targeting Mac OS X 10.5, use Objective-C garbage collection.</p> <p>If you are writing some code that may also need to run on the iPhone, you can write <em>and test</em> that code for both models very easily by keeping that code in a separate framework, writing it with property <code>-retain</code> and <code>-release</code> use, and setting both your framework and your unit test target for it to <em>GC-supported</em> rather than <em>GC-only</em>.</p> <p>Xcode will run your unit test bundle twice, once with GC on and once with GC off, and your framework will be usable under both execution models. Then if you eventually want to bring that model-level code to the iPhone, you can put it in an iPhone-targeted static library or include it directly in your iPhone project.</p> <p>Regardless of whether you're considering running your code on the iPhone, though, you should definitely target garbage collection if your application will require Leopard. It will ease development and the Objective-C garbage collector performs quite well.</p>
<p>GC is deprecated starting with 10.8. It was actually never a good idea to adopt this technology, cheerleading aside, because performance and stability goals were never met.</p> <p>Managing memory "manually" is actually very simple, because the management code can largely be factored out. My code base has &lt;1% code related to memory management, and that's larger than it needs to be. So I am also skeptical about ARC, just because the problem it's solving is so tiny that even fairly small gotchas with the technology make it less than worthwhile.</p>
46,545
<p>I'm trying to create a form that has an expandable widget. The problem is that when the widget is open, The form extends outside the limit in the content box, and it looks bad.</p> <p>I tried using <code>overflow:scroll</code> but it creates 2 ugly scrollbars that do not disappear even if the content is smaller then the content box. I only need one vertical scrollbar.</p> <p>Visual Studio also alerted that overflow-y is not available in CSS.</p>
<p>Change your overflow to <code>auto</code> and define the height and/or width of the element.</p>
<p>Swilliams gave a good answer about how to treat the symptom. But, you might want to think about the root cause too - if the content box were not constrained to a fixed size, it could shrink and/or expand to fit any size form, without scroll bars. Web pages are flexible by design, and attempts to "fix" that flexibility usually end up running into problems of this sort.</p>
28,448
<p>I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.</p> <p>Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads. </p> <p>The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?</p>
<p>Let me guess: the help "icon" is actually a link with a <code>javascript:</code> url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.</p> <pre><code>&lt;!-- clicking this link will do nothing. No onbeforeunload handler triggered. Nothing. And you could put something in before the return false bit... ...and the onunload handler would still not get called... --&gt; &lt;a href="http://www.google.com/" onclick="return false;"&gt;blah1&lt;/a&gt; &lt;!-- this should also do nothing, but IE will trigger the onbeforeunload handler --&gt; &lt;a href="javascript:void(0)"&gt;blah2&lt;/a&gt; </code></pre>
<p>I have a method that is a bit clunky but it will work in most instances.</p> <p>Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script language="Javascript" type="text/javascript"&gt; window.onbeforeunload = exitCheck; window.onunload = onCloseDoSomething; function onCloseDoSomething() { alert("This is executed at unload"); } function exitCheck(evt) { return "Any string here."} &lt;/script&gt; &lt;/head&gt; &lt;frameset rows="100%"&gt; &lt;FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx"&gt; &lt;/frameset&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.</p> <p>If the outer frame is refreshed or actually closed the events will fire.</p> <p>Like i said, not full-proof but will get round the firing of the event on every click or postback.</p>
8,219
<p>In an embedded application, we have a table describing the various address ranges that are valid on out target board. This table is used to setup the MMU.<br> The RAM address range is marked as cacheable, but other regions are marked at not cacheable. Why is that?</p>
<p>This is done so that the processor does not use stale values due to caching. When you access (regular) cached RAM, the processor can "remember" the value that you accessed. The next time you look at that same memory location, the processor will return the value it remembers without looking in RAM. This is caching.</p> <p>If the content of the location can change without the processor knowing as could be the case if you have a memory mapped device (an FPGA returning some data packets for example), the processor could return the value is "remembered" from last time, which would be wrong.</p> <p>To avoid this problem, you mark that address space as non-cacheable. This insures the processor does not try to remember the value.</p>
<p>Some areas like Flash can be read in one cycle, so do not need to be cached.</p>
11,563
<p>Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.</p>
<p>Putting project in read-only mode is really useful, when you make another instance from the previous project. So you copy all files from old project, then make changes in the new instance. It's really simple to edit files from old project by mistake (they have the same names)!</p> <p>Serg if you use linux, I suggest to put all files in read only mode with chmod in terminal:</p> <pre><code>sudo chmod 444 -R /path/to/your/project </code></pre> <p>After this operation Eclipse will tell you that file you are trying to edit is in read-only mode. I think that's enough to make the previous project safe :)</p>
<p>You can also use the close project/open project feature : close all projects and only open the one you need to work on ?</p>
12,250
<p>I'm looking for techniques to generate 'neighbours' (people with similar taste) for users on a site I am working on; something similar to the way last.fm works.</p> <p>Currently, I have a compatibilty function for users which could come into play. It ranks users on having 1) rated similar items 2) rated the item similarly. The function weighs point 2 heigher and this would be the most important if I had to use only one of these factors when generating 'neighbours'.</p> <p>One idea I had would be to just calculate the compatibilty of every combination of users and selecting the highest rated users to be the neighbours for the user. The downside of this is that as the number of users go up then this process couls take a very long time. For just a 1000 users, it needs 1000C2 (0.5 * 1000 * 999 = = 499 500) calls to the compatibility function which could be very heavy on the server also.</p> <p>So I am looking for any advice, links to articles etc on how best to achieve a system like this.</p>
<p>In the book Programming Collective Intelligence<br> <a href="http://oreilly.com/catalog/9780596529321" rel="nofollow noreferrer">http://oreilly.com/catalog/9780596529321</a><br></p> <p>Chapter 2 "Making Recommendations" does a really good job of outlining methods of recommending items to people based on similarities between users. You could use the similarity algorithms to find the 'neighbours' you are looking for. The chapter is available on google book search here: <br> <a href="http://books.google.com/books?id=fEsZ3Ey-Hq4C&amp;printsec=frontcover" rel="nofollow noreferrer">http://books.google.com/books?id=fEsZ3Ey-Hq4C&amp;printsec=frontcover</a></p>
<p>The problem seems like to be 'classification problems'. Yes there are so many solutions and approaches. </p> <p>To start exploration check this: <a href="http://en.wikipedia.org/wiki/Statistical_classification" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Statistical_classification</a></p>
18,126
<p>I'm using Server.HtmlEncode on a utf-8 string in asp-classic, which works fine until there are some accents in the string e.g. Rüstü Recber, which appears as Rüstü Recber (R&amp;#195;&amp;#188;st&amp;#195;&amp;#188; Recber in the source).</p> <p>I've tried setting the Response.Charset property to utf-8 but this doesn't make any difference.</p>
<p>Update (Solved): Adding &lt;%@CODEPAGE=65001%> at the start of the page corrected the problem (<a href="http://technet.microsoft.com/en-us/library/bb742422.aspx" rel="noreferrer">http://technet.microsoft.com/en-us/library/bb742422.aspx</a>)</p> <p>Many thanks for all of the suggestions.</p>
<p>Check if the editor you are using to view the text is set to show utf-8.</p>
31,189
<p>I need to hide a Windows form from the taskbar but I can't use <code>WS_EX_TOOLWINDOW</code> because I need the system menu and min/max buttons on the form's title bar. </p> <p>If I switch the form to a tool window at runtime the form skinning is stuffed up. From searching on the Web I see that VB has a ShowInTaskbar property and I'm wondering if this would do what I want, and whether it can be implemented in Delphi 2006. Also this project is a COM server and has no MainForm, etc.</p>
<p>There's an interesting discussion of this exact problem <a href="http://www.vbaccelerator.com/home/VB/Code/Libraries/Windows/Forcing_a_Window_to_Show_in_the_TaskBar/article.asp" rel="noreferrer">here</a> (from a VB6 persepective).</p> <p>The most relevant bit from your question's perspective is:</p> <blockquote> <p>"When you create a window, the taskbar examines the window's extended style to see if either the WS_EX_APPWINDOW (&amp;H40000) or WS_EX_TOOLWINDOW (&amp;H80) style is turned on. If WS_EX_APPWINDOW is turned on, the taskbar shows a button for the window, and if WS_EX_ TOOLWINDOW is turned on, the taskbar does not show a button for the window. A window should never have both of these extended styles. If the window doesn't have either of these styles, the taskbar decides to create a button if the window is unowned and does not create a button if the window is owned." </p> <p>Incidentally, you use the GetWindow API function with the GW_OWNER flag to determine whether a window is owned.</p> </blockquote>
<p>One way to do this in C# is:</p> <pre><code>ShowWindow(_window, SWHide); int style = GetWindowLong(_window, GWL_EXSTYLE); style |= WS_EX_TOOLWINDOW; SetWindowLong(_window, GWL_EXSTYLE, style); ShowWindow(_window, SWShow); </code></pre>
32,722
<p>I'm looking to re-organize the way we release our internal software. All of the code (PHP webapps, some Java apps and Perl scripts) is checked into Subversion repositories but there are no branches or tags, everything is checked into trunk (only around 1-3 devs per app). On the production linux servers, the software is just directly run from a working svn copy (actually most of the changes happen there as well).</p> <p>Since we have a lot of small apps and release very often small changes to the running system, I'm looking for a very lean or transparent way to do some release engineering and to clean up this mess abit.</p> <p>Are there any tools out there that may help me to do so in a heterogenous environment (language-wise) like that? Or has anyone an idea how to do this in a proper way?</p> <p>Otherwise I'd thought of writing some release (shell) scripts that automatically create subversion tags from trunk and then do a checkout of the corresponding tag to the production servers. But that sounds kinda hack'ish as well to me.</p> <p>Thanks,</p> <p>Haes.</p>
<p>Continuous Integration is definitely the way to go - any CI (even minimalist batch files) is better than none - but it'll only be as good as the policies you have in place. Since your files don't really end up as a 'binary' or 'distributable', marking a release might merely require only that you tag the repository, or even just stash the Subversion revision number somewhere. The important policy that you need is that any release can be reconstructed whenever you need it - so you can compare current and previous releases, or go back to an older release if something goes wrong. Don't worry about the 'overhead' of creating tags in svn - that's very efficient.</p> <p>A release script that does the subversion tag sounds fine. A CI implementation (I'd recommend CruiseControl since it's ideal for heterogeneous work, although heterogeneity requires a bit more configuration overhead) is great, since you can automatically kick the process off on a subversion checkin, and run automated tests that determine whether it's good enough to tag or not.</p> <p>I'd definitely not auto-deploy to a release server. A 'staging area' (call it 'nightly build', 'beta test', whatever) would be better. Let your users bang away on that before you decide it's good enough to roll out onto the production servers. And, as long as you've got the policy in place of being able to rollback to an earlier version, you've mitigated the possibility of a bad roll-out.</p> <p>The auto-checkout onto production servers is the only 'hackish' part - an automated checkout, test, tag, beta deploy is slick enough. Rolling-out to production shouldn't have an easy button, though.</p>
<p>Some Continuous Integration Servers do this sort of thing, <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a>, for example, has subversion integration. It can tag, run test, and deploy for you.</p>
31,205
<p>Is there a server implementation of <a href="http://www.freedesktop.org/wiki/Software/dbus" rel="nofollow noreferrer">DBus</a> for Java? There's a <a href="http://dbus.freedesktop.org/doc/dbus-java/" rel="nofollow noreferrer">lib</a> for clients and services (not servers).</p>
<p>It seems like since you originally asked your question, the library has gained support for what you ask for, at least the <a href="http://dbus-java.sourcearchive.com/documentation/2.8-2/DBusDaemon_8java_source.html" rel="nofollow">DBusDaemon</a> source contains a <a href="http://dbus-java.sourcearchive.com/documentation/2.8-2/classorg_1_1freedesktop_1_1dbus_1_1bin_1_1DBusDaemon_1_1DBusServer.html" rel="nofollow">DBusServer</a> class.</p>
<p>I'm not following why it would be necessary to have a language specific implementation of the server. I don't get the impression that more then one instance of DBus is intended to run in parallel on a server, so whichever events you public/subscribe to is all client side. If it's all client side that's all in java, and that's all you need to interact with. Nothing should be calling directly into the server code, so why would you need a java implementation of the server?</p>
31,731
<p>I'm a developer not a wordsmith and as such I'm stuck. </p> <p>We have a subscription based site whereby users may well come across our 401 page.</p> <p>We've decided that the IIS 401;2 page needs replacing.</p> <p>Does anyone have any examples or advise about writing a good non offensive 401 page? </p>
<p>This is an actual example - and a really funny one - supposedly taken from michaelbloomberg.com</p> <blockquote> <p>Unauthorized (401)</p> <p>Through a series of highly sophisticated and complex algorithms, this system has determined that you are not presently authorized to use this system function. It could be that you simply mistyped a password, or, it could be that you are some sort of interplanetary alien-being that has no hands and, thus, cannot type. If I were a gambler, I would bet that a cat (an orange tabby named Sierra or Harley) somehow jumped onto your keyboard and forgot some of the more important pointers from those typing lessons you paid for. Based on the actual error encountered, I would guess that the feline in question simply forgot to place one or both paws on the appropriate home keys before starting. Then again, I suppose it could have been a keyboard error caused by some form of cosmic radiation; this would fit nicely with my interplanetary alien-being theory. If you think this might be the cause, perhaps you could create some sort of underground bunker to help shield yourself from it. I don't know that it will work, but, you will probably feel better if you try something.</p> </blockquote> <p>And don't get me started on all the cool 404 pages out there....</p>
<p>It is a safe bet that Don Norman's and Jakob Nielsen's principles for Human Computer Interaction design is still valid for web design and 401 pages.</p> <p>The 401 pages is still a web-page, the main difference is a slightly more confused/frustrated user.</p> <p>Here is the design principles:</p> <ul> <li>Visibility - Can the user see that it is a 401 page and does he/she understand</li> <li>Feedback - Does the user understand what is happening </li> <li>Affordance - Does the user understand whats clickable and what to do with your interface</li> <li>Mapping - Does the user understand where to click to recover from the 401</li> <li>Constraint - limit the freedom the user have, to make it more cognitive easy for him/her to process.</li> <li>Consistency and standards - use the same standard that you used every where else in your website</li> </ul> <p>A very good and free resource on this issue, is the <a href="http://www.usability.gov/guidelines/guidelines_book.pdf" rel="nofollow">Usability Guidelines Book</a> from the US government.</p>
26,027
<p>I have a 3rd party XLL addin I'd like to wrap in my own custom vba function. How would I call the 3rd party function from my code?</p>
<p><strong>Edit:</strong> There are at least two ways to do this:</p> <hr> <p><strong>Option 1:</strong> <code>Application.Run(...)</code></p> <p>This looks like the best way to go about it, since your arguments are automatically converted to an appropriate type before being sent to the XLL function.</p> <pre><code>Public Function myVBAFunction(A as Integer, B as String, C as Double) myVBAFunction = Application.Run("XLLFunction", A, B, C) End Sub </code></pre> <p>See <a href="http://www.planatechsolutions.com/xllplus-online/faq.htm#VisualBasic" rel="noreferrer">this page</a> for more details.</p> <hr> <p><strong>Option 2:</strong> <code>Application.ExecuteExcel4Macro(...)</code></p> <p>With this method, you will have to convert any arguments into string format before passing them to the XLL function.</p> <pre><code>Public Function myVBAFunction(A as Integer, B as String, C as Double) dim macroCall as String macroCall = "XLLFunction(" &amp; A macroCall = macroCall &amp; "," &amp; Chr(34) &amp; B &amp; Chr(34) macroCall = macroCall &amp; "," &amp; C macroCall = macroCall &amp; ")" myVBAFunction = Application.ExecuteExcel4Macro(macroCall) End Sub </code></pre> <p>See <a href="http://www.planatechsolutions.com/xllplus-online/start_mt_demo_background_xla.htm" rel="noreferrer">this page</a> for more details.</p>
<p>I know this is a way late answer, but I discovered this alternate method and think it's worth sharing. You can declare the 3rd party functions in the same manner as a Win32 call. This has the added benefit of showing up in the Intellisense completion when you are coding.</p> <pre><code>Private Declare Function XLLFunction Lib "C:\PathTo3rdPartyDLL\3rdParty.xll" (ByVal A as Integer, ByVal B as String, C as Double) As Double Sub Function myVBAFunction(A as Integer, B as String, C as Double) as Double myVBAFunction = XLLFunction(A, B, C) End Sub </code></pre>
49,150
<p>I have a class which extends <code>DefaultTableCellRenderer</code>, which renders strings in a monospace font, with a particular color. By default, it appears that tabs are not rendered at all (0 spaces). How can I set the tab size and/or cause them to be rendered?</p> <p><strong>edits:</strong> By "tabs" I mean tab characters, which I would just like to be rendered as some number of spaces. Rewriting the string is an option, but I figured there was a better way.</p>
<p><a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html" rel="nofollow noreferrer"><code>DefaultTableCellRenderer</code></a> is a <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JLabel.html" rel="nofollow noreferrer"><code>JLabel</code></a> and does what a <code>JLabel</code> will do. I suggest you make yourself a custom <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/table/TableCellRenderer.html" rel="nofollow noreferrer"><code>TableCellRenderer</code></a> and return a <code>JPanel</code> with two or more <code>JLabel</code>s laid out appropriately. Alternatively use a <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html" rel="nofollow noreferrer"><code>JComponent</code></a> that overrides <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29" rel="nofollow noreferrer"><code>paintComponent</code></a> to draw as you wish. </p> <p>Note: attempting to use HTML in renderers is a really bad idea performance wise.</p>
<p>Half baked answer: replace them with space characters, the quantity you need (need some computing if used beyond just indentation of lines).</p>
23,456
<p>I've found a few resources on the subject, but they all require a deep understanding of <a href="http://en.wikipedia.org/wiki/Smalltalk" rel="noreferrer">SmallTalk</a> or <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a>, neither of which I know.</p>
<p>Here are some parser combinator libraries in more mainstream languages:</p> <ul> <li><a href="http://spirit.sourceforge.net/documentation.html" rel="noreferrer">Spirit</a> (C++)</li> <li><a href="http://jparsec.codehaus.org/" rel="noreferrer">Jparsec</a> (Java)</li> </ul>
<p><s>Cay Horstmann has <a href="http://horstmann.com/sjsu/cs152/schedule.html" rel="nofollow noreferrer">4 combinator parser lectures in Scala</a>, with exercises.</s> There is an example of parsing external DSLs in Scala <a href="http://debasishg.blogspot.com/2008/04/external-dsls-made-easy-with-scala.html" rel="nofollow noreferrer">here</a>.</p>
3,843
<p>Is Microsoft Project the best tool for managing software development or IT projects or is there an alternative that is better?</p>
<p>Project is not good for <em>managing</em> development at all. I find it marginally useful for scheduling / work breakdown.</p> <p>If you're on a Microsoft stack, <a href="http://msdn.microsoft.com/en-us/tfs2008/default.aspx" rel="nofollow noreferrer">Team Foundation Server</a> is a good project management solution. It integrates with Project for scheduling and also provides the essentials of source control, work item (task / defect) tracking, and document management (via sharepoint.) The 2008 version has matured nicely, and the 2010 version looks very promising, especially in the area of requirements specification and traceability.</p> <p>You can replicate the TFS features with a stack of open source and/or less expensive off-the-shelf software, but it is more work to integrate. It's debatable which is more flexible and easier to maintain once set up.</p> <p>The following are required, regardless of platform:</p> <ul> <li>Bug tracking</li> <li>Work item / story / progress tracking of some kind (may be managed by above)</li> <li>Collective team discussion (may be managed by above - discussion on work items, like FogBugz for example)</li> <li>Source control (anything but SourceSafe)</li> <li>Continuous build integration that runs unit tests</li> <li>Instant messaging (OpenFire works great if your network blocks external services)</li> <li>Document library</li> <li>Farm of virtualized test machines (especially useful for install/upgrade testing)</li> </ul>
<p>We use <a href="http://www.acunote.com/" rel="nofollow noreferrer">Acunote</a> at my work place, but we follow a Agile/Scrum methodology. </p> <p>What constitutes the "best tool" depends on many things. How you run your projects, who will be using them, etc.</p>
32,075
<p>Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding. Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.</p> <p>Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source? </p> <p>Code snippets would be great.</p> <p>Update: To make it more clear, Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls. </p>
<p>Here is some code I used to load a XML file from disk and bind it to a TreeView. I removed some of the normal tests for conciseness. The XML in the example is an OPML file.</p> <pre><code>XmlDataProvider provider = new XmlDataProvider(); if (provider != null) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(fileName); provider.Document = doc; provider.XPath = "/opml/body/outline"; FeedListTreeView.DataContext = provider; } </code></pre>
<p>using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider to the XMLDocument you got from the service.</p> <p>I'm not at a pc with visual studio to test it but it should be possible for you to do this.</p> <p>The steps are as you mentioned in your question:</p> <pre> 1. Get XML from webservice 2. Convert XML String to XML Document 3. Set the XMLDataProvider.Document value to your XML Document 4. Bind that to your controls </pre>
8,509
<p>I've been looking into implementing an external activator in SQL Server Express 2005, and I added the queues, services, contracts, and event notifications to the database. I also added a trigger to send a message to the target queue. Everything parses, runs, and the trigger is firing. However, when I select from the target queue, or use a quick T-SQL script to receive from the queue, nothing is there. </p> <p>I'm wondering:</p> <ol> <li>How is that even possible? Are the messages being auto-received?</li> <li>Is there any way to check while sending a message if it arrived correctly?</li> <li>Is there a better way to run a process on the server asynchronously after a trigger is fired?</li> </ol> <p>As an aside, good tutorial material for the Service Broker is hard to find. If anyone has any resources, please let me know. Right now, I'm reading a book from our companies' online resource but even that is a pain to filter through.</p> <p>Thanks,</p> <p><em>William</em></p>
<p>In answer to your first question, hopefully, you'll see something in the sys.transmission_queue system view. See <a href="http://msdn.microsoft.com/en-us/library/ms190336.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms190336.aspx</a> for documentation on that.</p> <p>If you Google that, you might find some useful troubleshooting resources too.</p> <p>Dave</p>
<p>John,</p> <p>I've only recently begun looking into the service broker in order to implement asynch messaging between DB instances. I found the following to be quite useful in getting my head around it.</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb839489(SQL.90).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb839489(SQL.90).aspx</a></p>
20,299
<p>I have valid <code>HBITMAP</code> handle of <code>ARGB</code> type. How to draw it using <em>GDI+</em>?</p> <p>I've tried method:</p> <pre><code>graphics.DrawImage(Bitmap::FromHBITMAP(m_hBitmap, NULL), 0, 0); </code></pre> <p>But it doesn't use alpha channel.</p>
<p>I've got working sample:</p> <p><em>Get info using bitmap handle: image size, bits</em></p> <pre><code>BITMAP bmpInfo; ::GetObject(m_hBitmap, sizeof(BITMAP), &amp;bmpInfo); int cxBitmap = bmpInfo.bmWidth; int cyBitmap = bmpInfo.bmHeight; void* bits = bmpInfo.bmBits; </code></pre> <p><em>Create &amp; draw new GDI+ bitmap using bits with pixel format PixelFormat32bppARGB</em></p> <pre><code>Gdiplus::Graphics graphics(dcMemory); Gdiplus::Bitmap bitmap(cxBitmap, cyBitmap, cxBitmap*4, PixelFormat32bppARGB, (BYTE*)bits); graphics.DrawImage(&amp;bitmap, 0, 0); </code></pre>
<p>Ah... but .Net doesn't use HBITMAP and GDI+ is a C++ library atop the basic Windows GDI, so I'm assuming you're using non-.Net C++.</p> <p>GDI+ has a Bitmap class, which has a FromHBITMAP() method.</p> <p>Once you have the GDI+ Bitmap instance, you can use it with the GDI+ library.</p> <p>Of course, if you can write your program in C# using .Net it will be a lot easier.</p>
22,110
<p>I have an XML that needs to be databound to a <strong>WPF TreeView</strong>. Here the XML can have different structure. The TreeView should be databound generic enough to load any permutation of hierarchy. However an <strong>XAttribute</strong> on the nodes (called <strong>Title</strong>) should be databound to the TreeViewItem's <strong>header text</strong> and <strong>not the nodename</strong>.</p> <p>XML to be bound:</p> <pre><code>&lt;Wizard&gt; &lt;Section Title="Home"&gt; &lt;Loop Title="Income Loop"&gt; &lt;Page Title="Employer Income"/&gt; &lt;Page Title="Parttime Job Income"/&gt; &lt;Page Title="Self employment Income"/&gt; &lt;/Loop&gt; &lt;/Section&gt; &lt;Section Title="Deductions"&gt; &lt;Loop Title="Deductions Loop"&gt; &lt;Page Title="Travel spending"/&gt; &lt;Page Title="Charity spending"/&gt; &lt;Page Title="Dependents"/&gt; &lt;/Loop&gt; &lt;/Section&gt; &lt;/Wizard&gt; </code></pre> <p>XAML:</p> <pre><code>&lt;Window x:Class="Wpf.DataBinding.TreeViewer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wpf.DataBinding" Title="TreeViewer" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TVTemplate"&gt; &lt;TreeViewItem Header="{Binding Path=Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel&gt; &lt;TreeView x:Name="_treeView" Style="{StaticResource TVallExpanded}" ItemsSource="{Binding Path=Root.Elements}" ItemTemplate="{StaticResource TVTemplate}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>XAML's codebehind that loads XML to XDocument and binds it to TreeView</p> <pre><code>public partial class TreeViewer : Window { public TreeViewer() { InitializeComponent(); XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml")); _treeView.DataContext = doc; } } </code></pre> <p>So in the XAML markup we are binding Name to TreeViewItem's header.</p> <pre><code>&lt;TreeViewItem Header="{Binding Path=Name}"/&gt; </code></pre> <p>However, I want to bind it to <strong>Title</strong> attribute of Section, Loop and Page in the Xml above. I read that it's not possible to use XPath while binding XDocument. But there has to be a way to bind the <strong>Title</strong> attribute to TreeViewItem's Header text. I tried using @Title, .[@Title] etc. But none seemed to work.</p> <p>This <a href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edd843b7-b378-4c2d-926f-c053dbd7b340" rel="nofollow noreferrer">thread on MSDN Forums</a> has a similar discussion.</p> <p>Any pointers would be greatly helpful.</p>
<p>Hurrah !!! I figured out how to bind XAttribute. It is not intuitive and it's not easily imaginable. But here is how it can be done.</p> <pre><code>&lt;TreeViewItem Header="{Binding Path=Attribute[Title].Value}"/&gt; </code></pre> <p>It is hard to imagine that Title can directly be used in square braces.</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc165615.aspx" rel="noreferrer">More @ this MSDN link</a></p>
<p>I think all you need to do is create a <a href="http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx" rel="nofollow noreferrer">HierarchicalDataTemplate</a> for each node type in your XML, load your xml it into an <a href="http://msdn.microsoft.com/en-us/library/ms749287.aspx" rel="nofollow noreferrer">XmlDataProvider</a>, and then bind <em>that</em> to the TreeView. The TV works with the XDP to bind data, and somewhere along the line they figure out what HDTs you have defined and match their DataType to the names of the nodes in your XML. You might have some issues with your XPATHs changing with the different types of data, but keeping those flexible is another question.</p> <p>For example, I have a little regex test app. It includes a help system which is essentially all the different regex parts listed in a tree: Categories and parts with descriptions, tooltips, and other stuff. The data about the parts is stored as an xml data source. Since its static, I just created a static resource with the application's resources:</p> <pre><code>&lt;XmlDataProvider x:Key="rxPartData" XPath="RegexParts"&gt; &lt;x:XData&gt; &lt;RegexParts xmlns=""&gt; &lt;Category Name="Character class" ToolTip="Sets of characters used in matching"&gt; &lt;RegexPart Regex="[%]" Hint="Positive character group" ToolTip="Matches any character in the specified group (replace % with one or more characters)" /&gt; &lt;!-- yadda --&gt; &lt;/Category&gt; &lt;/RegexParts&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; </code></pre> <p>Next, I created <a href="http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx" rel="nofollow noreferrer">HierarchicalDataTemplates</a> for each node type in the data (again, all of this is in the application's resources):</p> <pre><code>&lt;!-- Category data template --&gt; &lt;HierarchicalDataTemplate DataType="Category" ItemsSource="{Binding XPath=*}"&gt; &lt;TextBlock Focusable="False" Text="{Binding XPath=@Name}" ToolTip="{StaticResource CategoryTooltip}" ToolTipService.InitialShowDelay="0" ToolTipService.ShowDuration="{x:Static sys:Int32.MaxValue}" ToolTipService.HasDropShadow="True" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;!-- RegexPart data template --&gt; &lt;HierarchicalDataTemplate DataType="RegexPart" ItemsSource="{Binding XPath=*}"&gt; &lt;WrapPanel Focusable="False" ToolTip="{StaticResource RegexPartTooltip}" ToolTipService.InitialShowDelay="0" ToolTipService.ShowDuration="{x:Static sys:Int32.MaxValue}" ToolTipService.HasDropShadow="True"&gt; &lt;TextBlock Text="{Binding XPath=@Regex}" /&gt; &lt;TextBlock Text=" - " /&gt; &lt;TextBlock Text="{Binding XPath=@Hint}" /&gt; &lt;/WrapPanel&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <p>Lastly, I just bound the tree to the XmlDataProvider:</p> <pre><code>&lt;TreeView Name="_regexParts" DockPanel.Dock="Top" SelectedItemChanged="RegexParts_SelectedItemChanged" ItemsSource="{Binding Source={StaticResource rxPartData}, XPath=/RegexParts/Category}" ToolTip="Click the + to expand a category; click a part to insert it"&gt; &lt;/TreeView&gt; </code></pre> <p>And that's all you have to do. The TreeView and the <a href="http://msdn.microsoft.com/en-us/library/ms749287.aspx" rel="nofollow noreferrer">XmlDataProvider</a> will take care of finding and using the correct <a href="http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx" rel="nofollow noreferrer">HDT's</a> for the correct nodes in the data. The hardest part of all this is figuring out your xpaths for binding. It can get a little tricky, as if your paths are incorrect, you'll end up getting nothing in the tree and there won't be any errors (there are ways to increase error reporting in databinding in WPF, but that's another question). </p>
29,464
<p>I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?</p>
<p>I haven't come up with a solution I'm really happy with but here are some notes:</p> <ul> <li><p>Q. What is the OO API for mail merge?</p> <p>A. <a href="http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html" rel="noreferrer">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html</a></p></li> <li><p>Q. What support groups?</p> <p>A. <a href="http://user.services.openoffice.org/en/forum/viewforum.php?f=20" rel="noreferrer">http://user.services.openoffice.org/en/forum/viewforum.php?f=20</a></p></li> <li><p>Q. Sample code?</p> <p>A. <a href="http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&amp;t=946&amp;p=3778&amp;hilit=mail+merge#p3778" rel="noreferrer">http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&amp;t=946&amp;p=3778&amp;hilit=mail+merge#p3778</a></p> <p><a href="http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&amp;t=8088&amp;p=38017&amp;hilit=mail+merge#p38017" rel="noreferrer">http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&amp;t=8088&amp;p=38017&amp;hilit=mail+merge#p38017</a></p></li> <li><p>Q. Any more examples?</p> <p>A. file:///C:/Program%20Files/OpenOffice.org_2.4_SDK/examples/examples.html (comes with the SDK)</p> <p><a href="http://www.oooforum.org/forum/viewtopic.phtml?p=94970" rel="noreferrer">http://www.oooforum.org/forum/viewtopic.phtml?p=94970</a></p></li> <li><p>Q. How do I build the examples?</p> <p>A. e.g., for WriterDemo (C:\Program Files\OpenOffice.org_2.4_SDK\examples\CLI\VB.NET\WriterDemo)</p> <ol> <li>Add references to everything in here: C:\Program Files\OpenOffice.org 2.4\program\assembly</li> <li>That is cli_basetypes, cli_cppuhelper, cli_types, cli_ure</li> </ol></li> <li><p>Q. Does OO use the same separate data/document file for mail merge?</p> <p>A. It allows for a range of data sources including csv files</p></li> <li><p>Q. Does OO allow you to merge to all the different types (fax, email, new document printer)?</p> <p>A. You can merge to a new document, print and email</p></li> <li><p>Q. Can you add custom fields?</p> <p>A. Yes</p></li> <li><p>Q. How do you create a new document in VB.Net?</p> <p>A.</p> <pre><code> Dim xContext As XComponentContext xContext = Bootstrap.bootstrap() Dim xFactory As XMultiServiceFactory xFactory = DirectCast(xContext.getServiceManager(), _ XMultiServiceFactory) 'Create the Desktop Dim xDesktop As unoidl.com.sun.star.frame.XDesktop xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _ unoidl.com.sun.star.frame.XDesktop) 'Open a new empty writer document Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader) Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _ New unoidl.com.sun.star.beans.PropertyValue() {} Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "private:factory/swriter", "_blank", 0, arProps) Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument) </code></pre></li> <li><p>Q. How do you save the document?</p> <p>A.</p> <pre><code> Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable) arProps = New unoidl.com.sun.star.beans.PropertyValue() {} storer.storeToURL("file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", arProps) </code></pre></li> <li><p>Q. How do you Open the document?</p> <p>A.</p> <pre><code> Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", "_blank", 0, arProps) </code></pre></li> <li><p>Q. How do you initiate a mail merge in VB.Net?</p> <p>A.</p> <ol> <li><p>Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple.</p></li> <li><p>In VBScript:</p> <p>Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager")</p> <p>'Now set up a new MailMerge using the settings extracted from that doc Set oMailMerge = objServiceManager.createInstance("com.sun.star.text.MailMerge")</p> <p>oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' <a href="http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType" rel="noreferrer">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType</a> oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' <a href="http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType" rel="noreferrer">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType</a> oMailMerge.execute(Array())</p></li> <li><p>In VB.Net (Option Strict Off)</p> <pre><code> Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo) Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(New [Object]() {}) </code></pre></li> <li><p>The same thing but with Option Strict On (doesn't work)</p> <pre><code> Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo) Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.GetType().InvokeMember("DocumentURL", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"}) oMailMerge.GetType().InvokeMember("DataSourceName", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("CommandType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0}) oMailMerge.GetType().InvokeMember("Command", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("OutputType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2}) oMailMerge.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error </code></pre></li> </ol></li> </ul>
<p>You should take a look at <strong><a href="http://api.openoffice.org" rel="nofollow noreferrer">Apache OpenOffice API</a></strong>. A project for creating an API for Open Office. A few languages they said to support are: C++, Java, Python, CLI, StarBasic, JavaScript and OLE.</p> <p><a href="http://codesnippets.services.openoffice.org/Writer/Writer.MailMerge.snip" rel="nofollow noreferrer">Java Example of a mailmerge in OpenOffice</a>.</p>
5,982
<p>How do I create a batch file timer to execute / call another batch through out the day Maybe on given times to run but not to run on weekends ? Must run on system times can also be .cmd to run on xp server 2003 </p>
<p>For the timer part of your script i highly reccomend using:</p> <pre><code>echo. echo Waiting For One Hour... TIMEOUT /T 3600 /NOBREAK echo. echo (Put some Other Processes Here) echo. pause &gt;nul </code></pre> <p>This script waits for 1 hour (3600 seconds) and then continues on with the script and the user cannot press any buttons to bypass the timer (besides CTRL+C).</p> <p>You can use </p> <pre><code>Timeout /t 3600 /nobreak &gt;nul </code></pre> <p>If you don't want to see a countdown on the screen.</p>
<p>You could also do this></p> <pre><code>@echo off :loop set a=60 set /a a-1 if a GTR 1 ( echo %a% minutes remaining... timeout /t 60 /nobreak &gt;nul goto a ) else if a LSS 1 goto finished :finished ::code ::code ::code pause&gt;nul </code></pre> <p>Or something like that.</p>
38,353
<p>I'm a long time Windows developer, and it looks like I'm going to be involved in porting a Windows app to the Mac.</p> <p>We've decided to use Flex/Air for the gui for both sides, which looks really slick BTW.</p> <p>My Windows application has a C++ DLL that controls network adapters (wired and wireless). This is written using the standard library and Boost, so most of it should work cross platform.</p> <p>On the Mac, what IDE/complier do most folks use if they want to write C++? Also, can someone provide a pointer to whatever APIs the Mac has that can control WiFi adapters (associate, scan, disconnect, etc)?</p>
<p>Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership.</p> <p>I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it will let you do everything you want.</p> <p>Also, I would strongly recommend <strong>against</strong> trying to use Flex/Air for your application's user experience. It may look slick to you on Windows as a Windows developer, but when it comes to providing a full Macintosh user experience such technologies aren't always a great choice.</p> <p>For one example, I think Air applications don't support the full range of Mac OS X text editing keystrokes. While not all Mac users will use all keystrokes, for those people used to them trying to type in a text field that doesn't handle (say) control-A and control-E to go to the beginning and end of field is like swimming through syrup.</p> <p>For a new application that needs to be cross-platform, I'd strongly consider building the core logic in C++ while using Cocoa on the Mac and WPF on Windows to get the best user experience on each platform. Both Mac OS X and Windows have modern native user experience technologies that their respective users are getting used to, and also have good ways for C++ code to interoperate with these technologies.</p>
<p>Xcode is used a lot, as far as I know the combination editor (e.g. <a href="http://macromates.com/" rel="nofollow noreferrer">Textmate</a>), command line gcc is in fairly heavy use too. (that's what I do on OS X)</p> <p>For all API needs head to <a href="http://developer.apple.com" rel="nofollow noreferrer">Apple's developer site</a> e.g. the <a href="http://developer.apple.com/referencelibrary/Networking/" rel="nofollow noreferrer">networking</a> API's</p>
31,639
<p>I have a sql database that stores some documents.</p> <p>A user can sign into the application, and view a list of their documents.</p> <p>When clicking a linkbutton download in a gridview of their docs, I get the file from the database, write it to the file system, and then execute this code.</p> <pre><code> System.IO.FileInfo file = new System.IO.FileInfo(System.Configuration.ConfigurationManager.AppSettings["UploadPath"] + DocumentName); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Cookies.Clear(); Response.Cache.SetCacheability(HttpCacheability.Private); Response.CacheControl = "private"; Response.Charset = System.Text.UTF8Encoding.UTF8.WebName; Response.ContentEncoding = System.Text.UTF8Encoding.UTF8; Response.AppendHeader("Content-Length", file.Length.ToString()); Response.AppendHeader("Pragma","cache"); Response.AppendHeader("Expires", "60"); Response.ContentType = GetContentType(file.Extension); Response.AppendHeader("Content-Disposition", "inline; " + "filename=\"" + file.Name + "\"; " + "size=" + file.Length.ToString() + "; " + "creation-date=" + DateTime.Now.ToString("R") + "; " + "modification-date=" + DateTime.Now.ToString("R") + "; " + "read-date=" + DateTime.Now.ToString("R")); </code></pre> <p>My GetContentType() method just returns the appropriate file type for the files I'm allowing "application/pdf, application/msw0rd, etc.</p> <p>My problem is that when the file gets saved, it's the webpage itself, not the file from the file system. And in google chrome, it's putting a .htm extension on the end of the filename, I guess because it knows it's a web page?</p> <p>Anyhow, a great first step would be to get the actual file, and not a copy of the web page in HTML they are sitting on!</p> <p>Thanks.</p>
<p>How are you sending the actual content of the file?? </p> <p>I usually use <a href="http://msdn.microsoft.com/en-us/library/12s31dhy(VS.80).aspx" rel="nofollow noreferrer">Response.TransmitFile</a> method, it basically opens the file and sends its content to the Response.OutputStream</p>
<p>Have you tried setting the content-disposition to "attachment" rather than "inline"? I believe that the browser will then prompt the user to open or save the document.</p> <p>Also, you can usually bypass the file system by writing your byte stream from the database directly to the Response object with the BinaryWrite method... This is also a case where you might want to investigate using an HTTP Handler instead on an ASPX page so that you don't need to worry about clearing the Response, etc. I have had success in the past with using a hidden iframe on the page, then using Javascript to set its src to an HTTP Handler that takes the document ID as a parameter on the QueryString.</p>
43,631
<p>When should I use an interface and when should I use a base class? </p> <p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p> <p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>
<p> Let's take your example of a Dog and a Cat class, and let's illustrate using C#:</p> <p>Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:</p> <pre class="lang-cs prettyprint-override"><code>public abstract class Mammal </code></pre> <p>This base class will probably have default methods such as:</p> <ul> <li>Feed</li> <li>Mate</li> </ul> <p>All of which are behavior that have more or less the same implementation between either species. To define this you will have:</p> <pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal public class Cat : Mammal </code></pre> <p>Now let's suppose there are other mammals, which we will usually see in a zoo:</p> <pre class="lang-cs prettyprint-override"><code>public class Giraffe : Mammal public class Rhinoceros : Mammal public class Hippopotamus : Mammal </code></pre> <p>This will still be valid because at the core of the functionality <code>Feed()</code> and <code>Mate()</code> will still be the same.</p> <p>However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:</p> <pre class="lang-cs prettyprint-override"><code>public interface IPettable { IList&lt;Trick&gt; Tricks{get; set;} void Bathe(); void Train(Trick t); } </code></pre> <p>The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. </p> <p>Your Dog and Cat definitions should now look like:</p> <pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal, IPettable public class Cat : Mammal, IPettable </code></pre> <p>Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.</p> <p>Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly <em>as required</em> basis.</p>
<p>In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.</p> <p>The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.</p>
8,099
<p>I bought a self-made Reprap Prusa Mendel 3 printer, modified to be built from cheaper materials, and immediately after the deal I got various problems. I fixed the majority of them, but don't know what the reason of the strange extruder behavior is: The stepper motor is not rotating while extruding filament, it's moving back and forth with small steps instead. I made some footage, <a href="https://www.youtube.com/watch?v=OcF9qxtxIO0" rel="nofollow noreferrer">Reprap Prusa Mendel 3d printer extruder problem</a>, hoping that someone has met a similar problem before.</p> <p>If so, please tell me what to do to make it work as it should.</p> <p>The obvious option while encountering this problem was to slacken the bolt which holds this parts together (in the left bottom corner of the video), but that did not help.</p> <p>Any ideas are very welcomed. Thanks for your time. I hope this is an appropriate kind of question here.</p>
<p>Your controller board probably requires calibration.</p> <p>It sounds like, maybe, the extruder's stepper motor is <em>not receiving sufficient</em> current, to make it turn. <strong>Or</strong>, somewhat confusingly, maybe the stepper is <em>receiving too much current</em>, and overheating.</p> <p>You don't say which controller board you are using, but regardless, there should be an adjustable potentiometer on the board, next to each of the stepper drivers, or on the stepper driver daughter boards. Like so,</p> <p><a href="https://i.stack.imgur.com/xBF9V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xBF9V.png" alt="Photo of the adjustable potentiometer" /></a></p> <p>This potentiomenter adjusts the <em>reference voltage</em> used to control the stepper motor. From this <em>reference voltage</em>, and the resistance of the stepper coils, one can determine the current, which is used to drive the stepper motor.</p> <p>For the stepper driver of the extruder, you could try turning this adjustable potentiometer slightly, in order to provide more current to the stepper, in turn to provide <em>sufficient torque</em> such that the motor is able to turn. <strong>Or</strong>, less current to stop the stepper from overheating.</p> <p>The adjustments <em>can</em> be made whilst the power is on, but a <strong>non-ferrous</strong> (i..e. plastic) screw driver should be used, so as to avoid short circuits. Also care needs to be taken, when turning the potentiometer, as they have been known to just fall apart whilst being turned. If you are paranoid, then make micro adjustments with the power turned off, and then turn back on to check the behaviour.</p> <p><strong>Note</strong>: it should go without saying that one should <strong>never disconnect a stepper whilst the power is on</strong>, as both the driver and the stepper motor may be irrevocably damaged.</p> <hr /> <p>The photo above is taken from <a href="https://bootsindustries.com/pots-calibration-ramps-1-4/" rel="noreferrer">POTs Calibration – RAMPS 1.4</a>.</p> <blockquote> <p>If a POT is set too high then the associated stepper driver will tend to overheat and go into over-temperature thermal shutdown (to prevent damage to its components). The first sign of overheating is erratic stepper motor behavior. Typically, this can be recognized by the sounds of the stepper motor suddenly losing power (thermal shutdown). If no load or movement is required of the motor, it is hard to detect whether it is over-powered as the driver is barely producing any heat.</p> </blockquote> <p>and</p> <blockquote> <p>Conversely, if the POT is set too low, the stepper motor can enter an underpowered state. This can be recognized by a lack of holding torque and a stepper motor that is skipping steps because the necessary movement requires a higher power demand than the POT setting allows for.</p> </blockquote> <hr /> <h3>Driver cooling</h3> <p>In addition to the possibility of the stepper motor over heating, it could be possible that the stepper driver is overheating, although the symptoms may be different, to those that you are experiencing. Regardless, you may still find it advantageous to cooler the controller/driver board with a fan that is always on (not temperature controlled).</p> <h3>Additional reading</h3> <ul> <li><p>RigidWiki - <a href="http://rigidtalk.com/wiki/index.php?title=Stepper_Driver_Adjustment" rel="noreferrer">Stepper Driver Adjustment</a>, which goes into further detail about the adjustment of the potentiometers, that I outlined above, as well as the <em>reference voltage</em> and the adjustment thereof.</p> </li> <li><p>RepRap Wiki - <a href="http://reprap.org/wiki/RepRapPro_Setting_Motor_Currents" rel="noreferrer">RepRapPro Setting Motor Currents</a> describes a different controller to yours, but goes into the process of adjustment, and description of the <em>reference voltage</em> (which is applicable to all boards):</p> </li> </ul> <blockquote> <p>The wiper on each potentiometer generates a DC voltage that is sent to the chip. This is the reference voltage; it defines how much current the stepping motor driver chip supplies to the motor. The bigger the reference voltage (VREF), the higher the current (A) that the chip will send to the motor. For most NEMA14 motors, the current maximum is 1A, but this will generally cause it to get warm, so a setting of 750mA is recommended. For NEMA17 motors, depending on size, the limit on current is generally between 1.3A and 1.7A. If you drive stepper motors with more current than they were designed for, the motor will get hot, and may be damaged.</p> </blockquote> <ul> <li><p>Pololu - <a href="https://www.pololu.com/product/1183" rel="noreferrer">A4988 Stepper Motor Driver Carrier with Voltage Regulators</a> - this is a very common stepper driver.</p> </li> <li><p>MyHomeFab - <a href="http://www.my-home-fab.de/epages/64756193.mobile/en_GB/?ObjectPath=/Shops/64756193/Categories/Dokumentationen/Technische_Beschreibungen/DRV8825_Schrittmotor_Strom_einstellen&amp;Locale=en_GB" rel="noreferrer">DRV8825 Adjust Stepper Current</a> goes into the adjustment of the reference voltage, for the commonly used DRV8825, which is an alternative to the popular A4988.</p> </li> <li><p>This thread, about non-actuating steppers, may also be useful, <a href="http://forums.reprap.org/read.php?41,219920" rel="noreferrer">Motors</a>, which mentions <a href="http://forums.reprap.org/read.php?41,219920,222621#msg-222621" rel="noreferrer">setting the trimpots</a> and points the OP to RepRap Wiki - <a href="http://reprap.org/wiki/Pololu_stepper_driver_board" rel="noreferrer">Pololu stepper driver board</a>, which, in turn, refers to this thread, <a href="http://forums.reprap.org/read.php?4,116813,116832,quote=1" rel="noreferrer">Strange stepper behavior</a> and this video, <a href="https://m.youtube.com/watch?v=MsOBW3lnjnI" rel="noreferrer">video-2012-02-02-16-37-26.mp4</a>, which describes a jitter in the stepper behaviour.</p> </li> </ul>
<p>I also faced similar problem. Mine was a self-made marlin/repetier. The problem was that the motor current was much less than the motor requirement and the axis were not calibrated properly. Giving recommended current according to your motor ratings and limiting your feedrate according to your calibration should work.</p>
442
<p>I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then.</p> <p>This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder).</p> <p>I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript).</p>
<p><code>cmdMyButton.attributes.add("onclick", "alert('hello');")</code> ?</p>
<p><code>button.Attributes.Add("onclick", "javascript:fireLightBox()")</code></p> <p>that's the C# but I think that the VB.NET would be pretty similar.</p>
22,769
<p>It seems like if you compile a Visual Studio solution and have a version # in your AssemblyInfo.cs file, that should propagate to say, the Windows Explorer properties dialog. This way, someone could simply right click on the *.exe and click 'properties' to see the version #. Is there a special setting in Visual Studio to make this happen?</p> <p><a href="http://content.screencast.com/users/Pincas/folders/Jing/media/40442efd-6d74-4d8a-8e77-c1e725e6c150/2008-09-24_0849.png" rel="nofollow noreferrer">example picture http://content.screencast.com/users/Pincas/folders/Jing/media/40442efd-6d74-4d8a-8e77-c1e725e6c150/2008-09-24_0849.png</a></p> <p>Edit: I should have mentioned that this is, specifically, for .NET <strong>Compact Framework</strong> 2.0, which doesn't support AssemblyFileVersion. Is all hope lost?</p>
<p>Note, that the <em>AssemblyFileVersion</em> attribute is not available under .NET <strong>Compact Framework</strong>!</p> <p>See <a href="http://www.danielmoth.com/Blog/2004/11/assemblyfileversion-on-cf.html" rel="noreferrer">this</a> article from Daniel Mooth for a workaround.</p>
<p>I'm not sure that RevisionNumber is the correct field to be looking for.</p> <p>Try explorer, right click -> version tab, and look at the AssemblyVersion field there.</p>
15,445
<p><a href="https://stackoverflow.com/questions/2556/whats-the-best-online-payment-processing-solution">This question</a> talks about different payment processors and what they cost, but I'm looking for the answer to what do I need to do if I want to accept credit card payments?</p> <p>Assume I need to <em>store</em> credit card numbers for customers, so that the obvious solution of relying on the credit card processor to do the heavy lifting is not available.</p> <p><a href="https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml" rel="noreferrer">PCI Data Security</a>, which is apparently the standard for storing credit card info, has a bunch of general requirements, but <a href="http://en.wikipedia.org/wiki/PCI_DSS" rel="noreferrer">how does one implement them</a>? </p> <p>And what about the vendors, like <a href="http://usa.visa.com/merchants/risk_management/cisp_payment_applications.html" rel="noreferrer">Visa</a>, who have their own best practices?</p> <p>Do I need to have keyfob access to the machine? What about physically protecting it from hackers in the building? Or even what if someone got their hands on the backup files with the sql server data files on it?</p> <p>What about backups? Are there other physical copies of that data around?</p> <p>Tip: <a href="http://transfs.com/blog/" rel="noreferrer">If you get a merchant account, you should negotiate that they charge you "interchange-plus" instead of tiered pricing.</a> With tiered pricing, they will charge you different rates based on what type of Visa/MC is used -- ie. they charge you more for cards with big rewards attached to them. Interchange plus billing means you only pay the processor what Visa/MC charges them, plus a flat fee. (Amex and Discover charge their own rates directly to merchants, so this doesn't apply to those cards. You'll find Amex rates to be in the 3% range and Discover could be as low as 1%. Visa/MC is in the 2% range). <a href="http://transfs.com/" rel="noreferrer">This service is supposed to do the negotiation for you</a> (I haven't used it, this is not an ad, and I'm not affiliated with the website, but this service is greatly needed.)</p> <p><em>This blog post gives a <a href="http://blog.boxedice.com/2009/05/20/taking-payments-online-merchant-account-payment-processor-fees/" rel="noreferrer">complete rundown of handling credit cards</a> (specifically for the UK).</em></p> <hr> <p>Perhaps I phrased the question wrong, but I'm looking for tips like these:</p> <ol> <li>Use <a href="http://www.rsa.com/node.aspx?id=1156" rel="noreferrer">SecurID</a> or <a href="http://www.aladdin.com/etoken/" rel="noreferrer">eToken</a> to add an additional password layer to the physical box.</li> <li>Make sure the box is in a room with a physical lock or keycode combination.</li> </ol>
<p>I went through this process not to long ago with a company I worked for and I plan on going through it again soon with my own business. If you have some network technical knowledge, it really isn't that bad. Otherwise you will be better off using Paypal or another type of service.</p> <p>The process starts by getting a <strong><a href="https://stackoverflow.com/questions/2556/whats-the-best-online-payment-processing-solution">merchant account</a></strong> setup and tied to your bank account. You may want to check with your bank, because a lot of major banks provide merchant services. You may be able to get deals, because you are already a customer of theirs, but if not, then you can shop around. If you plan on accepting Discover or American Express, those will be separate, because they provide the merchant services for their cards, no getting around this. There are other special cases also. This is an application process, be prepared.</p> <p>Next you will want to purchase an <strong>SSL certificate</strong> that you can use for securing your communications for when the credit card info is transmitted over public networks. There are plenty of vendors, but my rule of thumb is to pick one that is a brand name in a way. The better they are known, the better your customer has probably heard of them.</p> <p>Next you will want to find a <strong><a href="http://en.wikipedia.org/wiki/Payment_gateway" rel="noreferrer">payment gateway</a></strong> to use with your site. Although this can be optional depending on how big you are, but majority of the time it won't be. You will need one. The payment gateway vendors provide a way to talk to the Internet Gateway API that you will communicate with. Most vendors provide HTTP or TCP/IP communication with their API. They will process the credit card information on your behalf. Two vendors are <a href="http://www.authorize.net/" rel="noreferrer">Authorize.Net</a> and <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_payflow-pro-overview-outside" rel="noreferrer">PayFlow Pro</a>. The link I provide below has some more information on other vendors.</p> <p>Now what? For starters there are guidelines on what your application has to adhere to for transmitting the transactions. During the process of getting everything setup, someone will look at your site or application and make sure you are adhering to the guidelines, like using SSL and that you have terms of use and policy documentation on what the information the user is giving you is used for. Don't steal this from another site. Come up with your own, hire a lawyer if you need to. Most of these things fall under the PCI Data Security link Michael provided in his question.</p> <p>If you plan on storing the credit card numbers, then you better be prepared to put some security measures in place internally to protect the info. Make sure the server the information is stored on is only accessible to members who need to have access. Like any good security, you do things in layers. The more layers you put in place the better. If you want you can use key fob type security, like <a href="http://www.rsa.com/node.aspx?id=1156" rel="noreferrer">SecureID</a> or <a href="http://www.aladdin.com/etoken/default.aspx" rel="noreferrer">eToken</a> to protect the room the server is in. If you can't afford the key fob route, then use the two key method. Allow a person who has access to the room to sign out a key, which goes along with a key they already carry. They will need both keys to access the room. Next you protect the communication to the server with policies. My policy is that the only thing communicating to it over the network is the application and that information is encrypted. The server should not be accessible in any other form. For backups, I use <a href="http://www.truecrypt.org/" rel="noreferrer">truecrypt</a> to encrypt the volumes the backups will be saved to. Anytime the data is removed or stored somewhere else, then again you use truecrypt to encrypt the volume the data is on. Basically where ever the data is, it needs to be encrypted. Make sure all processes for getting at the data carries auditing trails. use logs for access to the server room, use cameras if you can, etc... Another measure is to encrypt the credit card information in the database. This makes sure that the data can only be viewed in your application where you can enforce who sees the information.</p> <p>I use <a href="http://www.pfsense.com/" rel="noreferrer">pfsense</a> for my firewall. I run it off a compact flash card and have two servers setup. One is for fail over for redundancy.</p> <p>I found this <a href="http://www.west-wind.com/presentations/aspnetecommerce/aspnetecommerce.asp" rel="noreferrer">blog post</a> by Rick Strahl which helped tremendously to understand doing e-commerce and what it takes to accept credit cards through a web application.</p> <p>Well, this turned out to be a long answer. I hope these tips help. </p>
<p>There's a lot to the whole process. The single easiest way to do it is to use services similar to paypal, so that you never actually handle any credit card data. Apart from that, there's a quite a bit of stuff to go through to get approved to offer credit card services on your website. You should probably talk with your bank, and the people who issue your merchant ID to help you in setting up the process.</p>
7,397
<p>I've written a command line utility that detects which network interface is connected, and sets the staitc ip address and dns servers for it (by calling netsh). However, I can't seem to figure out how to set the dns search suffixes. netsh doesnt appear capable of doing that. How do I do that otherwise (WMI perhaps)?</p>
<p>I think you have to set the value(s) you want in the DNSDomainSuffixSearchOrder property of the Win32_NetworkAdapterConfiguration WMI object.</p> <p>Here's and example of setting values in WMI, if you need it: <a href="http://www.developerfusion.com/article/5450/using-wmi-from-managed-code/3/" rel="nofollow noreferrer">Modifying Objects &amp; Running Methods</a></p>
<p>The dns search suffixes are valid for the whole machine, not for a single network adapter. You can also get them from registry:</p> <pre><code>string searchList = &quot;&quot;; try { using (var reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(tcpSettingsSubKey)) { searchList = (reg.GetValue(&quot;SearchList&quot;) as string); } } catch(Exception ex) { // something went wrong } </code></pre> <p>(This is not the default dns suffix when the machine is an AD member)</p>
19,960
<p>I have a MySQL query that I use to retrieve random rows from a table. The query is:</p> <pre><code>SELECT * FROM QUESTION WHERE TESTID=1 ORDER BY RAND() LIMIT 10; </code></pre> <p>Now I need to change this query to <strong><em>Hibernate</em></strong>. Did a bit of googling but couldn't find the answer. Can someone provide help on this?</p>
<p>According to this <a href="http://cephas.net/blog/2004/05/21/hibernate-returning-n-records-in-a-random-order/" rel="nofollow noreferrer">post</a>, you can do that :</p> <pre><code>String query = "from QUESTION order by newid()"; Query q = session.createQuery(query); q.setMaxResults(10); </code></pre> <p>Not sure if it will work (especially for the random part), but you can try it :)</p>
<p>According to this <a href="http://cephas.net/blog/2004/05/21/hibernate-returning-n-records-in-a-random-order/" rel="nofollow noreferrer">post</a>, you can do that :</p> <pre><code>String query = "from QUESTION order by newid()"; Query q = session.createQuery(query); q.setMaxResults(10); </code></pre> <p>Not sure if it will work (especially for the random part), but you can try it :)</p>
43,278
<p>A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive.</p> <p>The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0. </p> <p>I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly. </p> <p>Ideas very very welcome!</p>
<p>Does the host utilize App Pool?</p> <p>Did you try increase the number to 5 to 10 in </p> <pre><code>An Application Pool -&gt; Performance -&gt; Web Garden -&gt; Max Number of worker processes </code></pre>
<p>Also check for network saturation. Make sure you aren't maxing out the network connection between your load test machine and the web server. Also, if you are returning alot of heavy text/binary data between your web and database server monitor that network connection. </p>
30,036
<p>I'm building an iPhone application that talks to a Ruby on Rails backend. The Ruby on Rails application will also service web users. The restful_authentication plugin is an excellent way to provide quick and customizable user authentication. However, I would like users of the iPhone application to have an account created automatically by the phone's unique identifier ([[UIDevice device] uniqueIdentifier]) stored in a new column. Later, when users are ready to create a username/password, the account will be updated to contain the username and password, leaving the iPhone unique identifier intact. Users should not be able to access the website until they've setup their username/password. They can however, use the iPhone application, since the application can authenticate itself using it's identifier.</p> <p>What is the best way to modify restful_authentication to do this? Create a plugin? Or modify the generated code?</p> <p>What about alternative frameworks, such as AuthLogic. What is the best way to allow iPhones to get a generated auth token locked to their UUID's, but then let the user create a username/password later?</p>
<p>I think you shouldn't use the phone identifier alone to authenticate as it is not a secret and it is probably also guessable/predictable. Don't forget that if someone wanted to hack your web app they don't have to use your code - they can just guess device IDs and try to mess with your users data using any web client.</p> <p>You should treat the device ID similar to a username - it is for identification and not authentication. I suggest you get the user to pick a password, or even better generate a random code automatically, to go with it - then send the device ID + this password/code to register the device firstly, and then subsequently to authenticate the device. </p> <p>You can also bet that some users will have more than one device - either they will replace one eventually, or you will get somebody like Stephen Fry who goes around with 4 iphones. To deal with this I would suggest that you look for a way to instantiate restful_authentication twice, once for authenticating users, and a second time for authenticating devices. I haven't used this plugin but I expect you just need to use different table parameters to make this happen. Then in your application logic allow users to associate more than one device with their account.</p> <p>To do that securely either do it from the device, or have the device display a random code which they then enter into the web app to prove they own the device (this sounds more painful than it is - it is the same process that apple use in itunes, apple TV, and the remote app - look at how they do it - so it won't be that surprising for users).</p> <p>(Also make sure that when generating any random passwords you use a cryptographic random number generator as the basis - there is probably an iPhone API for this - otherwise your passwords may be predictable).</p>
<p>Have you tried to use another auth scheme like <a href="http://authlogic.rubyforge.org/" rel="nofollow noreferrer">Authlogic</a>? I've found restful_authentication rather intrusive (although I cheated by using <a href="http://matthall.wordpress.com/2008/09/09/a-bort-fork-rails-base-application/" rel="nofollow noreferrer">bort</a>).</p>
45,784
<p>Hey so what I want to do is snag the content for the first paragraph. The string <code>$blog_post</code> contains a lot of paragraphs in the following format:</p> <pre><code>&lt;p&gt;Paragraph 1&lt;/p&gt;&lt;p&gt;Paragraph 2&lt;/p&gt;&lt;p&gt;Paragraph 3&lt;/p&gt; </code></pre> <p>The problem I'm running into is that I am writing a regex to grab everything between the first <code>&lt;p&gt;</code> tag and the first closing <code>&lt;/p&gt;</code> tag. However, it is grabbing the first <code>&lt;p&gt;</code> tag and the <strong>last</strong> closing <code>&lt;/p&gt;</code> tag which results in me grabbing everything.</p> <p>Here is my current code:</p> <pre><code>if (preg_match("/[\\s]*&lt;p&gt;[\\s]*(?&lt;firstparagraph&gt;[\\s\\S]+)[\\s]*&lt;\\/p&gt;[\\s\\S]*/",$blog_post,$blog_paragraph)) echo "&lt;p&gt;" . $blog_paragraph["firstparagraph"] . "&lt;/p&gt;"; else echo $blog_post; </code></pre>
<p>Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this</p> <pre><code>&lt;p&gt;.*?&lt;/p&gt; </code></pre> <p>Placing the <code>?</code> after your <code>*</code> makes it non-greedy, meaning it will only match as little text as necessary before matching the <code>&lt;/p&gt;</code>.</p>
<p>Using Regular Expressions for html parsing is never the right solution. You should be using XPATH for this particular case:</p> <pre><code>$string = &lt;&lt;&lt;XML &lt;a&gt; &lt;b&gt; &lt;c&gt;texto&lt;/c&gt; &lt;c&gt;cosas&lt;/c&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt;código&lt;/c&gt; &lt;/d&gt; &lt;/a&gt; XML; $xml = new SimpleXMLElement($string); /* Busca &lt;a&gt;&lt;b&gt;&lt;c&gt; */ $resultado = $xml-&gt;xpath('//p[1]'); </code></pre>
5,964
<p>I want to create a view that consists solely of a <code>UITextView</code>. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the <code>UITextView</code> first in order to begin editing.</p> <p>Is this possible? I see the class has a notification called <code>UITextViewTextDidBeginEditingNotification</code> but I'm not sure how to send that, or if that is even the right approach. </p>
<p>to accomplish that just send the becomeFirstResponder message to your UITextField, as follows (assuming you have an outlet called textField, pointing to the field in question):</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [textField becomeFirstResponder]; } </code></pre>
<p>Following worked fine for me using Swift</p> <pre><code>override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Show keyboard by default billField.becomeFirstResponder() } </code></pre> <p>Key is to use the viewDidAppear function. </p>
32,467
<p>I have a home-grown automated build script in the form of a DOS batch file. In part of that script, I check out (with "svn checkout") a section of our SVN repository that includes a bunch of third-party stuff that's used in our projects. This batch file performed pretty well for a long time, but now people have checked in lots of fluff (docs, sample code, etc.) into the third-party area and the checkout part of this script has gotten lots slower. I'd like to mitigate this by checking out only the stuff we need -- mostly dll files in our case. So, my question is this: what's the best way to check out an SVN repository filtered by file extension?</p> <p>I didn't see any obvious way to do this in the svn help. I have a .NET utility library that wraps svn.exe in some ways, and I was thinking of extending this to retrieve only content that matched my extensions of interest. But I'd prefer to use an easier or existing method if one exists.</p>
<p>This is possible: you can <code>svn checkout</code> an empty directory, and then <code>svn update filename</code> for each file that you <em>do</em> want.</p> <p>Your script can do something like:</p> <ol> <li><code>svn checkout svn://path/to/repos/directory --depth empty</code></li> <li><code>svn list --recursive svn://path/to/repos/directory</code></li> <li>Pipe that result through a filter that removes the forbidden file extensions, e.g. <code>grep</code></li> <li>Iterate over this new filtered list and <code>svn update --parents</code> each file</li> </ol> <p>That would give your desired result of a working copy without certain files or file extensions.</p> <p>Of course, there is also the issue that you mention of “people [checking] in lots of fluff” but that’s a separate matter.</p>
<p>The most simple and a correct way to do this: DON'T DO IT! </p> <p>If there is some crap in third party folder where there suppose to be .dll files that needs to be checkout - remove that crap to a different location! It does not belong here anyway.</p>
23,430
<p>It's common to see a UISearchBar in an application, that upon a click, will enlarge and animate into view with a keyboard. I'm curious, is this something the iPhone SDK provides for free, or is the Animation code more than likely written by the developer? I use a UISearchBar in several controllers, however by default a keyboard just pops into view, the search bar does not animate in any fashion. This is also very prominent in apps that have a search icon. How is it typically done?</p>
<p>There is a discussion <a href="http://discussions.apple.com/thread.jspa?threadID=1652157&amp;tstart=0" rel="nofollow noreferrer">"UISearchBar like Contacts"</a> on this at the apple site.</p>
<p>Did you put it in through Interface Builder or programatically? Because by default the keyboard animation should play.</p>
46,642
<p>I'm running Vista on my laptop, but would like to virtualize Ubuntu so that I can boot it from time to time for my personal use (e.g. running code, testing Linux programs). I tried this with Virtual PC 2007 (I allocated 1G of RAM for Ubuntu), and it was very slow. Should I try Hyper-V instead? (Note: I know very little about virtualization, so I'm not sure this is the type of use that Hyper-V is intended for.)</p>
<p>I'm using the free <a href="http://www.virtualbox.org/" rel="nofollow noreferrer">Virtual Box</a> and that's worked fine for me.</p>
<p>If you don't need to have both Windows and Ubuntu running at the same time, you could try <a href="http://wubi-installer.org/" rel="nofollow noreferrer">Wubi, the Windows-based Ubuntu Installer</a>, a program that installs Ubuntu into a set of files on your Windows disk and sets you up to dual boot, without having to repartition or anything like that. The most recent version(s) of Ubuntu come with Wubi on the CD. </p>
39,124
<p>I want to be able to check the status of a publication and subscription in SQL Server 2008 T-SQL. I want to be able to determine if its okay, when was the last successful, sync, etc.. Is this possible?</p>
<p>I know this is a little late....</p> <pre><code>SELECT (CASE WHEN mdh.runstatus = '1' THEN 'Start - '+cast(mdh.runstatus as varchar) WHEN mdh.runstatus = '2' THEN 'Succeed - '+cast(mdh.runstatus as varchar) WHEN mdh.runstatus = '3' THEN 'InProgress - '+cast(mdh.runstatus as varchar) WHEN mdh.runstatus = '4' THEN 'Idle - '+cast(mdh.runstatus as varchar) WHEN mdh.runstatus = '5' THEN 'Retry - '+cast(mdh.runstatus as varchar) WHEN mdh.runstatus = '6' THEN 'Fail - '+cast(mdh.runstatus as varchar) ELSE CAST(mdh.runstatus AS VARCHAR) END) [Run Status], mda.subscriber_db [Subscriber DB], mda.publication [PUB Name], right(left(mda.name,LEN(mda.name)-(len(mda.id)+1)), LEN(left(mda.name,LEN(mda.name)-(len(mda.id)+1)))-(10+len(mda.publisher_db)+(case when mda.publisher_db='ALL' then 1 else LEN(mda.publication)+2 end))) [SUBSCRIBER], CONVERT(VARCHAR(25),mdh.[time]) [LastSynchronized], und.UndelivCmdsInDistDB [UndistCom], mdh.comments [Comments], 'select * from distribution.dbo.msrepl_errors (nolock) where id = ' + CAST(mdh.error_id AS VARCHAR(8)) [Query More Info], mdh.xact_seqno [SEQ_NO], (CASE WHEN mda.subscription_type = '0' THEN 'Push' WHEN mda.subscription_type = '1' THEN 'Pull' WHEN mda.subscription_type = '2' THEN 'Anonymous' ELSE CAST(mda.subscription_type AS VARCHAR) END) [SUB Type], mda.publisher_db+' - '+CAST(mda.publisher_database_id as varchar) [Publisher DB], mda.name [Pub - DB - Publication - SUB - AgentID] FROM distribution.dbo.MSdistribution_agents mda LEFT JOIN distribution.dbo.MSdistribution_history mdh ON mdh.agent_id = mda.id JOIN (SELECT s.agent_id, MaxAgentValue.[time], SUM(CASE WHEN xact_seqno &gt; MaxAgentValue.maxseq THEN 1 ELSE 0 END) AS UndelivCmdsInDistDB FROM distribution.dbo.MSrepl_commands t (NOLOCK) JOIN distribution.dbo.MSsubscriptions AS s (NOLOCK) ON (t.article_id = s.article_id AND t.publisher_database_id=s.publisher_database_id ) JOIN (SELECT hist.agent_id, MAX(hist.[time]) AS [time], h.maxseq FROM distribution.dbo.MSdistribution_history hist (NOLOCK) JOIN (SELECT agent_id,ISNULL(MAX(xact_seqno),0x0) AS maxseq FROM distribution.dbo.MSdistribution_history (NOLOCK) GROUP BY agent_id) AS h ON (hist.agent_id=h.agent_id AND h.maxseq=hist.xact_seqno) GROUP BY hist.agent_id, h.maxseq ) AS MaxAgentValue ON MaxAgentValue.agent_id = s.agent_id GROUP BY s.agent_id, MaxAgentValue.[time] ) und ON mda.id = und.agent_id AND und.[time] = mdh.[time] where mda.subscriber_db&lt;&gt;'virtual' -- created when your publication has the immediate_sync property set to true. This property dictates whether snapshot is available all the time for new subscriptions to be initialized. This affects the cleanup behavior of transactional replication. If this property is set to true, the transactions will be retained for max retention period instead of it getting cleaned up as soon as all the subscriptions got the change. --and mdh.runstatus='6' --Fail --and mdh.runstatus&lt;&gt;'2' --Succeed order by mdh.[time] </code></pre>
<p>In case it's helpful, I've combined parts of the two answers given and taken sp_replmonitorhelppublication and sp_replmonitorhelpsubscription and placed them into Temp Tables so I can sort them and exclude columns as needed.</p> <p>Note, the subscriber script excludes some merge columns from sp_replmonitorhelpsubscription as I'm not looking for merge replication data.</p> <pre><code>------------------------------------------------------------------------------------------------------------------------- -- PUBLISHER SCRIPT ------------------------------------------------------------------------------------------------------------------------- IF OBJECT_ID ('tempdb..#tmp_replicationPub_monitordata') IS NOT NULL DROP TABLE #tmp_replicationPub_monitordata; CREATE TABLE #tmp_replicationPub_monitordata ( publisher_db sysname , publication sysname , publication_id INT , publication_type INT , status INT -- publication status defined as max(status) among all agents , warning INT -- publication warning defined as max(isnull(warning,0)) among all agents , worst_latency INT , best_latency INT , average_latency INT , last_distsync DATETIME -- last sync time , retention INT -- retention period , latencythreshold INT , expirationthreshold INT , agentnotrunningthreshold INT , subscriptioncount INT -- # of subscription , runningdistagentcount INT -- # of running agents , snapshot_agentname sysname NULL , logreader_agentname sysname NULL , qreader_agentname sysname NULL , worst_runspeedPerf INT , best_runspeedPerf INT , average_runspeedPerf INT , retention_period_unit TINYINT , publisher sysname NULL ); INSERT INTO #tmp_replicationPub_monitordata EXEC sp_replmonitorhelppublication; SELECT (CASE WHEN status = '1' THEN 'Start - ' + CAST(status AS VARCHAR) WHEN status = '2' THEN 'Succeed - ' + CAST(status AS VARCHAR) WHEN status = '3' THEN 'InProgress - ' + CAST(status AS VARCHAR) WHEN status = '4' THEN 'Idle - ' + CAST(status AS VARCHAR) WHEN status = '5' THEN 'Retry - ' + CAST(status AS VARCHAR) WHEN status = '6' THEN 'Fail - ' + CAST(status AS VARCHAR)ELSE CAST(status AS VARCHAR)END) [Run Status] , publisher_db , publication , publication_id , (CASE WHEN publication_type = '0' THEN 'Transactional - ' + CAST(publication_type AS VARCHAR) WHEN publication_type = '1' THEN 'Snapshot - ' + CAST(publication_type AS VARCHAR) WHEN publication_type = '2' THEN 'Merge - ' + CAST(publication_type AS VARCHAR)ELSE '' END) AS [Publication Type] , (CASE WHEN warning = '1' THEN 'Expiration' + CAST(warning AS VARCHAR) WHEN warning = '2' THEN 'Latency' + CAST(warning AS VARCHAR) WHEN warning = '4' THEN 'Mergeexpiration' + CAST(warning AS VARCHAR) WHEN warning = '16' THEN 'Mergeslowrunduration' + CAST(warning AS VARCHAR) WHEN warning = '32' THEN 'Mergefastrunspeed' + CAST(warning AS VARCHAR) WHEN warning = '64' THEN 'Mergeslowrunspeed' + CAST(warning AS VARCHAR)END) warning , worst_latency , best_latency , average_latency , last_distsync , retention , latencythreshold , expirationthreshold , agentnotrunningthreshold , subscriptioncount , runningdistagentcount , snapshot_agentname , logreader_agentname , qreader_agentname , worst_runspeedPerf , best_runspeedPerf , average_runspeedPerf , retention_period_unit , publisher FROM #tmp_replicationPub_monitordata ORDER BY publication; ------------------------------------------------------------------------------------------------------------------------- -- SUBSCRIBER SCRIPT ------------------------------------------------------------------------------------------------------------------------- IF OBJECT_ID ('tempdb..#tmp_rep_monitordata ') IS NOT NULL DROP TABLE #tmp_rep_monitordata; CREATE TABLE #tmp_rep_monitordata ( status INT NULL , warning INT NULL , subscriber sysname NULL , subscriber_db sysname NULL , publisher_db sysname NULL , publication sysname NULL , publication_type INT NULL , subtype INT NULL , latency INT NULL , latencythreshold INT NULL , agentnotrunning INT NULL , agentnotrunningthreshold INT NULL , timetoexpiration INT NULL , expirationthreshold INT NULL , last_distsync DATETIME NULL , distribution_agentname sysname NULL , mergeagentname sysname NULL , mergesubscriptionfriendlyname sysname NULL , mergeagentlocation sysname NULL , mergeconnectiontype INT NULL , mergePerformance INT NULL , mergerunspeed FLOAT NULL , mergerunduration INT NULL , monitorranking INT NULL , distributionagentjobid BINARY(16) NULL , mergeagentjobid BINARY(16) NULL , distributionagentid INT NULL , distributionagentprofileid INT NULL , mergeagentid INT NULL , mergeagentprofileid INT NULL , logreaderagentname sysname NULL , publisher sysname NULL ); INSERT INTO #tmp_rep_monitordata EXEC sp_replmonitorhelpsubscription @publication_type = 0; INSERT INTO #tmp_rep_monitordata EXEC sp_replmonitorhelpsubscription @publication_type = 1; SELECT (CASE WHEN status = '1' THEN 'Start - ' + CAST(status AS VARCHAR) WHEN status = '2' THEN 'Succeed - ' + CAST(status AS VARCHAR) WHEN status = '3' THEN 'InProgress - ' + CAST(status AS VARCHAR) WHEN status = '4' THEN 'Idle - ' + CAST(status AS VARCHAR) WHEN status = '5' THEN 'Retry - ' + CAST(status AS VARCHAR) WHEN status = '6' THEN 'Fail - ' + CAST(status AS VARCHAR)ELSE CAST(status AS VARCHAR)END) [Run Status] , publisher_db , publication , (CASE WHEN warning = '1' THEN 'Expiration' + CAST(warning AS VARCHAR) WHEN warning = '2' THEN 'Latency' + CAST(warning AS VARCHAR) WHEN warning = '4' THEN 'Mergeexpiration' + CAST(warning AS VARCHAR) WHEN warning = '16' THEN 'Mergeslowrunduration' + CAST(warning AS VARCHAR) WHEN warning = '32' THEN 'Mergefastrunspeed' + CAST(warning AS VARCHAR) WHEN warning = '64' THEN 'Mergeslowrunspeed' + CAST(warning AS VARCHAR)END) warning , subscriber , subscriber_db , (CASE WHEN publication_type = '0' THEN 'Transactional - ' + CAST(publication_type AS VARCHAR) WHEN publication_type = '1' THEN 'Snapshot - ' + CAST(publication_type AS VARCHAR) WHEN publication_type = '2' THEN 'Merge - ' + CAST(publication_type AS VARCHAR)ELSE '' END) AS [Publication Type] , (CASE WHEN subtype = '0' THEN 'Push - ' + CAST(subtype AS VARCHAR) WHEN subtype = '1' THEN 'Pull - ' + CAST(subtype AS VARCHAR) WHEN subtype = '2' THEN 'Anonymous - ' + CAST(subtype AS VARCHAR)ELSE '' END) AS SubscriptionType , latency , latencythreshold , agentnotrunning , agentnotrunningthreshold , last_distsync , timetoexpiration , expirationthreshold , distribution_agentname , monitorranking , distributionagentjobid , mergeagentjobid , distributionagentid , distributionagentprofileid , mergeagentid , mergeagentprofileid , logreaderagentname , publisher FROM #tmp_rep_monitordata ORDER BY publication ASC; </code></pre>
27,130
<p>In the case of languages that support single decision and action without brackets, such as the following example:</p> <pre><code>if (var == true) doSomething(); </code></pre> <p>What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:</p> <pre><code>if (var == 1) doSomething(1); else if (var &gt; 1 &amp;&amp; var &lt; 10) doSomething(2); else { validate(var); doSomething(var); } </code></pre>
<p>There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like</p> <pre><code>if ( a == b) { doSomething(); } else { doSomething(); } </code></pre> <p>but this is a holy war. </p>
<p>Our boss makes us put { } after a decision statement no matter what, even if it's a single statement. It's really annoying to add two extra lines. The only exception is ternary operators.</p> <p>I guess it's a good thing I have my code monitor in portrait orientation at 1200x1600.</p>
3,228
<p>Are there any techniques for getting a smooth finish for parts printed with co-polyester (PET) filaments? More specifically, I am looking for an alternative that does not roughen the look of the part - such as using sandpaper - but rather works like acetone baths for ABS.</p> <p>In particular, I want to treat ColorFabb's XT filament made from the <a href="http://www.eastman.com/Markets/3D_Printing/Pages/Products.aspx" rel="nofollow">Eastman Amphora™ 3D polymer</a> (<a href="http://ws.eastman.com/ProductCatalogApps/PageControllers/ProdDatasheet_PC.aspx?Product=71100831&amp;sCategoryName=Generic" rel="nofollow">datasheet</a>). This is also the polymer is also used in:</p> <ul> <li>ColorFabb <a href="http://colorfabb.com/co-polyesters" rel="nofollow">nGen and XT</a></li> <li>Taulman3D n-vent</li> <li>TripTech Athiri 1800</li> <li>3DXTech 3DXNano</li> </ul>
<p>Ethyl acetate (sold as a MEK substitute) is supposed to work for vapor smoothing PET. It doesn't seem very toxic (it's used to decaffinate cofee and tea, and as a nail polish remover), but you might want to look more into it. There's a post on Printed Solid's blog where he vapor smoothed colorFabb XT and MadeSolid PET+ along with a few other filaments and got some good results.</p> <p><a href="http://printedsolid.com/blogs/news/37035395-vapor-smoothing-3d-printed-parts-pla-colorfabb-xt-t-glase-pet" rel="nofollow">http://printedsolid.com/blogs/news/37035395-vapor-smoothing-3d-printed-parts-pla-colorfabb-xt-t-glase-pet</a></p> <p>The links in the blog don't work for me, but google was able to find slightly larger versions:</p> <p><a href="https://cdn.shopify.com/s/files/1/0887/0138/files/blog_2014-03-20-18.38.04-1024x613.jpg?16147388421280943481" rel="nofollow">https://cdn.shopify.com/s/files/1/0887/0138/files/blog_2014-03-20-18.38.04-1024x613.jpg?16147388421280943481</a></p> <p><a href="https://cdn.shopify.com/s/files/1/0887/0138/files/blog_2014-03-21-18.16.28-1024x612.jpg?9543779874607042697" rel="nofollow">https://cdn.shopify.com/s/files/1/0887/0138/files/blog_2014-03-21-18.16.28-1024x612.jpg?9543779874607042697</a></p>
<p>I've found a <a href="http://www.plasticsintl.com/plastics_chemical_resistence_chart.html" rel="nofollow">chart</a> which covers several plastics and solvents and only two of them (<a href="https://en.wikipedia.org/wiki/Chloromethane" rel="nofollow">Chloromethane</a> and <a href="https://en.wikipedia.org/wiki/Chloroform" rel="nofollow">Chloroform</a>) are rated "D" which includes dissolving the material and both seem to be quite nasty and I doubt you will be able to purchase them without being placed on several lists.</p> <p>Is it possible that something like <a href="http://www.smooth-on.com/Epoxy-Coatings-XTC/c1397_1429/index.html" rel="nofollow">XTC-3D</a> from Smooth-On would work for you?</p> <p>Also some more information on dissolving PET <a href="https://www.researchgate.net/post/How_do_you_dissolve_polyethyelene_terephthalate_PET" rel="nofollow">here</a>, several sources also mention PET is affected by Hydrogen Peroxide but they do not mention to what degree the plastic is affected.</p>
152
<p>I'm working on a large legacy java application for which an important feature was automatic scaling of GUI Components based on monitor resolution. We are upgrading the JVM on which it runs from 1.4.2 to 1.6 and now the scaling is broken due to a change in the implementation of java.awt.Container.getPreferredSize().</p> <p>getPrefferedSize used to return the same object that you gave with setPreferredSize() (everything also goes for min/max size), so what we would do is call setPRefferedSize on every scaling component with a particular subclass of java.awt.Dimension, then we would walk the component hierarchy and update each scaling component whenever the resolution changed.</p> <p>However in Java 1.6 getPreferredSize returns a copy of the Dimension object you passed it, so it is no longer the right type and nothing gets scaled.</p> <p>I hacked together a solution pretty quick by overriding the Component class with my own implementation (thank you open source JRE) by placing it in front of the JRE on the class path. However this solution is clearly not maintainable.</p> <p>Does anyone else know any other solution to this problem, how would you implement GUI scaling in java 1.5/1.6?</p>
<p>It sounds like they are protecting the internal state of the component better in 1.6 than before. Maybe they ran <a href="http://findbugs.sourceforge.net/" rel="nofollow noreferrer">FindBugs</a> on it and fix the <a href="http://findbugs.sourceforge.net/bugDescriptions.html#EI_EXPOSE_REP" rel="nofollow noreferrer">bug</a>. </p> <p>When I first read this question, I thought of Java 1.6u10. It includes a new look and feel called <a href="http://java.sun.com/javase/downloads/ea/6u10/nimbus.jsp" rel="nofollow noreferrer">Nimbus</a> which supports High DPI displays by way of using vector graphics to draw all of the interface components. </p> <p>However, after reading the question a little slower and trying to comprehend what you are saying, I'd suggest that you rewrite the user interface using a layout manager that will manage the sizes of the internal components for you. My feeling is that hand managing the component sizes as you suggest is really not a good idea. As <a href="https://stackoverflow.com/questions/188046/java-gui-resolution-independant-scaling#188261">jjnguy</a> suggests, you could use GridBagLayout. There are a number of other choices for Layout Managers. There was a <a href="https://stackoverflow.com/questions/116957/which-layout-manager-do-you-use">question posted</a> that provides a survey of everyone's favorite Layout Managers, if you are looking for something different than GridBagLayout.</p>
<p>Changing layout managers seems like good solutions, but would, in this case, necessitate a complete redesign of the UI (which includes thousands of components) so this isn't really a practical solution for this application. </p>
22,790
<p>Does anyone know of a good way to compress or decompress files and folders in C# quickly? Handling large files might be necessary.</p>
<p>I've always used the SharpZip Library.</p> <p><a href="http://sharpdevelop.net/OpenSource/SharpZipLib/Download.aspx" rel="noreferrer">Here's a link</a></p>
<p>You can create zip file with this method:</p> <pre class="lang-cs prettyprint-override"><code>public async Task&lt;string&gt; CreateZipFile(string sourceDirectoryPath, string name) { var path = HostingEnvironment.MapPath(TempPath) + name; await Task.Run(() =&gt; { if (File.Exists(path)) File.Delete(path); ZipFile.CreateFromDirectory(sourceDirectoryPath, path); }); return path; } </code></pre> <p>and then you can unzip zip file with this methods:</p> <p>1- This method work with zip file path</p> <pre class="lang-cs prettyprint-override"><code>public async Task ExtractZipFile(string filePath, string destinationDirectoryName) { await Task.Run(() =&gt; { var archive = ZipFile.Open(filePath, ZipArchiveMode.Read); foreach (var entry in archive.Entries) { entry.ExtractToFile(Path.Combine(destinationDirectoryName, entry.FullName), true); } archive.Dispose(); }); } </code></pre> <p>2- This method work with zip file stream</p> <pre class="lang-cs prettyprint-override"><code>public async Task ExtractZipFile(Stream zipFile, string destinationDirectoryName) { string filePath = HostingEnvironment.MapPath(TempPath) + Utility.GetRandomNumber(1, int.MaxValue); using (FileStream output = new FileStream(filePath, FileMode.Create)) { await zipFile.CopyToAsync(output); } await Task.Run(() =&gt; ZipFile.ExtractToDirectory(filePath, destinationDirectoryName)); await Task.Run(() =&gt; File.Delete(filePath)); } </code></pre>
2,260
<p>I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?</p> <p>Is there one elegant solution that works for the majority of the cases? </p>
<p>You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a <code>media="print"</code> so that it only applies to print media (when it is printed)</p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="print" href="print.css" /&gt; </code></pre>
<p>I am a php user, but the point must be that the result no matter what is HTML and HTML is styled with CSS and there is an option for your style sheets for just using the style for printing. This should be the way to do it, imho. About big tables, there isnt really a magic "fix" for that. Page will break where it breaks, dont really understand the problem here either. </p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="print" href="print.css" /&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="screen.css" /&gt; </code></pre>
6,891
<p>I have been using git for several months in a project developed only by myself. I have a local repository and push it regularly to github for backup purposes.</p> <p>I want to add another developer to this project, however I will have the responsibility of integrating the whole project.</p> <p>What is the recommended workflow? </p> <p>Do we need a private and a public repository for each developer?</p> <p>If the github repository is the main one, does the other developer have to clone this repository or the repository in my computer?</p> <p>Should he have the right to push in my repository or should I pull from his repository?</p>
<p>Git is geared towards <em>pulling</em>, rather than pushing. Ideally, the other developer would clone from your <em>public</em> repo on Github; then, when he was done with his changes, you'd either pull from a repo that he makes available to you, or you'd integrate his changes with patches that he emails to you. Either way, you'd pull the changes into the <em>private</em> repo <em>on your computer</em>, fix any mistakes that result from the merge, and then push his changes to your public repo (the one on Github).</p> <p>Of course, there's nothing wrong with giving him commit access to your Github repo, either.</p>
<p>A word of advice... make sure you're both clear on which git operations will rewrite history. Resetting branch pointers, rebasing, appending commits, etc. will rewrite the history which is okay but only for private branches. For branches that you are sharing (pushing to or pulling from) you should avoid rewriting history.</p> <p>Here's an article on <a href="http://www.golden-gryphon.com/software/misc/packaging.html" rel="nofollow noreferrer">Packaging software using Git</a> that's a nice read. It's aimed at people doing large scale integration (like building linux distributions) but the principals are generally applicable.</p>
36,300
<p>I'm experiencing a strange behavior of SVN. I've got SVN repository running on Apache 2.2.9 with mod_dav, mod_dav_svn and SVN 1.5.2. When I try to check out (from remote 1.5.4 client or server-local 1.5.2 client - both "default" svn binaries), I'm getting something like:</p> <p>mx-mac:Test mx$ svn ci -m "" Adding test.txt svn: Commit failed (details follow): svn: XML data was not well-formed</p> <p>What I've found out by sniffing the HTTP connection is, that one request to remote SVN repository (Apache) ends by "Reset by peer" and not returning the response (used HTTP Scoop to sniff).</p> <p>As for the configuration of Apache, all modules are loaded. Proper permissions are set for repo and repo was created by svnadmin create and then chowned to apache user (anyway, it did not worked even if I've chmod -R 777 repo directory).</p> <p>Apache configuration contains DAV and SVNPath directives along with authentication.</p> <p>I'm pretty desperate after few long hours of trying, so if someone ever encountered such issue, please let me know. Thanks a lot!</p>
<p>Finally, I figured out that redefined ErrorDocument in .htaccess file for the same VirtualHost as the SVN's caused invalid data to be sent to SVN client on some occasions and for some reason intercepting with commit process.</p>
<p>Daren, you are not exactly correct right now. I've tried all the possible combinations of working copies, new repositories and so on. I've tried mostly everything. At last, I've found one strange message in NEON debug messages, displaying my 404 page on a homepage, which I mostly forgot about. Then, I've realized - as created long time ago - I've sent improper HTTP status code from the 404 page (200 instead of 404), therefore NEON considered it proper output and processed, leaving it in somehow incorrect state.</p> <p>So, right now it was apache issue, caused by stupid web developer - me in 2003... :)</p>
40,038
<p>I am working in Java on a fairly large project. My question is about how to best structure the set of Properties for my application.</p> <p>Approach 1: Have some static Properties object that's accessible by every class. (Disadvantages: then, some classes lose their generality should they be taken out of the context of the application; they also require explicit calls to some static object that is located in a different class and may in the future disappear; it just doesn't <em>feel</em> right, am I wrong?)</p> <p>Approach 2: Have the Properties be instantiated by the main class and handed down to the other application classes. (Disadvantages: you end up passing a pointer to the Properties object to almost every class and it seems to become very redundant and cumbersome; I don't <em>like</em> it.)</p> <p>Any suggestions?</p>
<p>I like using Spring dependency injection for many of the properties. You can treat your application like building blocks and inject the properties directly into the component that needs them. This preserves (encourages) encapsulation. Then, you assemble your components together and create the "main class". </p> <p>A nice side effect of the dependency injection is that your code should be more easily testable.</p>
<p>I usually go for a singleton object that resides in a common project and contains a hashtable of itself keyed on namespace, resulting in a properties class for each. </p> <p>Dependency injection is also a nice way of doing it.</p>
31,179
<p>I'm looking for a component for C#.NET 2008 Professional that is capable of doing the majority of the network communications work that is required of our application so our programmers don't have to.</p> <p>This component should function similarly to the way <a href="http://www.realthinclient.org/" rel="nofollow noreferrer">RealThinClient</a> (RTC) does. The component must be able to gracefully lose and regain connections. It must have encryption built-in. It must have compression built in. RTC is capable of doing connection pooling as well and this is something that we would also like to have.</p> <p>A little background about us: we were previously a Delphi 7 shop and are moving to using Visual Studio .NET 2008. We just located RTC before we made the decision to move to .NET and are wishing that there was something that duplicated the functionality available. :-)</p> <p>Thanks for your help and links are much appreciated.</p> <p>Michael Beck</p>
<p>You should look at IPWorks from www.NSoftware.com Not only do they have a Dot Net library, they have a Delphi component as well. This might help you convert. If you buy their Red Carpet Subscription you'd get all libraries.</p>
<p>You should look at IPWorks from www.NSoftware.com Not only do they have a Dot Net library, they have a Delphi component as well. This might help you convert. If you buy their Red Carpet Subscription you'd get all libraries.</p>
36,745
<p>Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:</p> <pre><code>response.should use_layout('my_layout_name') </code></pre> <p>I found a use_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.</p>
<p>David Chelimsky posted a good answer over on the <a href="http://www.ruby-forum.com/topic/216851" rel="noreferrer">Ruby Forum</a>:</p> <pre><code>response.should render_template("layouts/some_layout") </code></pre>
<p>Here's a version of dmcnally's code that allows no arguments to be passed, making "should use_layout" and "should_not use_layout" work (to assert that the controller is using any layout, or no layout, respectively - of which I would expect only the second to be useful as you should be more specific if it is using a layout):</p> <pre><code>class UseLayout def initialize(expected = nil) if expected.nil? @expected = nil else @expected = 'layouts/' + expected end end def matches?(controller) @actual = controller.layout #@actual.equal?(@expected) if @expected.nil? @actual else @actual == @expected end end def failure_message if @expected.nil? return 'use_layout expected a layout to be used, but none was', 'any', @actual else return "use_layout expected #{@expected.inspect}, got #{@actual.inspect}", @expected, @actual end end def negative_failure_message if @expected.nil? return "use_layout expected no layout to be used, but #{@actual.inspect} found", 'any', @actual else return "use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}", @expected, @actual end end end def use_layout(expected = nil) UseLayout.new(expected) end </code></pre>
13,457
<p>Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider.</p> <p>I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.).</p> <p>What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)?</p> <p><strong>Update:</strong> There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.</p>
<p>I think, it will take time, till the tools get more refined, more people gain experience with MDD. At the moment if you want to get something out of MDD you have to invest quite a lot, so its use remains limited.</p> <p>Looking at openArchitectureWare for example: While it is quite robust and basic documentation exists, documentation on the inner workings are missing and there are still problems with scalability, that are undocumented - maybe that will get better when Xtext and Xpand get rewritten. </p> <p>But despise those limitations the generation itself is quite easy with oAW, you can navigate your models like a charm in Xtend and Xpand and by combining several workflows into bigger workflows, you can also do very complex things. If needed you can resort to Java, so you have a very big flexibility in what you can do with your models. Writing your own DSL with Xtext in oAW, too, is quickly done, yet you get your meta-model, a parser and a very nice editor basically for free. Also you can get your models basically from everywhere, e.g. a component that can convert a database into a meta-model and corresponding models can be written without big effort.</p> <p>So I would say, MDD is still building up, as tools and experience with it increases. It can already used successfully, if you have the necessary expertise and are ready to push it within your company. In the end, I think, it is a very good thing, because a lot of glue code (aka copy paste) can and should be generated. Doing that with MDD is a very nice and structured way of doing this, that facilitates reusability, in my opinion.</p>
<p>This is a very late reply, but I am currently searching for MDD tools to replace Rose RT, which is unfortunately being supplanted by Rhapsody. We are in the real-time, embedded and distributed C++ space and we get a LOT out of MDD. We are trying to move on to a better tool and get more widespread use of the tool in our very large company. It is an uphill battle because of some of the fine reasons mentioned here.</p> <p>I think of MDD as just one level above the compiler, just as the compiler is above assembly. I want a tool that lets me, as the architect, develop the application framework, and extensively edit the code generation (scripts) to use that framework and whatever middleware we are using for message passing. I want the developers making complete UML classes and state diagrams that include all the code needed to generate the application and/or library.</p> <p>It is true that you can do anything with code, but I would roughly summarize the benefits of MDD as this:</p> <ol> <li>A few people make the application framework, middleware adapters and glue that to the MDD tool. They build the "house".</li> <li>Other people create complete classes, diagrams, and state machine transition code. This lets them focus on the application in stead fo the "house".</li> <li>Its easy to see when peopel have wierd design since the diagram is the code. We don't have all expert developers and its nice to bring junior people up this way.</li> <li>Mostly its the nasty state machine code that can happen in something like a mobile robotics project. I want people making state diagrams that I can understand, criticize and work on them with.</li> <li>You can also have nice refactoring like dragging operation and attributes up inheritence chains or to other classes, etc. I like that better than digging in files.</li> </ol> <p>Even as I type this I realize that you can do everything in code. I like a thin tool jsut on top of the code to enforce uniformity, document the design, and allow a bit easier refactoring.</p> <p>The main problem I encounter that I don't have a good answer for is that there is no standard set of functionality and file format for such models. People worry about the vendor going away and then being stuck. (We bascially had that happen with Rose RT.) You don't have that with source code. However, you would have the latest version of the tool and the course code that you generated last :). I'm willing to bet that the benefit outweighs the risk.</p> <p>I have yet to find the tool like this, but I am trying to get a few vendors to listen to me and maybe accept money to make this happen.</p>
4,141
<p>I'm trying to port an old library (that doesn't use namespaces as far as I can tell) to modern compilers. One of my targets can't tell the difference between System::TObject and ::TObject (without a namespace). System::TObject is native to the compiler.</p> <p>I've tried a using directive, i.e. using ::TObject;</p> <p>But that doesn't do it.</p> <p>The obvious solution is to wrap all the original library in a namespace and then calling it by name- that should avoid the ambiguity. But is that the wisest solution? Is there any other solution? Adding a namespace would require changing a bunch of files and I don't know if it would have unwanted repercussions later.</p>
<p>You can do as Dib suggested, with a slight modification:</p> <pre><code>// In a wrapper header, eg: include_oldlib.h... namespace oldlib { #include "oldlib.h" }; #ifndef DONT_AUTO_INCLUDE_OLD_NAMESPACE using namespace oldlib; #endif </code></pre> <p>This allows you to #define the exclusion in only the files where you're getting conflicts, and use all the symbols as global symbols otherwise.</p>
<p>If you have the source to the library, maybe include a header file at the top of each source where that header file has only:</p> <pre><code>#define TObject TMadeUpNameObject </code></pre>
23,044
<p>Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object. </p> <p>Here is the scenario with simplified code:</p> <ol> <li><p><code>Default.aspx</code></p></li> <li><p><code>MainScript.js</code></p> <pre><code>function getObject(){ return new Array(); } function function1(obj){ var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } function function2(){ var obj=getObject(); var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } </code></pre></li> <li><p><code>Content.aspx</code></p></li> <li><p><code>ContentScript.js</code></p> <pre><code>function serializeObject(){ var obj=window.top.getObject(); window.top.function1(obj); // &lt;– This works fine obj=new Array(); window.top.function1(obj); // &lt;– this causes an Out of Stack Space error } </code></pre></li> </ol> <p>The code for the sample pages and JavaScript is <a href="http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/" rel="nofollow noreferrer">here</a>.</p> <p>Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.</p> <p>A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx). </p> <p>Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.</p> <p>Any ideas?</p>
<p>This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method.</p> <p>Example of the clone() methode you can find here (comments in Russian): <a href="http://snowcore.net/clone-javascript-object" rel="nofollow noreferrer">link text</a></p>
<p>I have no way of testing your code right now, but it looks like a bug in JavaScriptSerializer.serialize to me. My guess is that it tries to do some kind of type checking on the array via the CLR and that it doesn't handle an empty array properly. </p> <p>Have you tried to add an item of a serializable type to the array in your code? If so, what happens?</p>
8,102
<p>I am not too familiar with .NET desktop applications (using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="noreferrer">Visual&nbsp;Studio&nbsp;2005</a>). Is it possible to have the entire application run from a single .exe file?</p>
<p>Yes, you can use the <a href="https://github.com/dotnet/ILMerge" rel="nofollow noreferrer">ILMerge</a> tool. It is also available <a href="https://www.nuget.org/packages/ilmerge" rel="nofollow noreferrer">as a NuGet package</a>.</p>
<p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=17630" rel="nofollow noreferrer">ILMerge</a> can combine assemblies to one single assembly provided the assembly has only managed code. You can use the commandline application, or add reference to the EXE file and programmatically merge. For a GUI version, there is <a href="http://www.foss.kharkov.ua/g1/projects/eazfuscator/dotnet/Default.aspx#downloads" rel="nofollow noreferrer">Eazfuscator</a>, and also <a href="http://madebits.com/netz/" rel="nofollow noreferrer">.Netz</a>, both of which are free. Paid applications include <a href="http://boxedapp.com/" rel="nofollow noreferrer">BoxedApp</a> and <a href="http://www.red-gate.com/products/dotnet-development/smartassembly/" rel="nofollow noreferrer">SmartAssembly</a>.</p> <p>If you have to merge assemblies with unmanaged code, I would suggest <a href="http://www.red-gate.com/products/dotnet-development/smartassembly/" rel="nofollow noreferrer">SmartAssembly</a>. I never had hiccups with <a href="http://www.red-gate.com/products/dotnet-development/smartassembly/" rel="nofollow noreferrer">SmartAssembly</a>, but with all others. Here, it can embed the required dependencies as resources to your main EXE file.</p> <p>You can do all this manually, not needing to worry if an assembly is managed or in mixed mode by embedding the DLL file in your resources and then relying on AppDomain's Assembly <code>ResolveHandler</code>. This is a one-stop solution by adopting the worst case, that is, assemblies with unmanaged code.</p> <pre><code>class Program { [STAThread] static void Main() { AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =&gt; { string assemblyName = new AssemblyName(args.Name).Name; if (assemblyName.EndsWith(".resources")) return null; string dllName = assemblyName + ".dll"; string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName); using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + ".Resources." + dllName)) { byte[] data = new byte[stream.Length]; s.Read(data, 0, data.Length); // Or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length); File.WriteAllBytes(dllFullPath, data); } return Assembly.LoadFrom(dllFullPath); }; } } </code></pre> <p>Where <code>Program</code> is the class name. The key here is to write the bytes to a file and load from its location. To avoid a chicken-and-egg problem, you have to ensure you declare the handler before accessing the assembly and that you do not access the assembly members (or instantiate anything that has to deal with the assembly) inside the loading (assembly resolving) part. Also take care to ensure <code>GetMyApplicationSpecificPath()</code> is not any temporary directory since temporary files could be attempted to get erased by other programs or by yourself (not that it will get deleted while your program is accessing the DLL file, but at least it's a nuisance. AppData is a good location). Also note that you have to write the bytes each time; you can't load from location just because the DLL file already resides there.</p> <p>For managed DLL files, you need not write bytes, but directly load from the location of the DLL file, or just read the bytes and load the assembly from memory. Like this or so:</p> <pre><code>using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + ".Resources." + dllName)) { byte[] data = new byte[stream.Length]; s.Read(data, 0, data.Length); return Assembly.Load(data); } // Or just return Assembly.LoadFrom(dllFullPath); // If location is known. </code></pre> <p>If the assembly is fully unmanaged, you can see <a href="https://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-sharp-dll">this link</a> or <a href="http://bsmadhu.wordpress.com/2012/03/19/embedding-c-libraryexe-inside-net-assembly/" rel="nofollow noreferrer">this</a> as to how to load such DLL files.</p>
15,401
<p>I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.</p> <pre><code>XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement("url", new XElement("loc", "http://www.example.com/page"), new XElement("lastmod", "2008-09-14")))); </code></pre> <p>The result is ...</p> <pre><code>&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt; &lt;url xmlns=""&gt; &lt;loc&gt;http://www.example.com/page&lt;/loc&gt; &lt;lastmod&gt;2008-09-14&lt;/lastmod&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre> <p>I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?</p>
<p>The "more correct way" would be:</p> <pre><code>XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement(ns + "url", new XElement(ns + "loc", "http://www.example.com/page"), new XElement(ns + "lastmod", "2008-09-14")))); </code></pre> <p>Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is:</p> <pre><code>&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt; &lt;url&gt; &lt;loc&gt;http://www.example.com/page&lt;/loc&gt; &lt;lastmod&gt;2008-09-14&lt;/lastmod&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre> <p>which is, if I'm not mistaken, what you want.</p>
<p>If one element uses a namespace, they all must use one. In case you don't define one on your own the framework will add a empty namespace as you have noticed. And, sadly, there is no switch or something similiar to suppress this "feature".</p> <p>So, there seems to be no better method as to strip it out. Using <em>Replace(" xmlns=\"\"", "")</em> could be a little bit faster than executing a RegEx.</p>
8,619
<p>I recently read this Phil Haack post (<a href="http://haacked.com/archive/2007/06/13/the-most-useful-.net-utility-classes-developers-tend-to-reinvent.aspx" rel="nofollow noreferrer">The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse</a>) from last year, and thought I'd see if anyone has any additions to the list.</p>
<p>People tend to use the following which is ugly and bound to fail:</p> <pre><code>string path = basePath + "\\" + fileName; </code></pre> <p>Better and safer way:</p> <pre><code>string path = Path.Combine(basePath, fileName); </code></pre> <p>Also I've seen people writing custom method to read all bytes from file. This one comes quite handy:</p> <pre><code>byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine </code></pre> <p>As <a href="https://stackoverflow.com/users/8543/thexenocide">TheXenocide</a> pointed out, same applies for <code>File.ReadAllText()</code> and <code>File.ReadAllLines()</code></p>
<p>Path.Append is always forgotten in stuff I have seen.</p>
21,515
<p>I have this in a page :</p> <pre><code>&lt;textarea id="taEditableContent" runat="server" rows="5"&gt;&lt;/textarea&gt; &lt;ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent" ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx" ServiceMethod="EditContent" ContextKey='&lt;%=ContextKey %&gt;' /&gt; </code></pre> <p>Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.</p> <p>If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;string xmlns="http://rprealm.com/"&gt;First line Third line Fourth line&lt;/string&gt; </code></pre> <p>But what I get in the text area is :</p> <pre><code>First line Third line Fourth line </code></pre>
<p>The problem is that the white space is ignored by default when the XML is processed. Try to add the <code>xml:space="preserve"</code> attribute to the string element. You'll also need to define the xml prefix as <code>xmlns:xml="http://www.w3.org/XML/1998/namespace"</code>.</p>
<p>Try to add the following style on textarea: <strong>style="white-space: pre"</strong></p>
8,533
<p>I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.</p> <p>I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in</p> <pre><code>MessageBox("Hello, World!"); </code></pre> <p>I received the following error:</p> <p>MessageBox is a 'type' but used as a 'variable'</p> <p>Fair enough, it seems in C# MessageBox is an Object. I tried the following</p> <pre><code>MessageBox a = new MessageBox("Hello, World!"); </code></pre> <p>I received the following error: MessageBox does not contain a constructor that takes '1' arguments</p> <p>Now I am stumped. Please help.</p>
<p>MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like</p> <pre><code>if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) { //some interesting behaviour here } </code></pre> <p>which I guess is a bit unwieldy but it gets the job done.</p> <p>See <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult</a> for additional enum options you can use here.</p>
<p>In the <code>System.Windows.Forms</code> class, you can find more on the <a href="http://www.msdn.com/" rel="nofollow">MSDN</a> page for this here. Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript <code>alert("my message");</code> or <code>confirm("my question");</code> functions.</p>
7,158
<p>How do i measure how long a client has to wait for a request. </p> <p>On the server side it is easy, through a filter for example. But if we want to take into accout the total time including latency and data transfer, it gets diffcult.</p> <p>is it possible to access the underlying socket to see when the request is finished? or is it neccessary to do some javascript tricks? maybe through clock synchronisation between browser and server? are there any premade javascripts for this task?</p>
<p>There's no way you can know how long the client had to wait purely from the server side. You'll need some JavaScript.</p> <p>You don't want to synchronize the client and server clocks, that's overkill. Just measure the time between when the client makes the request, and when it finishes displaying its response.</p> <p>If the client is AJAX, this can be pretty easy: call new Date().getTime() to get the time in milliseconds when the request is made, and compare it to the time after the result is parsed. Then send this timing info to the server in the background.</p> <p>For a non-AJAX application, when the user clicks on a request, use JavaScript to send the current timestamp (from the client's point of view) to the server along with the query, and pass that same timestamp back through to the client when the resulting page is reloaded. In that page's onLoad handler, measure the total elapsed time, and then send it back to the server - either using an XmlHttpRequest or tacking on an extra argument to the next request made to the server.</p>
<p>You could set a 0 byte socket send buffer (and I don't exactly recommend this) so that when your blocking call to HttpResponse.send() you have a closer idea as to when the last byte left, but travel time is not included. <strong><em>Ekk</em></strong>--I feel queasy for even mentioning it. You can do this in Tomcat with connector specific settings. (<a href="http://tomcat.apache.org/tomcat-6.0-doc/config/http.html" rel="nofollow noreferrer">Tomcat 6 Connector documentation</a>) </p> <p>Or you could come up with some sort of javascript time stamp approach, but I would not expect to set the client clock. Multiple calls to the web server would have to be made. </p> <ul> <li>timestamp query</li> <li>the real request</li> <li>reporting the data</li> </ul> <p>And this approach would cover latency, although you still have have some jitter variance. </p> <p>Hmmm...interesting problem you have there. :)</p>
11,150
<p>I want to achieve going to the parent element then to the prev element get the atrribute id of the element which has class: classname.</p> <pre><code>&lt;div&gt; &lt;span&gt;&lt;span id="190" class="classname"&gt;blabla&lt;/span&gt;&lt;/span&gt; &lt;span&gt;&lt;a href="#" class="button"&gt;blabla&lt;/a&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>Pseudo code:</p> <pre><code>$('.button').click(function(){ console.log($(this).parent().prev().$(".classname").attr("id")); }); </code></pre> <p>Do I have to use a find here or is there another way?</p>
<p>For your example:</p> <pre><code>$(this).parent().prev().children( '.classname' ).attr( 'id' ); </code></pre>
<p>I would use <code>find</code> as you have suggested.</p>
44,680
<p>Has anyone figured out how to use Crystal Reports with Linq to SQL?</p>
<p>You can convert your LINQ result set to a <code>List</code>, you need not strictly use a <code>DataSet</code> as the reports <code>SetDataSource</code>, you can supply a Crystal Reports data with an <code>IEnumerable</code>. Since <code>List</code> inherits from <code>IEnumerable</code> you can set your reports' Data Source to a List, you just have to call the <code>.ToList()</code> method on your LINQ result set. Basically:</p> <pre><code> CrystalReport1 cr1 = new CrystalReport1(); var results = (from obj in context.tSamples where obj.ID == 112 select new { obj.Name, obj.Model, obj.Producer }).ToList(); cr1.SetDataSource(results); crystalReportsViewer1.ReportSource = cr1; </code></pre>
<p>The above code wont work in web application if you have dbnull values. You have to convert the results list object to dataset or datatable. There is no built in method for it. I have gone through the same issue and after hours of exploring on the internet, I found the solution and wanna share here to help anyone stuck up with it. You have to make a class in your project:-</p> <pre><code> public class CollectionHelper { public CollectionHelper() { } // this is the method I have been using public DataTable ConvertTo&lt;T&gt;(IList&lt;T&gt; list) { DataTable table = CreateTable&lt;T&gt;(); Type entityType = typeof(T); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (T item in list) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } table.Rows.Add(row); } return table; } public static DataTable CreateTable&lt;T&gt;() { Type entityType = typeof(T); DataTable table = new DataTable(entityType.Name); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (PropertyDescriptor prop in properties) { // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES table.Columns.Add(prop.Name, Nullable.GetUnderlyingType( prop.PropertyType) ?? prop.PropertyType); } return table; } } </code></pre> <p>and here setting up your crystal report </p> <pre><code>CrystalReport1 cr1 = new CrystalReport1(); var results = (from obj in context.tSamples where obj.ID == 112 select new { obj.Name, obj.Model, obj.Producer }).ToList(); CollectionHelper ch = new CollectionHelper(); DataTable dt = ch.ConvertTo(results); cr1.SetDataSource(dt); crystalReportsViewer1.ReportSource = cr1; </code></pre>
12,295
<p>Imagine you had a group of product categories organized in a nice tree hierarchy and you wanted to provide hackable urls to browse these. You could do something like this</p> <pre><code>/catalog/categorya/categoryb/categoryc </code></pre> <p>You could then quite easily figure out which category you should list the products for (note that the full URL is needed since you could have categories with the same name but at different locations in the hierarchy)</p> <p>Now what would be a good approach to add product information in that as well? To give you an example, you wanted to display the product Oblivion for this category </p> <pre><code>/catalog/games/consoles/playstation/adventure </code></pre> <p>It's tempting to just add the product at the end of the url</p> <pre><code>/catalog/games/consoles/playstation/adventure/oblivion </code></pre> <p>but the moment you do so you loose the ability to know if its category or a product which is called oblivion. I personally feel that not being forced to add a suffix such as .html</p> <pre><code>/catalog/games/consoles/playstation/adventure/oblivion.html </code></pre> <p>would be the nicest solution and using some sort of prefix, such as </p> <pre><code>/catalog/games/consoles/playstation/adventure/product:oblivion </code></pre> <p>You could also add some sort of trigger like</p> <pre><code>/catalog/games/consoles/playstation/adventure/PRODUCT/oblivion </code></pre> <p>not as nice either and you would (even though its very unlikely it would be a problem) restrict yourself from having a category called <em>product</em></p> <p>So far a suffix solution looks like the most user-friendly approach that I can think of from the top of my head but I'm not fond of having to use an extension</p> <p>What are your thoughts on this?</p>
<p>Deep paths irk me. They're hideous to share. </p> <pre><sub> /product/1234/oblivion --> direct page /product/oblivion --> /product/1234/oblivion if oblivion is a unique product, --> ~ Diambiguation page if oblivion is not a unqiue product. /product/1234/notoblivion -> /product/1234/oblivion /categories/79/adventure --> playstation adventure games /categories/75/games --> console games page /categories/76/games --> playstation games page /categories/games --> Disambiguation Page. </sub></pre> <p>Otherwise, the long urls, while <em>seeming</em> hackable, require you to get all node elements right to hack it. </p> <p>Take php.net </p> <pre> php.net/str_replace --> goes to http://nz2.php.net/manual/en/function.str-replace.php </pre> <p>And this model is so hackable people use it all the time blindly. </p> <p>Note: The .html suffix is regarded by the W3C as functionally meaningless and redundant, and should be avoided in URLs. </p> <p><a href="http://www.w3.org/Provider/Style/URI" rel="nofollow noreferrer">http://www.w3.org/Provider/Style/URI</a></p>
<p>@Lou Franco yeah either method needs a sturdy fallback mechanism and sending it to some sort of suggestion page or seach engine would be good candidates</p> <p>@Stefan the problem with treating both as targets are how to distinguish them (like I described). At worst case scenario is that you first hit your database to see if there is a category which satisfies the path and if it doesn't then you check if there is a product which does. The problem is that for each product path you will end up making a useless call to the database to make sure its not a category.</p> <p>@some yeah a delimiter could be a possible solution but then a .html suffix is more userfriendly and commonly known of. </p>
36,953
<p>I had filament on my 3D45 coming out of threads on the nozzle.</p> <p>To fix this I removed the nozzle to find the PTFE Liner in really bad shape. It looked crushed and deformed. Now the tough part, how do I replace the PTFE Liner. You can't seem to buy the liner and getting a replacement nozzle assembly from Dremel takes weeks. Can anybody help me figure this out please, I really would like to get back to printing!!</p>
<p>The initial problem you had with filament coming out of the threads at the nozzle is caused by improper seating of the heat break to the nozzle. In a &quot;from the ground up&quot; installation, you'd have an empty heat block, containing your heater core and your thermistor. Threaded into the &quot;bottom&quot; of the block is the nozzle, just a turn shy of being flush with the heat block. The heat break is the thin threaded segment extending from the heavily finned heat sink.</p> <p>The heat sink/heat break combination is threaded into the heat block until it contacts the nozzle, at which time, the nozzle is snugged into place securely. This keeps continuous the filament path from the heat break to the nozzle. Somewhere in time, a gap opened between the two.</p> <p>When you have assembled everything (including the PTFE liner), you'll want to heat the extruder assembly to about 250 °C and re-snug the nozzle to the heat block and heat break. Hold securely the heater block, as you do not want to apply force that will snap or otherwise damage the fragile heat break. Use a wrench that fits the heater block without contacting the wiring. Use a wrench that will keep your fingers safe, as the heat block will be hot.</p> <p>Stepping back in time a bit, when you remove the assembly, you should be able to determine the necessary length for the PTFE tube. I checked the manual for your printer and it is lacking in detail for this information. The diameters you've specified are standard and you should be able to locate a suitable substitute from many online sources. Amazon, Matterhackers, eBay, etc.</p> <p>Examine the heat break tubing. The diameter should not be so small as to allow you to push the PTFE tubing in from the heater block side, unless you have an unusually manufactured product. Dremel may have decided to create a new bit of engineering, but I'd expect not.</p> <p>You'll purchase more PTFE than required and examination of the upper portion of the heat sink should give you a clue how much to use. When the cover of the extruder assembly is removed, is there a guide for the filament to make it easier to push through the PTFE tubing? If so, the length of the PTFE is from the bottom of the guide to the bottom of the bore of the heat sink/heat break assembly.</p> <p>Photos of the upper entry to the heat sink/heat break, with the cover removed, would be useful, but you may have sufficient resources in hand to resolve your problem, once you replace the nozzle and purchase PTFE tubing of the correct size.</p>
<p>Capricorn sells 3x2mm ptfe heat break tube. Havnt used it long enough to know if it will hold up to its claims of withstanding temps up to 275c and beyond for any length of time; but I do know the generic ptfe I had in it before lived up to its reputation of going funny at 240c even though they sell it as rated for 250c. But capricorn has a good reputation in general it seems; and I can already testify that the reduction in friction in my bowden tube certainly did live up to the hype, so id recommend giving them a try.</p>
1,707
<p>I have a large collection of static 'Utility' classes that contain very generic static methods. For example, I have a CollectionUtility class that has useful methods like:</p> <p>public static void RemoveDuplicates(ICollection collection)... etc</p> <p>With C# 3.0 I've been converting these to extension methods.</p> <p>Now, I've heard some talk that in an 'enterprise level' application it is often considered best practice to avoid large libraries of these static classes and methods. I imagine that it could get quite hard to maintain.</p> <p>A question for those of you who work on large enterprise projects for large companies - do you maintain libraries of utility classes like these or not? What do you?</p>
<p>You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable</p> <p>I'd follow these guidelines:</p> <ul> <li>These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on parameters). If they aren't naturally stateless, then you should be making a proper class to manage that state.</li> <li>Cover these with Unit Tests. If you don't Unit Test anything else, Unit Test these. This should be very very easy to do. If this isn't easy, this isn't right.</li> </ul> <p>If dependency injection is something you like, you can still have it. Code that relies on a static method could instead be calling a Func(T, U) or an Action that references that static method.</p>
<p>Absolutely not. Utility modules over time turn into large collections of cruddy code.</p>
22,392
<p>Both Session.Clear() and Session.Abandon() get rid of session variables. As I understand it, Abandon() ends the current session, and causes a new session to be created thus causing the End and Start events to fire.</p> <p>It seems preferable to call Abandon() in most cases, such as logging a user out. Are there scenarios where I'd use Clear() instead? Is there much of a performance difference?</p>
<p><code>Session.Abandon()</code> <strong>destroys the session</strong> and the <strong>Session_OnEnd event</strong> is triggered. </p> <p><code>Session.Clear()</code> just <strong>removes all values</strong> (content) from the Object. The session with the same key is still alive.</p> <p>So, if you use <code>Session.Abandon()</code>, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.</p> <p>Use <code>Session.Clear()</code>, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data. </p>
<p>I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.</p> <pre><code>public static void RemoveEverythingButUserInfo() { foreach (String o in HttpContext.Current.Session.Keys) { if (o != "UserInfoIDontWantToAskForAgain") keys.Add(o); } } </code></pre>
45,198
<p>Is it correct to say that typically user_dump_dest is on a local drive?</p> <p>If so, are there issues with mounting a NAS volume to both Unix and Windows and pointing user_dump_dest at that?</p> <p>If so, what are they? </p> <p>Are any issues worth not doing this in prod? </p>
<p>I've run 9.2 instances with user_dump_dest on a NAS and never had a problem with it.</p> <p>If you are concerned though, have oracle write them locally, then sync them across to your NAS and remove them from local, I've never needed to do that though.</p>
<p>Yes, typically (and by default), user_dump_dest is on a local drive. I wouldn't expect there are any specific issues with putting it on NAS; but it would have all the potential issues that any application might: (1) If the NAS could not be reached, Oracle would not be able to write out user dump files, and (2) the write latency would be increased. The latency issue is probably only important if you're doing large-scale tracing to diagnose performance issues, as the write latency would impact the timing measurements. I would expect that if the NAS because unreachable and Oracle tried to write to it, it would silently fail.</p> <p>I don't think I would do it unless space constraints on the local disk forced me to. But generally the contents of this directory should be insignificant relative to your data.</p>
24,756
<p>My function iterates through every node of an instance of an <code>XMLDocument</code>. It checks to see if the current node's name is in a lookup list. If it is, it applies appropriate validation to the value of the current node.</p> <p>When the validation method indicates that the value has been changed, I want to replace the value in the original document with the updated value.</p> <p>I think the easiest way to achieve this might be to write out to an <code>XMLTextWriter</code> as I process each node in the original <code>XMLDocument</code>, either writing out the original or modified node and value as appropriate. This method would rely on determining whether the current node has any children, or is a stand-alone node.</p> <p>Is there a better way I could update the values in the original document? I need to end up with the complete <code>XMLDocument</code>, but with updated node values, where appropriate.</p> <p>Thanks in advance.</p>
<p>Can you not modify the existing nodes (which ate already in the correct structure and in an XMLDocument, then re-serialise the XMLDocument? If the nodes are simple text containters then the </p> <pre><code>.InnerText </code></pre> <p>property is the one you want.</p>
<p>I know I always go back to this but this sounds like an example where clever use of apply-templates and <a href="http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addextensionobject.aspx" rel="nofollow noreferrer">ExtensionObjects</a> in XSLT would be efficient.</p> <p>That said XMLDocument is optimised for modification, so if you were going with a pure programmatic solution I would modify the object directly, not create a new Writer.</p>
43,258
<p>Is there any reason not to use the bitwise operators &amp;, |, and ^ for "bool" values in C++? </p> <p>I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use &amp; and |. I also need to accumulate Boolean values sometimes, and &amp;= and |= can be quite useful.</p> <p>I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?</p>
<p><code>||</code> and <code>&amp;&amp;</code> are boolean operators and the built-in ones are guaranteed to return either <code>true</code> or <code>false</code>. Nothing else.</p> <p><code>|</code>, <code>&amp;</code> and <code>^</code> are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 &ndash; as is the case with the C language &ndash; you may end up with some behavior you didn't want. For instance:</p> <pre><code>BOOL two = 2; BOOL one = 1; BOOL and = two &amp; one; //and = 0 BOOL cand = two &amp;&amp; one; //cand = 1 </code></pre> <p>In C++, however, the <code>bool</code> type is guaranteed to be only either a <code>true</code> or a <code>false</code> (which convert implicitly to respectively <code>1</code> and <code>0</code>), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say <code>b = b &amp;&amp; x</code> and be done with it.</p>
<p>IIRC, many C++ compilers will warn when attempting to cast the result of a bitwise operation as a bool. You would have to use a type cast to make the compiler happy.</p> <p>Using a bitwise operation in an if expression would serve the same criticism, though perhaps not by the compiler. Any non-zero value is considered true, so something like "if (7 &amp; 3)" will be true. This behavior may be acceptable in Perl, but C/C++ are very explicit languages. I think the Spock eyebrow is due diligence. :) I would append "== 0" or "!= 0" to make it perfectly clear what your objective was.</p> <p>But anyway, it sounds like a personal preference. I would run the code through lint or similar tool and see if it also thinks it's an unwise strategy. Personally, it reads like a coding mistake.</p>
4,416
<p>How would one configurably set http-headers to cache files in IIS >= 6?</p> <p>Example:</p> <ul> <li><code>*.cache.*</code> => cache nearly forever</li> <li><code>*.nocache.*</code> => never cache</li> </ul> <p>An example framework using this naming would be the GWT framework.</p>
<p>I think you're referring to setting the cache-control header.</p> <p>See here <a href="http://support.microsoft.com/kb/247404" rel="nofollow noreferrer">http://support.microsoft.com/kb/247404</a></p>
<p><a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/23ea6f24-4b44-4fa0-a275-a1b907e1afb6.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/23ea6f24-4b44-4fa0-a275-a1b907e1afb6.mspx?mfr=true</a></p> <p>Explains the different methods of caching data in IIS.</p>
9,933
<p>What is the best way to determine which ASP.NET button was clicked on a single page using JavaScript?</p>
<p>I just the set the OnClientClick event handler for the button with the JavaScript function I wanted executed when the button was clicked during the Page_Load event.</p> <pre><code>protected void Page_Load(object sender, EventsArgs e) { MyButton.OnClientClick = "MyJavaScriptMethod();"; } </code></pre>
<p>You can easily add a client side Javascript click handler to an ASP button like this.</p> <pre><code>Button1.Attributes.Add("onclick", "alert('You clicked me!');"); </code></pre>
49,738
<p>If someone logs on to my application this user contains a dictionary with certain permissions.</p> <pre><code>ex: module.view.workspace = true module.view.reporting = false ... </code></pre> <p>Then we know to what parts of the application the user has access. What I want to know is how we can apply these permissions on the view. We are working in an AS 3 (FLEX) environment.</p> <p>This is what we came up with so far (but I wanna have an idea of other possibilities). We have a modelLocator storing the loggedOnUser (which contains it's permissions). these permissions are added to a permissionObject in the modellocator. We Create a SecurityManager class that has a function called hasAccess("permission"). This object will check the PermissionObject in the modellocator and return true/false. In the view we just check if the user has access and then show the control.</p> <pre><code>If (SecurityManager.hasAccess("module.view.workspace") { // code that generates the workspace; } </code></pre> <p>I just don't know if this is the best practice. Please help me out here.</p>
<p>There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:</p> <p>This is the shortest statement, and may be quickest if your phone book is very short:</p> <pre><code>SELECT * FROM Call WHERE phone_number NOT IN (SELECT phone_number FROM Phone_book) </code></pre> <p>alternatively (thanks to <a href="https://stackoverflow.com/users/36848/alterlife">Alterlife</a>)</p> <pre><code>SELECT * FROM Call WHERE NOT EXISTS (SELECT * FROM Phone_book WHERE Phone_book.phone_number = Call.phone_number) </code></pre> <p>or (thanks to WOPR)</p> <pre><code>SELECT * FROM Call LEFT OUTER JOIN Phone_Book ON (Call.phone_number = Phone_book.phone_number) WHERE Phone_book.phone_number IS NULL </code></pre> <p>(ignoring that, as others have said, it's normally best to select just the columns you want, not '<code>*</code>')</p>
<pre><code>SELECT name, phone_number FROM Call a WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b) </code></pre>
48,018
<p>Apologies in advance for the long-winded question.</p> <p>I'm really a database programmer, but have inherited support of a classic-ASP intranet application which has recently been migrated from IIS 5 to a new server running IIS 6. The user-base is about a dozen, all using IE 6.</p> <p>The UI displays hierarchies of items returned from a database, using a combination of HTML unordered lists and javascript to hide/expand branches as the user navigates.</p> <p>Images are displayed next to the list members with CSS (using list-style-image), using a different image for each type of item. The number of different item types (and therefore images) in a hierarchy varies between 2 and 10. Hierarchies vary between 20 and 200 items.</p> <p><strong>The problem:</strong></p> <p>Since the migration to IIS 6, several users have experienced a problem which appears to be caused by images failing to be properly applied to one or more items in the hierarchy; the list displays correctly, but one or more images is missing and clicking on any link causes an empty page to load.</p> <p>Analysis of network traffic using Wireshark and the IIS logs show that the problem isn't on the server side - all content has been correctly supplied to the client. </p> <p>The issue appears to be related to content caching at the client: it seems to more often affect users who have not used the application before on their current PC, or have not used it for some time. Also, I can replicate the issue approximately one attempt in three by starting a session, clearing my browser cache and then refreshing the page. However, the same is true of the application when running on IIS 5, so this issue may have existed before the migration to IIS 6 but have happened less frequently. Occasionally, if I leave the session for 20 minutes or so, the browser seems to "find" the missing images, and everything works OK.</p> <p>If the application is accessed through a local proxy (I used Fiddler) the problem never occurs, although the Fiddler connection log shows one or more connections made to the server to retrieve the images has aborted. As before, network traffic shows that the image was returned by the server. However, using the proxy seems to enable IE to find other successfully retrieved copies of the image from the cache.</p> <p>I've reached the point where I'm at the end of my limited knowledge of debugging ASP/IIS issues. Removing the list-style-images from the CSS fixes the problem, but this has to be the option of last resort since it makes the application more difficult to use.</p> <p>Any suggestions on how I can proceed would be gratefully received.</p> <p><strong>Edit</strong></p> <p>AnonJr suggests that this must be a client configuration issue, as all other components appear to be functioning correctly. </p> <p>I discounted a simple client configuration issue because this is the only application affected by the issue described I have tested all the options under Tools > Internet Options > Temporary Files > Settings with no change in behaviour. </p> <p>What other client configuration options should I be considering?</p> <p><strong>Edit 2 - a solution</strong></p> <p>The accepted answer prompted me to search for a known issue with IE6 requesting multiple copies of images when HTML is generated from client-side script - <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;319546" rel="nofollow noreferrer">http://support.microsoft.com/default.aspx?scid=kb;en-us;319546</a>.</p> <p>The article (having stated that this behaviour is "by design") suggests a work-around of pre-caching the required images by loading them into an invisible DIV:</p> <pre><code>&lt;DIV style='display:none'&gt;&lt;IMG SRC='image.gif'&gt;&lt;/DIV&gt; </code></pre> <p>This appears to work for me - I can no longer replicate the problem by clearing my browser cache in the middle of a session, and a Fiddler trace shows each image being requested only once.</p> <p>I did find one caveat which I wasn't aware of before; the IE cache is case-sensitive, so a cached image will only be used if the case of the file name specified in the invisible DIV matches that used elsewhere in the page.</p>
<p>This smacks of an IE6 bug where the browser makes multiple requests for the same resource. For example if the content calls for the display of a small icon repeated 20 times in a list, instead of just fetching that image once, it attempts to fetch it 20 times. OK 19 of the responses are 304 Not Modified but that's still 19 extra round trips to the server.</p> <p>I've found in the past with this excessive requesting eventually you end up with too many unfullfilled requests. At that point further requests to the server even for other pages struggle to get a response, at least for a while.</p> <p>I'm not sure that this is what is happening in your case, one way to examine this is to use IE7 instead to see if you get the same problem, this bug was fixed in IE7.</p> <p><strong>Edit</strong>: Now that the problem is confirmed to be the bug I was refering to you should also note the KB reference to a 'short time delay'. The underlying problem is that in order to re-use a newly fetched image the browser needs to do work that is defered until the current chunk of javascript has completed. More than a 'short time delay' is needed, an asynchronous approach is needed. </p> <p>I've used the display:none DIV approach to pre-fetching the images and this works well for AJAX style work. However if you have code running during or before the onload event of a window you will still have the problem when adding images in this code. A setTimeout is needed in order to get further code to run after the onload event is complete.</p>
<p>You may want to focus your attention on tweaking the caching settings on the client end. If the images are being sent by the server, then its not likely to be an IIS issue. If the HTML for the images is being sent to the browser, its not an ASP issue. That leaves the client.</p> <p>The proxy may be mitigating some of the issues, and/or it could be a factor in how IE6 decides to cache images, etc.</p>
39,171
<p>I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:</p> <pre><code>@CollectionOfElements(fetch = EAGER) @JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note")) @Column(name = "substitution") @IndexColumn(name = "listIndex", base = 0) @Lob private List&lt;String&gt; substitutions; </code></pre> <p>So basically I may have a Note with some subsitutions, say <code>"foo"</code> and <code>"fizzbuzz"</code>. So in my main table I could have a Note with id 4 and in my <code>NOTE_JOIN_TABLE</code> I would have two rows, <code>"foo"</code> and <code>"fizzbuzz"</code> that both have a relationship to the Note.</p> <p>However, when one of these is inserted into the DB <strong>the larger substitution values are cropped to be as long as the shortest.</strong> So in this case I would have <code>"foo"</code> and <code>"fiz"</code> in the DB instead of <code>"foo"</code> and <code>"fizzbuzz"</code>.</p> <p>Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate.</p>
<p>To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure out how to traverse the XML returned. If you can't do Java, then I suggest PHP because it could be already installed, and have the proper modules loaded. This link might be helpful:</p> <p><a href="http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html" rel="nofollow noreferrer">http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html</a></p>
<p>Are you trying to implement a client to a web service hosted somewhere else? If so, Java's not necessary. You can do web service clients in <a href="http://www.dotnetjunkies.ddj.com/Tutorial/4D13CEFA-D0FD-44BE-8749-8D17B5757564.dcik" rel="nofollow noreferrer">.NET</a>, <a href="http://sourceforge.net/projects/nusoap/" rel="nofollow noreferrer">PHP</a>, <a href="http://raa.ruby-lang.org/project/soap4r" rel="nofollow noreferrer">Ruby</a>, or pretty much any modern web technology out there. All you need is a WSDL document to provide metadata about how to invoke the services.</p>
7,672
<p>I have a string that I need to convert to the equivalent array of bytes in .NET. </p> <p>This ought to be easy, but I am having a brain cramp.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?redirectedfrom=MSDN&amp;view=netframework-4.7.2" rel="noreferrer">You need to use an encoding</a> (<code>System.Text.Encoding</code>) to tell .NET what you expect as the output. For example, in <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.unicode?view=netframework-4.7.2#System_Text_Encoding_Unicode" rel="noreferrer">UTF-16 (= <code>System.Text.Encoding.Unicode</code>)</a>:</p> <pre><code>var result = System.Text.Encoding.Unicode.GetBytes(text); </code></pre>
<p>Like this:</p> <pre><code> string test = "text"; byte[] arr = Encoding.UTF8.GetBytes(test); </code></pre>
29,883
<p>I got this page, and have some problems with ie &lt; 7 and opera 7.11</p> <p><a href="http://browsershots.org/png/original/c5/c5bac9b3838ba30cfebae2f03f896548.png" rel="nofollow noreferrer">This</a> is what i hoped to be the layout in all browsers, and these are the IE ones instead: <a href="http://browsershots.org/screenshots/97347e42778e88203c896cc3f30134bd/" rel="nofollow noreferrer">ie 5.5</a> and <a href="http://browsershots.org/screenshots/b53d6391290363ea1e7ada0e77bdca20/" rel="nofollow noreferrer">ie 6.0</a>.</p> <p>the xhtml is quite simple:</p> <pre><code>print "&lt;div id=\"page\"&gt; &lt;div id=\"header\"&gt; &lt;ul id=\"nav\"&gt; &lt;li&gt;&lt;a href=\"/\" class=\"first\"&gt;Címlap&lt;div&gt;Az oldal címlapja&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=\"/blog\"&gt;Blogok&lt;div&gt;Minden bejegyzés&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=\"/friss\"&gt;Friss tartalom&lt;div&gt;Aktuális témák&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- header --&gt; &lt;div id=\"main\"&gt;&lt;div id=\"main-in\"&gt; &lt;div id=\"right\"&gt;"; do_boxes(); print " &lt;/div&gt; &lt;!-- right --&gt; &lt;div id=\"left\"&gt;"; do_content(); print"&lt;/div&gt; &lt;!-- left --&gt; &lt;/div&gt;&lt;/div&gt;&lt;!-- main --&gt; &lt;/div&gt;"; </code></pre> <p>Where a the content made from posts and a post looks like: </p> <pre><code> &lt;div class="post"&gt; &lt;h2&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast"&gt;Newcastleben betiltották a ketreces tojást&lt;/a&gt;&lt;/h2&gt; &lt;div class="author"&gt;warnew | 2008. october 16. 20:26 &lt;/div&gt; &lt;p&gt;Az angliai Newcastle Városi Tanácsa kitiltotta a ketreces baromfitartásból származó tojásokat az iskolai étkeztetésből, személyzeti éttermekből, rendezvényekről es a "hospitality outletekből".&lt;/p&gt; &lt;p&gt;A ketreces csirke- és pulykahúst még nem tiltották be, de vizsgálják a kérdést, ahogy a &lt;a href="http://en.wikipedia.org/wiki/Halal"&gt;Halal&lt;/a&gt; hús és a ketreces tojásból készült sütemények és tésztafélék tiltását is.&lt;/p&gt; &lt;ul class="postnav"&gt; &lt;li&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast%7D"&gt;Tovább&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast#comments"&gt;Hozzászólások (0)&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- post --&gt; </code></pre> <p>and a box is like this: </p> <pre><code>&lt;div id="ownadbox" class="box"&gt; &lt;h5&gt;Viridis matrica&lt;/h5&gt; &lt;a href="http://viridis.hu/blog/2/172/nepszerusits-minket" title="Népszerűsíts minket"&gt;&lt;img src="http://viridis.hu/files/viridis_matrica_jobb.png" alt="viridis matrica"/&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>The -what i think is - relevan css:</p> <pre><code>body { background : transparent url(/images/design/background.png) repeat; } #page { margin : 0px auto; width : 994px; background : transparent url(/images/design/header.jpg) no-repeat top left; } div#header { width : 746px; margin : 0px auto; } div#header ul#nav { padding-top : 170px; margin-left : 3px; margin-right : 3px; border-bottom : #896e51 solid 7px; overflow : hidden; } div#header ul#nav li { display : block; float : left; width : 120px; margin-bottom : 7px; } div#main { width : 746px; margin : 0px auto; } div#main div#main-in { padding : 30px 20px; background : transparent url(/images/design/content-background.png) repeat-y top left; overflow : hidden; } div#main div#main-in div#left { width : 460px; overflow : hidden; float : left; } div#main div#main-in div#left div.post { clear : left; margin-bottom : 35px; } div#main div#main-in div#right { width : 215px; float : right; } div#main div#main-in div#right div.box { margin-bottom : 30px; clear : both; } </code></pre> <p>The live version is <a href="http://viridis.hu/index3.php" rel="nofollow noreferrer">here</a>, but after I got it fixed it's gona move - thats the reason behind the long codes in the post.</p>
<p>Do you <em>really</em> need to support IE5.5? That seems needlessly painful. Unless you're explicitly doing this for a client who's using the browser, you can pretty much assume that everyone uses IE6 or later.</p> <p>The CSS support in IE6 is flaky, and almost nonexistent in IE versions older than that. Your best bet for such ancient browsers may be to just display a separate version of the site for those</p> <p>Edit: There are several things you can do to patch up IE. Conditional comments can be used to add specific javascript and CSS hacks for various versions of IE, and the following files in particular, do a lot to add in missing functionality:</p> <pre><code>&lt;!--[if lt IE 7]&gt;&lt;script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;!--[if lt IE 8]&gt;&lt;script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"&gt;&lt;/script&gt;&lt;![endif]--&gt; </code></pre> <p>In addition, make sure IE doesn't jump into quirks mode. There are simple javascript snippets that test which mode the current page is being rendered in, but the main way to avoid quirks mode is to ensure that there is <em>nothing</em> (not even the <code>&lt;?xml</code> prolog tag) before the doctype, and that the doctype is strict.</p>
<p>Take a look at a stripped-down layout that works, such as on <a href="http://www.alistapart.com/d/holygrail/example_1.html" rel="nofollow noreferrer">A List Apart</a>. Start with a working layout such as this and then edit it to your liking. I find this is easier than trying to fix a broken layout.</p>
40,913
<p>I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition.</p> <p>Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object.</p>
<p>Hmm, must read docs harder next time.</p> <pre><code>var theComposition = app.project.item(1); var theTextLayer = theComposition.layers[1]; theTextLayer.property("Source Text").setValue("This text is from code"); </code></pre>
<p>I wrote a simple function for myself to change properties. Here it is:</p> <pre><code>function change_prop(prop, name, value){ var doc = prop.value; doc[name] = value; prop.setValue(doc); return prop; } </code></pre> <p>Example use:</p> <pre><code>// Changing source text change_prop(text_layer.property("Source Text"), "text", "That's the source text"); // Changing font size change_prop(text_layer.property("ADBE Text Properties").property("ADBE Text Document"), "fontSize", 10) </code></pre>
9,483