instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<pre><code>something.each do |x|
#lots of stuff
end if some_condition
</code></pre>
|
<p>I think the popular way is to <strong>use statement modifiers only if it is a one-liner</strong>.
In all other cases, use the normal if style prevalent in C, Java etc.</p>
<pre><code>bail_out if reqd_param.nil?
if its_gonna_be_long then
long_exec stmt1
long_exec stmt2
....
end
</code></pre>
|
<p>In the organization I work for we have started to flag such constructs for re-write.</p>
| 25,641
|
<p>Are there any good online resources for how to create, maintain and think about writing test routines for numerical analysis code?</p>
<p>One of the limitations I can see for something like testing matrix multiplication is that the obvious tests (like having one matrix being the identity) may not fully test the functionality of the code.</p>
<p>Also, there is the fact that you are usually dealing with large data structures as well. Does anyone have some good ideas about ways to approach this, or have pointers to good places to look?</p>
|
<p>It sounds as if you need to think about testing in at least two different ways:</p>
<ol>
<li><p>Some numerical methods allow for some meta-thinking. For example, invertible operations allow you to set up test cases to see if the result is within acceptable error bounds of the original. For example, matrix <em>M-inverse</em> times the matrix <em>M</em> * random vector <em>V</em> should result in <em>V</em> again, to within some acceptable measure of error.<br>
Obviously, this example exercises matrix inverse, matrix multiplication and matrix-vector multiplication. I like chains like these because you can generate quite a lot of random test cases and get statistical coverage that would be a slog to have to write by hand. They don't exercise single operations in isolation, though.</p></li>
<li><p>Some numerical methods have a closed-form expression of their error. If you can set up a situation with a known solution, you can then compare the difference between the solution and the calculated result, looking for a difference that exceeds these known bounds.</p></li>
</ol>
<p>Fundamentally, this question illustrates the problem that testing complex methods well requires quite a lot of domain knowledge. Specific references would require a little more specific information about what you're testing. I'd definitely recommend that you at least have <a href="http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html" rel="nofollow noreferrer">Steve Yegge's recommended book list</a> on hand.</p>
|
<p>Check out a book by <a href="http://en.wikipedia.org/wiki/David_Gries" rel="nofollow noreferrer">David Gries</a> called <a href="https://rads.stackoverflow.com/amzn/click/com/0387964800" rel="nofollow noreferrer" rel="nofollow noreferrer">The Science of Programming</a>. It's about proving the correctness of programs. If you want to be sure that your programs are correct (to the point of proving their correctness), this book is a good place to start.</p>
<p>Probably not exactly what you're looking for, but it's the computer science answer to a software engineering question.</p>
| 3,714
|
<p>I have been learning C++ for a while now, I find it very powerful. But, the problem is the the level of abstraction is not much and I have to do memory management myself.
What are the languages that I can use which uses a higher level of abstraction.</p>
|
<p>Java, C#, Ruby, Python and JavaScript are probably the big choices before you.</p>
<p><a href="http://en.wikipedia.org/wiki/Java_(programming_language)" rel="noreferrer">Java</a> and <a href="http://en.wikipedia.org/wiki/C_Sharp" rel="noreferrer">C#</a> are not hugely different languages. This big difference you'll find from C++ is memory management (i.e. objects are automatically freed when they are no longer referenced). You would chose these if you were interested in desktop style applications, or keen on static typing (and you'd probably choose between them based on how you feel towards Microsoft and the Windows platform). In both cases you'll find much richer standard libraries than you'll be used to from C++.</p>
<p><a href="http://en.wikipedia.org/wiki/Python_(programming_language)" rel="noreferrer">Python</a> and <a href="http://en.wikipedia.org/wiki/Ruby_(programming_language)" rel="noreferrer">Ruby</a> take a step away from static typing, into a world where you can call and method on any object (and fail at runtime if it's not there). That is both a blessing (a lot less boilerplate code) and a curse (the compiler can't catch those errors for you anymore). Once again, you'll find they have richer standard libraries, and are higer level again than Java / C#. Performance is the main downfall, with Python being somewhat faster than Ruby as I understand it. To choose between them, you'd probably choose Ruby if you're interesting in web development for the Ruby on Rails framework community, and otherwise go with Python.</p>
<p><a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> is even more different from C++ in that it does away with classes entirely. Objects are simply cloned from other objects and can have methods and properties added to them at runtime. Very flexible, but also very easy to make into a total mess. JavaScript is the only real choice if you're interested in running applications in a browser, which is really coming into its own as a platform. You'll find the standard libraries available rather limited if you're not doing a lot with the browser, but there are quite a few good frameworks which fill in some of the gaps.</p>
<p>Some other interesting, though more niche choices are</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Smalltalk" rel="noreferrer">Smalltalk</a> - More or less in the Ruby and Python camp, and significantly faster as I understand it. Be careful though _ I've seen lots of good engineers learn Smalltalk and never come back ;)</li>
<li><a href="http://en.wikipedia.org/wiki/Objective-C" rel="noreferrer">Objective-C</a> - When C went object oriented, C++ went one way (static typing), and Objective-C went the other (dynamic typing). It's quite Smalltalk inspired, and has a good standard library if you're in Mac / iPhone land. In terms of memory management, unlike everything else I've listed, it's not garbage collected (though that's now an option on Mac OS X 10.5), but it does have a reference counting scheme which makes life significantly simpler than managing memory by hand.</li>
<li><a href="http://en.wikipedia.org/wiki/Lisp_programming_language" rel="noreferrer">Lisp</a> - I've never learnt it myself beyond what I needed for minor Emacs hacking. As I understand it, the libraries were nice in their day, but though the language remains supremely elegant, they've fallen a little behind the times.</li>
<li><a href="http://en.wikipedia.org/wiki/Haskell_(programming_language)" rel="noreferrer">Haskel</a> - If you wanted a complete break from objects and classes, Haskel and it's functional approach is an interesting way to go (or Lisp as above, or <a href="http://en.wikipedia.org/wiki/F_Sharp_programming_language" rel="noreferrer">F#</a> if you are in .Net land). Basically, you're giving up loops and variables in favour of doing everything recursively. Takes some time to wrap your mind around, and probably isn't practical for most real world applications, but it's a good one to learn.</li>
<li><a href="http://en.wikipedia.org/wiki/Eiffel_(programming_language)" rel="noreferrer">Eiffel</a> - I love it - Very clean syntax, and designed for serious engineering type systems. Statically types like C# and Java, and with a weaker standard library, but it will make you really think about language and class library design.</li>
<li><a href="http://en.wikipedia.org/wiki/ActionScript" rel="noreferrer">ActionScript</a> and <a href="http://en.wikipedia.org/wiki/Adobe_Flex" rel="noreferrer">Flex</a> - The programming interface to Flash, which is based on what seems to be a statically typed version of JavaScript. I've played with it a bit, and it's quite slick if you're interested in developing media based applications. You can also push beyond the browser with Flex and into the <a href="http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime" rel="noreferrer">Air</a> platform to build real desktop apps.</li>
</ul>
|
<p>Since you are already into C++, next step would be to learn .Net through <a href="http://www.ondotnet.com/pub/a/dotnet/2003/01/13/intromcpp.html" rel="nofollow noreferrer">managed C++</a> or managed extensions for C++..this will get you a step in the big world of .Net framework..Once you understand the framework, makes it more comfortable to learn other .Net languages like C#, VB.Net etc.</p>
<p><em>One of the areas that MC++ excels in, and is in fact unique in amongst the .NET languages, is the ability to take an existing unmanaged (C++) application, recompile it with the /clr switch, have it generate MSIL and then run under the CLR. This extraordinary feat is aptly termed "It Just Works (IJW)!" There are some limitations, but for the most part, the application will just run. The C++ code can consist of old-fashioned printf statements, MFC, ATL, or even templates!</em></p>
| 8,623
|
<p>I have some XML in an XmlDocument, and I want to display it on an ASP.NET page. (The XML should be in a control; the page will have other content.) Right now, we're using the Xml control for that. Trouble is, the XML displays with no indentation. Ugly.</p>
<p>It appears that I'm supposed to create an XSLT for it, but that seems kind of boring. I'd rather just throw it into a control and have it automagically parse the XML and indent correctly. Is there an easy way to do that?</p>
|
<p>You could try to use XmlWriter/XmlTextWriter, set the writer's Indentation property, write to a StringBuilder or MemoryStream, and output the result inside a <pre> tag</p>
|
<p>You can find a slightly modified version of the XSLT that IE uses to transform XML to HTML when viewing in IE at <a href="http://www.dpawson.co.uk/xsl/sect4/N10301.html#d15977e117" rel="nofollow noreferrer">http://www.dpawson.co.uk/xsl/sect4/N10301.html#d15977e117</a>.</p>
<p>I have used it in a WebBrowser control in a WinForms application, and it works lika a charm. I have not tested it in FireFox/Chrome/Safari/Operat, though.</p>
| 45,597
|
<p>Does anyone have an XSLT that will take the app.config and render it into a non-techie palatable format?</p>
<p>The purpose being mainly informational, but with the nice side-effect of validating the XML (if it's been made invalid, it won't render)</p>
|
<p>First draft at a solution to show</p>
<ul>
<li>Connection Strings</li>
<li>App Settings</li>
</ul>
<p>Whack this in the app.config:</p>
<pre><code><?xml-stylesheet type="text/xsl" href="display-config.xslt"?>
</code></pre>
<p>And this is the contents of display-config.xslt:</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Settings</h2>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="connectionStrings">
<h3>Connection Strings</h3>
<table border="1">
<tr bgcolor="#abcdef">
<th align="left">Name</th>
<th align="left">Connection String</th>
</tr>
<xsl:for-each select="add">
<tr>
<td><xsl:value-of select="@name"/></td>
<td><xsl:value-of select="@connectionString"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
<xsl:template match="appSettings">
<h3>Settings</h3>
<table border="1">
<tr bgcolor="#abcdef">
<th align="left">Key</th>
<th align="left">Value</th>
</tr>
<xsl:for-each select="add">
<tr>
<td><xsl:value-of select="@key"/></td>
<td><xsl:value-of select="@value"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
<p>What type of conversion are you looking for? Just for informational purposes? What level of detail are you looking to transform?</p>
| 22,100
|
<p>Let's say that we have an ARGB color:</p>
<pre><code>Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
</code></pre>
<p>When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is <code>Color.FromARGB(255, 162, 133, 255);</code></p>
<p>The solution should work like this:</p>
<pre><code>Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);
</code></pre>
<p>What is <code>ToRGB</code>'s implementation? </p>
|
<p>It's called <a href="http://en.wikipedia.org/wiki/Alpha_compositing" rel="noreferrer">alpha blending</a>.</p>
<p>In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.</p>
<pre><code>alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
</code></pre>
<p><em>note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly</em></p>
<p><strong>Edited to add:</strong></p>
<p>If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). </p>
<p>In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).</p>
|
<p>if you don't need to know this pre-render, you could always use the win32 method of getpixel, I believe. </p>
<p>Note: typing on iPhone in the middle of Missouri with no inet access. Will look up real win32 example and see if there is a .net equivalent.</p>
<p>In case anyone cares, and doesn't want to use the (excellent) answer posted above, you can get the color value of a pixel in .Net via this link <a href="http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx" rel="nofollow noreferrer">MSDN example</a></p>
| 2,490
|
<p>This is a continuation of <a href="https://3dprinting.stackexchange.com/questions/19523/filament-not-being-extruded">this question</a> where comments and answers were extremely helpful in diagnosing the issue, which I am still unable to solve.</p>
<p>I determined I have the problem shown in figure 3 on <a href="https://3dprinting.stackexchange.com/questions/15629/what-are-ways-to-avoid-heat-creep">this question</a>. How I confirmed that is I started a print and monitored it closely. As soon as the filament stopped coming out I paused the print and pulled out the filament - it looked like this:</p>
<p><a href="https://i.stack.imgur.com/OO4oZ.png" rel="nofollow noreferrer" title="Photo of filament with different sized diameter after being pulled from hotend"><img src="https://i.stack.imgur.com/OO4oZ.png" alt="Photo of filament with different sized diameter after being pulled from hotend" title="Photo of filament with different sized diameter after being pulled from hotend" /></a></p>
<p>I snipped the expanded part off and re-inserted the filament back in, hit resume print and it continued printing normally, except it had skipped a layer or two.</p>
<p>What I understand is there can be a few reasons for this problem:</p>
<ol>
<li>Filament moving too fast and not being able to melt at the nozzle</li>
<li>Too much heat in the radiator block causes the filament to soften up and unable to be pushed by the incoming filament.</li>
</ol>
<p>To combat case 1 I reduced the speed of the print using the knob down to 80 % which already felt like it is too slow, but that didn't seem to make a difference. I also tried printing at speeds of 85 %, 90 %, and 95 % as well and the problem occurred in all of them. So this leads me to believe that speed is probably not the issue.</p>
<p>I read that there could also be another thing causing case 1 and that is over-extrusion. To verify this I did the 100 mm extrusion test where I marked 0 mm and 100 mm and extruded 100 mm manually in steps of 0.1 mm. It took a while but eventually in the end I determined that it is under-extruding at 95 mm actual filament extruded which means there is less filament being pushed which should actually be working against the jam. I pulled the filament out after the test to see what it looks like and this was it:</p>
<p><a href="https://i.stack.imgur.com/bCDQp.png" rel="nofollow noreferrer" title="Photo of filament with significantly different sized diameter"><img src="https://i.stack.imgur.com/bCDQp.png" alt="Photo of filament with significantly different sized diameter" title="Photo of filament with significantly different sized diameter" /></a></p>
<p>Nevertheless, I adjusted my E-steps from 93 to 99 and repeated the 100 mm test again which this time was about 1 mm off (99 mm actual filament extruded) but I guess my markings could be off too so it should be good enough. I again checked the filament and it still had an expansion on the end.</p>
<p>At this point, I'm assuming that there is no issue with my extruder and print speed, so I'm on to case 2.</p>
<p>I tried printing at 180 °C but that had no effect.</p>
<p>I also tried printing without heating the bed as I read that could affect the cooling of the radiator as the fan will be blowing hot air, but that also didn't help and the filament seized.</p>
<p>I took the fan cover off and set the nozzle to 200 °C. After a few minutes, I measured the surface temperatures on the cooling block/radiator using a multimeter which showed 47 °C on the top-most fin and 65 °C on the bottom-most. I also tried reducing the nozzle to 180 °C and took measurements again which were pretty much the same with about a degree or 2 off. Ok so maybe something is fishy here because in <a href="https://youtu.be/ItJTrTX6HJw?t=308" rel="nofollow noreferrer">this video</a> you can see the temperatures he's reading are in the 35-40s range.</p>
<p>Just to confirm this was the problem I took quite a large home fan and directed it such that the stream is hitting the radiator from about 5 cm (this is while the hot end fan is not mounted with the screws but hanging on the side, which was also blowing at the radiator). I waited a couple of minutes and measured the temperatures again which this time showed 35 °C on the top and 50 °C on the bottom. That was as low as I could get it and the house fan was pretty strong. I extruded another 100 mm manually and this is what the filament looked like afterward:</p>
<p><a href="https://i.stack.imgur.com/g12ZN.png" rel="nofollow noreferrer" title="Photo of filament with a blob of filament a the end after being pulled from the hotend"><img src="https://i.stack.imgur.com/g12ZN.png" alt="Photo of filament with a blob of filament a the end after being pulled from the hotend" title="Photo of filament with a blob of filament a the end after being pulled from the hotend" /></a></p>
<p>It still had a blob on the end and I'm pretty confident given more time it would clog up again.</p>
<p>Honestly, at this point, I feel like I've put way too much time and effort into resolving this issue and that is frustrating me as I fail to see any results.</p>
<p>I'm even more confused by the fact that I have had a couple of 3h prints go flawless, then out of the blue, it starts doing this problem. Sometimes it doesn't happen, sometimes it happens 3-5 times per print. I had an 8h print which went very well until the last 30 min when it clogged, thankfully I was around and I did the snipping procedure so the print finished but it is visible where it skipped a bunch of layers and has a weak spot.</p>
<p>It is quite annoying to have to babysit the printer like that and I'm really reaching out to anyone who'd be able to help me.</p>
|
<p>Yes.</p>
<p>The issue is, that there are small gaps between the layers. But you can coat the print in an airtight material. While epoxy and similar materials work very well, they are somewhat too viscous and take a long time to cure.</p>
<p>My special recipe for coating PLA prints with a fast-curing airtight thin layer is:</p>
<ol>
<li>Dissolve 1 g Paraloid B-72 in 20 ml acetone.</li>
<li>Dip or otherwise evenly coat the print and dry at room temperature for 10-20 minutes.</li>
</ol>
|
<p>Yes.</p>
<p>The issue is, that there are small gaps between the layers. But you can coat the print in an airtight material. While epoxy and similar materials work very well, they are somewhat too viscous and take a long time to cure.</p>
<p>My special recipe for coating PLA prints with a fast-curing airtight thin layer is:</p>
<ol>
<li>Dissolve 1 g Paraloid B-72 in 20 ml acetone.</li>
<li>Dip or otherwise evenly coat the print and dry at room temperature for 10-20 minutes.</li>
</ol>
| 2,166
|
<p>I have asked our hosting provider to add mod_python to our httpd server. The server appears to be in an hsphere cluster and they appear to use yum to administer it. He is reporting some dependencies missing and I do't quite understand how that could have come about.</p>
<p>versions (this is as much as I have been given):
CentOS 5
apache - 2 (but he's not sure about the exact version)
mod_python - 3.3.1
numpy - 1.1.1
scipy - 0.6.0
yum - 3.2.8
hsphere - 3.1 patch 1</p>
<p>The error he is reporting is as follows:</p>
<pre><code>yum install mod_python
...
Package mod_python.i386 0:3.2.8-3.1 set to be updated
Processing Dependency: httpd >- 2.0.40 for package: mod_python
Processing Dependency: httpd-mmn = 20051115 for package: mod_python
Finished Dependency Resolution
Error: Missing Dependency: httpd >= 2.0.40 is needed by package mod_python
Error: Missing Dependency: httpd-mmn = 20051115 is needed by package mod_python
</code></pre>
<p>Not being a UNIX admin I only have a naive guess about this, but the message would seem to suggest that there is a version mismatch between httpd and mod_python rather than the dependencies being missing completely. </p>
<p>So my question is, what should I ask/tell the Administrator to do?</p>
<p>Is there something obviously wrong with the combination of components above?</p>
|
<p>We have mod_python 3.3 running on Apache 2.2 on a CentOS (forgot the version). All we did is download the tar.gz (from <a href="http://httpd.apache.org/modules/python-download.cgi" rel="nofollow noreferrer">http://httpd.apache.org/modules/python-download.cgi</a>) , extract it...</p>
<pre><code>$ ./configure --with-apxs=/usr/local/apache2/bin/apxs
$ ./make
$ su
$ make install
</code></pre>
<p>Everything works fine. We couldn't use yum so everything is built from source.
My suggestion would be to try to build from source.</p>
|
<p>My first reaction would be to <code>yum update apache</code> (or just a <code>yum update</code>). </p>
<p>Then try the <code>yum install mod_python</code>.</p>
| 20,100
|
<p>FCKeditor has InsertHtml API (<a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API" rel="nofollow noreferrer">JavaScript API document</a>) that inserts HTML in the current cursor position. How do I insert at the very end of the document?</p>
<p>Do I need to start browser sniffing with something like this</p>
<pre><code>if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
</code></pre>
<p>or is there a blessed way that I missed?</p>
<p>Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack.</p>
|
<p>It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and reinsert everything into the editor. Although it does say </p>
<blockquote>
<p>Note that when using this method, you will lose any listener that you may have previously registered on the editor.EditorDocument.</p>
</blockquote>
<p>Hope that helps!</p>
|
<pre><code>var oEditor = FCKeditorAPI.GetInstance('Editor_instance') ;
OldText=oEditor.GetXHTML( true );
oEditor.SetData( OldText+"Your text");
</code></pre>
| 4,487
|
<p>I broke 2 keys (i.e. left ctrl, enter) on my Asus UX31A laptop and it seems that this model is too old to find replacement keys.</p>
<p>Is there any way I can find a 3D model of the needed keys to have them 3D printed?</p>
<p>I do not have a printer nor I have any experience in this field.
What I need is either someone that has models for these or that can point me where I can find such models.</p>
|
<p>This is more off-topic as an answer, but serves as a possible solution.</p>
<p>Replacementlaptopkeys.com is a resource that appears to have keycaps for the model you've noted.</p>
<p><a href="https://www.replacementlaptopkeys.com/asus-zenbook-ux31a-db71-laptop-keys-replacement-dark-brown-black/" rel="nofollow noreferrer">https://www.replacementlaptopkeys.com/asus-zenbook-ux31a-db71-laptop-keys-replacement-dark-brown-black/</a></p>
<p>At seven dollars a key, it's going to be less expensive than 3D printing to accomplish your objective.</p>
<p>If you owned a 3D printer, it would not be less expensive to purchase, but the work involved would increase your cost to have such keys commissioned. As a 3D printed object, the strength is going to be less than a keycap purchased from the linked site.</p>
|
<p>You're better off if you can get the key from Fred's link. I was impressed by the detail of a 3D-printed battery cover for electronic calipers, but I'm sure it took much work to get it right. Also, ebay has keyboards for your model.</p>
| 1,943
|
<p>I'm using a <code>BindingList<T></code> in my Windows Forms that contains a list of "<code>IComparable<Contact></code>" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid.</p>
<p>There is a way described on MSDN online which shows how to implement a custom collection based on <code>BindingList<T></code> which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code?</p>
<p>I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.</p>
|
<p>I higly appreciate <a href="https://stackoverflow.com/a/281324/3834">Matthias' solution</a> for its simplicity and beauty.</p>
<p>However, while this gives excellent results for low data volumes, when working with large data volumes the performance is not so good, due to reflection.</p>
<p>I ran a test with a collection of simple data objects, counting 100000 elements. Sorting by an integer type property took around 1 min. The implementation I'm going to further detail changed this to ~200ms.</p>
<p>The basic idea is to benefit strongly typed comparison, while keeping the ApplySortCore method generic. The following replaces the generic comparison delegate with a call to a specific comparer, implemented in a derived class:</p>
<p>New in SortableBindingList<T>:</p>
<pre><code>protected abstract Comparison<T> GetComparer(PropertyDescriptor prop);
</code></pre>
<p>ApplySortCore changes to:</p>
<pre><code>protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
List<T> itemsList = (List<T>)this.Items;
if (prop.PropertyType.GetInterface("IComparable") != null)
{
Comparison<T> comparer = GetComparer(prop);
itemsList.Sort(comparer);
if (direction == ListSortDirection.Descending)
{
itemsList.Reverse();
}
}
isSortedValue = true;
sortPropertyValue = prop;
sortDirectionValue = direction;
}
</code></pre>
<p>Now, in the derived class one have to implement comparers for each sortable property:</p>
<pre><code>class MyBindingList:SortableBindingList<DataObject>
{
protected override Comparison<DataObject> GetComparer(PropertyDescriptor prop)
{
Comparison<DataObject> comparer;
switch (prop.Name)
{
case "MyIntProperty":
comparer = new Comparison<DataObject>(delegate(DataObject x, DataObject y)
{
if (x != null)
if (y != null)
return (x.MyIntProperty.CompareTo(y.MyIntProperty));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
// Implement comparers for other sortable properties here.
}
return comparer;
}
}
}
</code></pre>
<p>This variant requires a little bit more code but, if performance is an issue, I think it worths the effort.</p>
|
<p>Not for custom objects. In .Net 2.0, I had to roll my on sorting using BindingList. There may be something new in .Net 3.5 but I have not looked into that yet. Now that there is LINQ and the sorting options that come with if this now may be easier to implement.</p>
| 31,062
|
<p>Here's a simplified version of my scenario:</p>
<ul>
<li>I have a table named <strong>Project</strong> that I reference via an 'id' field.</li>
<li>I have a table named <strong>Photo</strong> that has a field named 'project_id' which I use to relate multiple photos to a single project. The Photo table also has an auto-incrementing 'id' field that I use for ordering, amongst other things.</li>
</ul>
<p>Here's what I want to accomplish: <em>For a collection of Project id values, I wish to retrieve the last 5 photos added to each project</em> -- ideally in a single query, of course. :-)</p>
<p>Put another way, instead of imposing a single query limit, I would ideally like to specify a per project limit on the number of photos returned.</p>
<p>I am currently implementing this as one-query per project, so N projects = N queries (a good caching strategy will certainly reduce the hurt, but that'll come later).</p>
<p>Anyone have a solution?</p>
<p>Thanks.</p>
|
<p>For the "last n items" problem in MySQL, take look here: <a href="https://stackoverflow.com/questions/271730/how-to-select-maximum-3-items-per-users-in-mysql">How to select maximum 3 items per users in MySQL?</a> (it's right in the top answer).</p>
<p>When you take it from there, all you are missing is a JOIN with your <code>Projects</code> table, which should be easy to do.</p>
|
<pre><code>SELECT project.*, photo.*
FROM photo
LEFT JOIN project USING project_id
WHERE photo.project_id = '{$id}'
ORDER BY photo_id DESC
LIMIT project.project_photos_limit
</code></pre>
<p>Try that? (with your fieldnames, obviously)</p>
| 40,526
|
<p>We've installed Windows Search Server Express on one of our servers, which apparently runs on top of sharepoint.</p>
<p>Sharepoint was installed on port 80, where our "normal" intranet runs. When I disable the intranet and run the sharepoint site, everything works as intended. The intranet is linked in many places it would be a pain to move it, so I'm trying to move sharepoint to another "place" (hoping this is less of a pain), either a different port or as a virtual directory under the main site. </p>
<p>First, when I make any of these changes, it fails to get access to the intranet root. Not sure what it is looking for there, but ok, I give "Network service" (the acocunt the "Sharepoint 80" application pool is running under) access to the intranet root. This gets me one step further, I am stumped:</p>
<p>When I move the Sharepoint website to another port, it complains that it can't find default.aspx (there is none, but also it doesn't need it when running on port 80)</p>
<p>When I move it to a sub folder of the existing site, and try to open the global.asax in the browser, ti tells me that this extension is prohibited, even though the "Application configuration" is - as far as I understand - identical to that of the Sharepoint site, and allows GET, HEAD, POST, DEBUG for .asax.</p>
<p>Any suggestions?</p>
|
<p>Sharepoint sites should be able to run on any port- if you go into Sharepoint Central Admin and create or delete web applications without a problem.</p>
<p>Is it your intention to run heterogenously with Sharepoint and your regular site both on Port 80? I know that you can create a web application on 80 and then not have a root site collection ( Sharepoint applications consist of a Web Application that runs on a certain port and any number of Site Collections within that, each of which has it's own directory path and can contain lists, libraries, other Site Collections and so on ) just creating one on a different path, but I don't know for sure how that would work alongside an existing web site on the same port- it may not play nice. Again, you can create and delete site collections from the Sharepoint Central Admin page, which is linked from your Administrative Tools list on your server.I would try this first, as if it works it's an easy solution.</p>
<p>Is Windows Search Server Express related to Sharepoint's own search facilities? If it is you may find that it expects to run using some of the Shared Service Provider facilities, which even Sharepoint doesn't expect to be running on the same port as the sites it's providing services for.</p>
|
<p>Thank you! I found the option in the sharepoint administration website.</p>
<p>I add this response to detail the steps I have taken - maybe they are useful for someone else.</p>
<p>In the sharepoint administration website (running flawlessly on another port), I chose "create or extend web applications", then "extend existing web application".</p>
<p>There, from the the drop down "Web application", "change web application" opens a popup with the web applications available. Search server was installed as "Sharepoint 80", so I selected that.</p>
<p>Then I selected "Create new IIS website", with a new name and a new port. All the other options looked fine to me as default. </p>
<p>Clicking OK, this creates a new web site in IIS, which was configured correctly. it doesn't work via the IP address of the server (<a href="http://192.x.x.x:8080" rel="nofollow noreferrer">http://192.x.x.x:8080</a>), only using the server name - but that's ok with me :)</p>
<p>I still had to make some adjustments with the access rights, but the full crawl is running and I can find a few documents already. Yay!</p>
| 34,193
|
<p>Doesn't an ORM usually involve doing something like a select *?</p>
<p>If I have a table, MyThing, with column A, B, C, D, etc, then there typically would be an object, MyThing with properties A, B, C, D. </p>
<p>It would be evil if that object were incompletely instantiated by a select statement that looked like this, only fetching the A, B, not the C, D:</p>
<p>select A, B from MyThing /* don't get C and D, because we don't need them */</p>
<p>but it would also be evil to always do this:</p>
<p>select A, B, C, D /* get all the columns so that we can completely instantiate the MyThing object */</p>
<p>Does ORM make an assumption that database access is so fast now you don't have to worry about it and so you can always fetch all the columns?</p>
<p>Or, do you have different MyThing objects, one for each combo of columns that might happen to be in a select statement?</p>
<p><strong>EDIT: Before you answer the question, please read Nicholas Piasecki's and Bill Karwin's answers. I guess I asked my question poorly because many misunderstood it, but Nicholas understood it 100%. Like him, I'm interested in other answers.</strong></p>
<hr>
<p>EDIT #2: Links that relate to this question:</p>
<p><a href="https://stackoverflow.com/questions/18655/why-do-we-need-entity-objects">Why do we need entity objects?</a></p>
<p><a href="http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx" rel="nofollow noreferrer">http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx</a>, especially the section "The Partial-Object Problem and the Load-Time Paradox"</p>
<p><a href="http://groups.google.com/group/comp.object/browse_thread/thread/853fca22ded31c00/99f41d57f195f48b" rel="nofollow noreferrer">http://groups.google.com/group/comp.object/browse_thread/thread/853fca22ded31c00/99f41d57f195f48b</a>?</p>
<p><a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html" rel="nofollow noreferrer">http://www.martinfowler.com/bliki/AnemicDomainModel.html</a></p>
<p><a href="http://database-programmer.blogspot.com/2008/06/why-i-do-not-use-orm.html" rel="nofollow noreferrer">http://database-programmer.blogspot.com/2008/06/why-i-do-not-use-orm.html</a></p>
|
<p>In my limited experience, things are as you describe--it's a messy situation and the usual cop-out "it depends" answer applies.</p>
<p>A good example would be the online store that I work for. It has a <code>Brand</code> object, and on the main page of the Web site, all of the brands that the store sells are listed on the left side. To display this menu of brands, all the site needs is the integer <code>BrandId</code> and the string <code>BrandName</code>. But the <code>Brand</code> object contains a whole boatload of other properties, most notably a <code>Description</code> property that can contain a substantially large amount of text about the <code>Brand</code>. No two ways about it, loading all of that extra information about the brand just to spit out its name in an unordered list is (1) measurably and significantly slow, usually because of the large text fields and (2) pretty inefficient when it comes to memory usage, building up large strings and not even looking at them before throwing them away.</p>
<p>One option provided by many ORMs is to lazy load a property. So we could have a <code>Brand</code> object returned to us, but that time-consuming and memory-wasting <code>Description</code> field is not until we try to invoke its <code>get</code> accessor. At that point, the proxy object will intercept our call and suck down the description from the database just in time. This is sometimes good enough but has burned me enough times that I personally don't recommend it:</p>
<ul>
<li>It's easy to forget that the property is lazy-loaded, introducing a SELECT N+1 problem just by writing a foreach loop. Who knows what happens when LINQ gets involved.</li>
<li>What if the just-in-time database call fails because the transport got flummoxed or the network went out? I can almost guarantee that any code that is doing something as innocuous as <code>string desc = brand.Description</code> was not expecting that simple call to toss a <code>DataAccessException</code>. Now you've just crashed in a nasty and unexpected way. (Yes, I've watched my app go down hard because of just that. Learned the hard way!)</li>
</ul>
<p>So what I've ended up doing is that in scenarios that require performance or are prone to database deadlocks, I create a separate interface that the Web site or any other program can call to get access to specific chunks of data that have had their query plans carefully examined. The architecture ends up looking kind of like this (forgive the ASCII art):</p>
<pre>
Web Site: Controller Classes
|
|---------------------------------+
| |
App Server: IDocumentService IOrderService, IInventoryService, etc
(Arrays, DataSets) (Regular OO objects, like Brand)
| |
| |
| |
Data Layer: (Raw ADO.NET returning arrays, ("Full cream" ORM like NHibernate)
DataSets, simple classes)
</pre>
<p>I used to think that this was cheating, subverting the OO object model. But in a practical sense, as long as you do this shortcut for displaying data, I think it's all right. The updates/inserts and what have you still go through the fully-hydrated, ORM-filled domain model, and that's something that happens far less frequently (in most of my cases) than displaying particular subsets of the data. ORMs like NHibernate will let you do projections, but by that point I just don't see the point of the ORM. This will probably be a stored procedure anyway, writing the ADO.NET takes two seconds.</p>
<p>This is just my two cents. I look forward to reading some of the other responses.</p>
|
<p>SELECT * is not bad. Did you ask whoever considered it to be bad "why?".</p>
| 37,230
|
<p>I'm storing a Word document in a SQL Server 2005 database in a varbinary(max) column. Is there a way to open this document from a VB.NET Windows Forms application without serialising to a file first (i.e. directly from the byte array I've read from the database)?</p>
|
<p>Depends on what's reading it. If it's Word, you'll probably have to serialize to a file, but if it's a function or library that can take an IO.Stream then you could wrap a new MemoryStream around the byte array and pass that.</p>
|
<p>Not really. You need to treat it like an e-mail attachment, where the file is generally copied to a temp folder that is cleaned out periodically.</p>
| 8,103
|
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder.</p>
|
<p>Use the LoginUrl property for the forms item?</p>
<pre><code><authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms>
</authentication>
</code></pre>
|
<p>I found the answer at <a href="http://www.codersource.net/asp_net_forms_authentication.aspx" rel="nofollow noreferrer">CoderSource.net</a>. I had to put the correct path into my web.config file.</p>
<pre><code><?xml version="1.0"?>
<configuration>
<system.web>
...
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Forms">
<forms loginUrl="~/FolderName/Login.aspx" />
</authentication>
...
</system.web>
...
</configuration>
</code></pre>
| 5,308
|
<p>I have XML files in a directory that I wish to get over to a webservice on a server that will validate them and return a true/false as to whether they are valid in construct and values etc.
Reason for server side processing is that the validation rules may change from time to time and need to adjust in one place as opposed to all client machines.</p>
<p>What would be the best mechanism to do this?</p>
<p>At the moment am wondering if passing the XMLDocument object from the client to the webservice as a parameter may be the way to go?</p>
<p>Am using .net 3 for this in C#</p>
|
<p>You might consider using something like a WCF service and streaming the xml up using the GZipStream. I am doing something similar to this and it is working pretty well. </p>
|
<p>Wouldn't a normal string be enough? It's overkill to serialize / deserialize an entire XDoc instance in my opinion. Of course, you can also zip the entire thing to reduce the size of the requests.</p>
| 44,238
|
<p>I have a batch process that reads data from multiple tables into a dataset based on a common key. I then build a second dataset of the destination data querying on the same key. </p>
<p>At this point I have two Datasets that are structurally identical (from a table/column layout perspective). I then have a process that adds any row that exists in source to the destination dataset. In addition, the process will attempt to update certain columns based on the common key as well. </p>
<p>The problem seems to come in when the DataAdapter.UPDATE command is called with existing rows that it needs to update.
Error:
System.InvalidOperationException was unhandled
Message="The table specified in the SELECT statement does not contain a unique key or identifier column, or the SELECT statement does not include all of the key columns."</p>
<p>Since I have no way of controlling what the PK is on the destination DB, is there a way to tell the Adapter what the key is for this particular update? I have "custom" set the primary keys for each DataTable in the Dataset.</p>
<p>This is a non user interfacing batch process and its perf requirements are quite low. (to explain the use of datasets, etc)</p>
<p>Any Thoughts?</p>
|
<p>profile the db and see what queries are being fired. copy the queries from Profiler and try to exe them manually. if they fail, then the problem is with the sql and the error is coming from the db and simply being passed up to your application.</p>
<p>this should at least tell u if the problem is caused by the lack of real PK's in the db.</p>
|
<p>you have to set the PK for each table in the dataset like you did.
i don't think there's a way for adapter to figure out what the PK's are by itself.
if there is and someone knows it i'm all ears.</p>
| 35,171
|
<p>Why does this work:</p>
<pre><code>$(window).keydown(function(event){
alert(event.keyCode);
});
</code></pre>
<p>but not this:</p>
<pre><code>$('#ajaxSearchText').keydown(function(event){
alert(event.keyCode);
});
</code></pre>
<p>I'm testing with Firefox 3.
Interestingly, neither of them work in IE7.</p>
|
<p>Checked this in Chrome, IE7 and Firefox 3.0.3. Works as it should. jQuery version 1.2.6.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript">
$(function()
{
$("#ajaxSearchText").keydown(function(event)
{
alert(event.keyCode);
});
});
</script>
</head>
<body>
<input type="text" id="ajaxSearchText"></input>
</body>
</html>
</code></pre>
|
<p>Because key events are not supported on the 'window' object.</p>
<p><a href="http://www.w3schools.com/jsref/obj_window.asp" rel="nofollow noreferrer">http://www.w3schools.com/jsref/obj_window.asp</a></p>
<p>But only on 'document':</p>
<p><a href="http://www.w3schools.com/jsref/dom_obj_event.asp" rel="nofollow noreferrer">http://www.w3schools.com/jsref/dom_obj_event.asp</a></p>
<p>If it ever worked then it was a bug in jQuery.</p>
| 22,673
|
<p>I am wondering if Unittesting and using statements can really go hand in hand as there is no way to mock the disposable object instantiated in the using statement. How would I be able to effectively unittest a method containing the following using statement?</p>
<pre>
public void MyMethod()
{
using(MyDisposableClass disp = new MyDisposableClass())
{
...
}
}
</pre>
<p>Are using statements simply forbidden when you are unit-testing?</p>
<p>Any comments appreciated.</p>
|
<p>No, using statements are certainly not forbidden. But what does MyDisposableClass actually do? It strikes me that this isn't really a matter of the using statement being a problem - it's a matter of the method creating a new object which you want to mock - <em>that's</em> the problem.</p>
<p>Do you genuinely need to mock MyDisposableClass? Can it be passed into MyMethod instead of being created inside it? As ever, the trick is to work out how to hook into the process and inject your own objects when you need to...</p>
|
<p>Using the <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow noreferrer">factory pattern</a> and/or <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection pattern</a> will greatly simplify the way you unit test methods that instantiate their own resources.</p>
<p>Here's a good read on the subject:</p>
<ul>
<li><a href="http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/" rel="nofollow noreferrer">Unit Testing, Mocking and Dependency Injection</a></li>
</ul>
| 46,802
|
<p>I have Java 1.5.0 installed on a Mac OS machine. I have the Java Embedding Plugin 0.9.6.4 installed and java enabled on the preferences panel. When I go to <a href="http://java.com/en/download/help/testvm.xml" rel="nofollow noreferrer">http://java.com/en/download/help/testvm.xml</a> the applet appears blank. Does anyone has an idea of what is happening?</p>
|
<p>I have found the solution. The Java Embedding Plugin uses the installed JVM which itself gets its proxy definitions from MacOS and not from Firefox. So, proxy definitions have to be defined for both MacOS/Safari and Firefox.
I've also updated Firefox and selected Java 1.5 on the Java preferences panel. However I'm not sure if these two actions helped solve the issue.</p>
|
<p>Firefox 3.0.1 on Mac OS X 10.5 should support java applets without any extra Java Embedding Plugin.</p>
| 15,525
|
<p>Is it possible to use a variable from one page in a piece of code on another? e.g. submit a form on one page and on the second page use a PHP script to add the data from the form to a MySQL table</p>
<p>Thanks for all the help </p>
|
<p>This is what the GET and POST 'super' globals are for.
<a href="http://www.tizag.com/phpT/postget.php" rel="nofollow noreferrer">http://www.tizag.com/phpT/postget.php</a></p>
|
<p>The script that generates the form does not have to be the script the processes the form. all it takes is for the FORM tag to point to the correct script. The only caveat is that whatever page you submit the form data to also has to then generate some suitable output (unless you do a AJAX POST).</p>
<p>If you're instead asking if two page executions can handle the same POSTed data, well that is quite a different question. At a simplistic level, you can have the first include() the second so it has access to all the same data. A bit more advanced is to re-create the original POST and synthesize a POST. This will probably require some JavaScript assistance. Another approach is to use PHP's session feature and put the value aside so a later script has access to it. This relies on the user then following the correct link, however!</p>
| 27,692
|
<p>I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<% If CBool(Eval("Deleted")) Then%>
...
<% Else%>
...
<% End If%>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>Is this possible? If not, what are the alternatives?</p>
|
<p>I might suggest keeping the code-front lean and writing out the desired text via a function result:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<%# GetText(Container.DataItem) %>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>And the code-behind:</p>
<pre><code>protected static string GetText(object dataItem)
{
if (Convert.ToBoolean(DataBinder.Eval(dataItem, "Deleted"))
return "Deleted";
return "Not Deleted";
}
</code></pre>
<p>I hope it helps.</p>
|
<p>Perhaps use the ItemDataBound event of a datalist. For gridview's its the rowdatabound event that is ideal for altering display of values based on other values in the result set.
<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx" rel="nofollow noreferrer">ItemDataBound event</a></p>
<p>So basically on itemdatabound you can play around with your conditionals. Again, this is an educated guess since I've typically done this with the RowDataBound event on gridview's.</p>
| 33,117
|
<p>I need to create a custom volume slider for a WMP object. The current slider is complicated to modify, and use, is there a simple way to generate a slider on an HTML page that can have it's value passed to a javascript function?</p>
|
<p><a href="http://jqueryui.com/demos/slider/" rel="noreferrer">jQuery UI Slider</a> (<a href="http://docs.jquery.com/UI/Slider" rel="noreferrer">API docs</a>)</p>
|
<p>The code below should be enough to get you started. Tested in Opera, IE and Chrome.</p>
<pre><code><script>
var l=0;
function f(i){
im = 'i' + l;
d=document.all[im];
d.height=99;
document.all.f1.t1.value=i;
im = 'i' + i;
d=document.all[im];
d.height=1;
l=i;
}
</script>
<center>
<form id='f1'>
<input type=text value=0 id='t1'>
</form>
<script>
for (i=0;i<=50;i++)
{
s = "<img src='j.jpg' height=99 width=9 onMouseOver='f(" + i + ")' id='i" + i + "'>";
document.write(s);
}
</script>
</code></pre>
| 20,850
|
<p>C++ 0x has template aliases (sometimes referred to as template typedefs). See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates" rel="noreferrer">here</a>. Current spec of C++ does not. </p>
<p>What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ?</p>
|
<blockquote>
<p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p>
</blockquote>
<p>The canonical way is to use a metafunction like thus:</p>
<pre><code>template <typename T>
struct my_string_map {
typedef std::map<std::string, T> type;
};
// Invoke:
my_string_map<int>::type my_str_int_map;
</code></pre>
<p>This is also used in the STL (<code>allocator::rebind<U></code>) and in many libraries including Boost. We use it extensively in a <a href="http://www.seqan.de/dddoc/html/index.html" rel="noreferrer">bioinformatical library</a>.</p>
<p>It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.</p>
<p>(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)</p>
|
<p>Sometimes you can just explicitly write out the untemplated typedefs for all the necessary types. If the base class is templated on multiple template args with only one type desired to be typedefed you can inherit a specialized class with typedef effectively included in the inherited class name. This approach is less abstruse than the metafunction approach.</p>
| 4,576
|
<p>I'm working on the K&R book. I've read farther ahead than I've done exercises, mostly for lack of time. I'm catching up, and have done almost all the exercises from chapter 1, which is the tutorial.</p>
<p>My issue was exercise 1-18. The exercise is to:</p>
<blockquote>
<p>Write a program to remove trailing blanks and
tabs from line of input, and to delete entirely blank lines</p>
</blockquote>
<p>My code (below) does that, and works. My problem with it is the trim method I implemented. It feels ... wrong ... somehow. Like if I saw similar code in C# in a code review, I'd probably go nuts. (C# being one of my specialties.)</p>
<p>Can anyone offer some advice on cleaning this up -- with the catch that said advice has to only use knowledge from Chapter 1 of K & R. (I know there are a zillion ways to clean this up using the full C library; we're just talking Chapter 1 and basic stdio.h here.) Also, when giving the advice, can you explain why it will help? (I am, after all, trying to learn! And who better to learn from than the experts here?)</p>
<pre><code>#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int max);
void trim(char line[], char ret[]);
int main()
{
char line[MAXLINE];
char out[MAXLINE];
int length;
while ((length = getline(line, MAXLINE)) > 0)
{
trim(line, out);
printf("%s", out);
}
return 0;
}
int getline(char line[], int max)
{
int c, i;
for (i = 0; i < max - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
line[i] = c;
if (c == '\n')
{
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void trim(char line[], char ret[])
{
int i = 0;
while ((ret[i] = line[i]) != '\0')
++i;
if (i == 1)
{
// Special case to remove entirely blank line
ret[0] = '\0';
return;
}
for ( ; i >= 0; --i)
{
if (ret[i] == ' ' || ret[i] == '\t')
ret[i] = '\0';
else if (ret[i] != '\0' && ret[i] != '\r' && ret[i] != '\n')
break;
}
for (i = 0; i < MAXLINE; ++i)
{
if (ret[i] == '\n')
{
break;
}
else if (ret[i] == '\0')
{
ret[i] = '\n';
ret[i + 1] = '\0';
break;
}
}
}
</code></pre>
<p>EDIT: I appreciate all the helpful tips I'm seeing here. I would like to remind folks that I'm still a n00b with C, and specifically haven't gotten up to pointers yet. (Remember the bit about Ch.1 of K&R -- Ch.1 doesn't do pointers.) I "kinda" get some of those solutions, but they're still a touch advanced for where I'm at ... </p>
<p>And most of what I'm looking for is the trim method itself -- specifically the fact that I'm looping through <strong>3</strong> times (which feels so dirty). I feel like if I were just a touch more clever (even without the advanced knowledge of C), this could have been cleaner.</p>
|
<p>There is no reason to have two buffers, you can trim the input line in place</p>
<pre><code>int trim(char line[])
{
int len = 0;
for (len = 0; line[len] != 0; ++len)
;
while (len > 0 &&
line[len-1] == ' ' && line[len-1] == '\t' && line[len-1] == '\n')
line[--len] = 0;
return len;
}
</code></pre>
<p>By returning the line length, you can eliminate blank lines by testing for non-zero length lines</p>
<pre><code>if (trim(line) != 0)
printf("%s\n", line);
</code></pre>
<p>EDIT: You can make the while loop even simpler, assuming ASCII encoding.</p>
<pre><code>while (len > 0 && line[len-1] <= ' ')
line[--len] = 0;
</code></pre>
|
<p>First of all:</p>
<blockquote>
<p>int main(void)</p>
</blockquote>
<p>You know the parameters to main(). They're nothing. (Or argc&argv, but I don't think that's Chapter 1 material.)</p>
<p>Stylewise, you might want to try K&R-style brackets. They're much easier on the vertical space:</p>
<pre><code>void trim(char line[], char ret[])
{
int i = 0;
while ((ret[i] = line[i]) != '\0')
++i;
if (i == 1) { // Special case to remove entirely blank line
ret[0] = '\0';
return;
}
for (; i>=0; --i) { //continue backwards from the end of the line
if ((ret[i] == ' ') || (ret[i] == '\t')) //remove trailing whitespace
ret[i] = '\0';
else if ((ret[i] != '\0') && (ret[i] != '\r') && (ret[i] != '\n')) //...until we hit a word character
break;
}
for (i=0; i<MAXLINE-1; ++i) { //-1 because we might need to add a character to the line
if (ret[i] == '\n') //break on newline
break;
if (ret[i] == '\0') { //line doesn't have a \n -- add it
ret[i] = '\n';
ret[i+1] = '\0';
break;
}
}
}
</code></pre>
<p>(Also added comments and fixed one bug.)</p>
<p>A big issue is the usage of the MAXLINE constant -- main() exclusively uses it for the <em>line</em> and <em>out</em> variables; trim(), which is only working on them doesn't need to use the constant. You should pass the size(s) as a parameter just like you did in getline().</p>
| 19,574
|
<p>Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller. </p>
<p>I bind some <code>onclick</code> events to a button, but I find that they sometimes execute in an order I did not expect. </p>
<p>Is there a way to ensure order, or how have you handled this problem in the past?</p>
|
<p>If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.</p>
<pre><code>$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff now that #mydiv has been manipulated
return;
});
</code></pre>
<p>Something like that at least.</p>
|
<p>JQuery 1.5 introduces promises, and here's the simplest implementation I've seen to control order of execution. Full documentation at <a href="http://api.jquery.com/jquery.when/" rel="nofollow">http://api.jquery.com/jquery.when/</a></p>
<pre><code>$.when( $('#myDiv').css('background-color', 'red') )
.then( alert('hi!') )
.then( myClickFunction( $('#myID') ) )
.then( myThingToRunAfterClick() );
</code></pre>
| 36,993
|
<p>I have read the post <a href="http://www.julienlecomte.net/blog/2007/10/28/" rel="noreferrer">here</a> about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "please wait" animated GIF freezes while the local JavaScript is processing. Thanks!</p>
<pre><code>function appendToSelect() {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
for (var i = 1; i < obj.data.length; i++) {
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}
}
</code></pre>
|
<p>Here is a solution:</p>
<pre><code>function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="'+obj.data[0].value+'">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0, 1); // we only want remaining data
var appendOptions = function() {
var dataChunk = obj.data.splice(0, 10); // configure this last number (the size of the 'chunk') to suit your needs
for(var i = 0; i < dataChunk.length; i++) {
$("#mySelect").append(
'<option value="' + dataChunk[i].value + '">'
+ dataChunk[i].name
+ '</option>'
);
}
if(obj.data.length > 0) {
setTimeout(appendOptions, 100); // change time to suit needs
}
};
appendOptions(); // kicks it off
}
</code></pre>
<p>Not as elegant as <a href="https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968">@Borgar's</a> solution, but you get the idea. Basically, I am doing the same thing, but all in your one function rather than breaking it into a higher-order function like he does. I like his solution, but if you don't, perhaps this will work for you.</p>
<hr>
<p>EDIT: For those that don't immediately see it, one of the main differences between this solution and <a href="https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968">@Borgar's</a> is that this solution allows you to set the size of the 'chunks' of data that is processed between each timeout. <a href="https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968">@Borgar's</a> times-out after <em>every single member</em> of the array is processed. If I get time, I will try to create a higher-order function to handle this so it is more elegant. No promises though! ;)</p>
<hr>
<p>EDIT: So, here is my adaptation of <a href="https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968">@Borgar's</a> solution, which allows for setting a 'chunk' size and configuring the timeout value more easily:</p>
<pre><code>function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {
var itemIndex = 0;
(function() {
var remainingDataLength = (data.length - itemIndex);
var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;
if(itemIndex < data.length) {
while(currentChunkSize--) {
workerCallback(data[itemIndex++]);
}
setTimeout(arguments.callee, timeout);
} else if(completionCallback) {
completionCallback();
}
})();
}
function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0,1); // we only want remaining data
incrementallyProcess(function(data) {
$("#mySelect").append(
'<option value="' + data.value + '">'
+ data.name
+ '</option>'
);
}, obj.data, 10, 100, removeAnimatedGifFunction); // last function not required...
}
</code></pre>
<p>Hope that helps - I think this combines the best of both solutions. <strong>Notice</strong>, the second anonymous function no longer uses the index value, but simply passes in the entire object (with the value and name properties); that makes it a bit cleaner, since the index of the current object really isn't <em>usually</em> that useful when iterating over things, IMO.</p>
<p>I am sure there are still things that could be done to make this even better, but that is left as an exercise for the reader. ;)</p>
|
<p>You would need to rewrite the function to cache the element list, then loop over the list using a counter of some sort.</p>
<p>Then when the counter reaches counter % max_num_before_wait == 0, call timeout back to the function itself.</p>
<p>Make sure to clear the cache and counter at the end of the complete list, or use a secondary function with an extra count parameter.</p>
| 25,886
|
<p>I have a .NET assembly which I have exposed to COM via a tlb file, and an installer which registers the tlb. I have manually checked that the installer works correctly and that COM clients can access the library. So far, so good...</p>
<p>However, I am trying to put together some automated system tests which check that the installer is working correctly. As part of that I have automated the installation on a VM, and I now want to make some calls to the installed COM library to verify that it is working correctly. I originally thought about writing some tests in VB6, but I already have a large suite of tests written in C#, which reference the .NET assembly. I was hoping that I could change these to reference the .tlb, but I get an error when I try this within VS2008:</p>
<p>The ActiveX type library 'blah.tlb' was exported from a .NET assembly and cannot be added as a reference.</p>
<p>Is there any way I can fool VS2008 into allowing me to add this reference, perhaps by editing the tlb file? </p>
<p>Googling hasn't come up with any solutions. All I've found is a Microsoft Connect article stating that this is "By Design": <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120882" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120882</a></p>
|
<p>The Closest I've gotten to a solution is something like the following:</p>
<pre><code>using System;
class ComClass
{
public bool CallFunction(arg1, arg2)
{
Type ComType;
object ComObject;
ComType = Type.GetTypeFromProgID("Registered.ComClass");
// Create an instance of your COM Registered Object.
ComObject = Activator.CreateInstance(ComType);
object[] args = new object[2];
args[0] = arg1;
args[1] = arg2;
// Call the Method and cast return to whatever it should be.
return (bool)ComType.InvokeMember("MethodToCall", BindingFlags.InvokeMethod, null, ComObject, args))
}
}
</code></pre>
<p>It's not very pretty, but I think gets the point across. You could of course put the ComObject instantiation into a constructor and wrap the rest of the calls to the object, but probably not necessary for test code. </p>
|
<p>Using <a href="http://msdn.microsoft.com/en-us/library/tt0cf3sx(VS.80).aspx" rel="nofollow noreferrer">tlbimp.exe</a> you can generate an assembly from your COM component that can be used in .NET code</p>
| 48,037
|
<p>I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using:</p>
<pre><code>SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
</code></pre>
|
<pre><code>WHERE
DateDiff(d, Received, GETDATE()) = 0
</code></pre>
<p>Edit: As lined out in the comments to this answer, that's not an ideal solution. Check the other answers in this thread, too. </p>
|
<p>that's pretty much the best way to do it.
you could put the DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0) and DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1) into variables and use those instead but i don't think that this will improve performance.</p>
| 42,212
|
<p>How do I make an MD5 hash of a string with Delphi?</p>
|
<p>If you want an MD5 digest and have the <a href="http://www.indyproject.org" rel="nofollow noreferrer">Indy</a> components installed, you can do this:</p>
<pre><code>uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;
with TIdHashMessageDigest5.Create do
try
Result := TIdHash128.AsHex(HashValue('Hello, world'));
finally
Free;
end;
</code></pre>
<p>Most popular algorithms are supported in the <a href="http://www.cityinthesky.co.uk/opensource/dcpcrypt/" rel="nofollow noreferrer">Delphi Cryptography Package</a>:</p>
<ul>
<li>Haval</li>
<li>MD4, MD5</li>
<li>RipeMD-128, RipeMD-160</li>
<li>SHA-1, SHA-256, SHA-384, SHA-512,</li>
<li>Tiger</li>
</ul>
<p><strong>Update</strong>
<code>DCPCrypt</code> is now maintained by <a href="https://stackoverflow.com/users/84704/warren-p">Warren Postma</a> and source can be found <a href="https://bitbucket.org/wpostma/dcpcrypt2010" rel="nofollow noreferrer">here</a>.</p>
|
<p>Using ICS, you simply call StrMD5 function which is located in OverbytecsMD5 unit.</p>
<p>Beside that specific function, there are a lot more MD5 function for other datatypes and scenarios. There are also other hash methods such as SHA.</p>
| 8,302
|
<p>I have a COM interop assembly, and I would like to check from a .NET application whether the component I'm about to create is installed on the machine. </p>
<p>I would like to provide a nice error message if it is not installed.</p>
<p>Put the instantiation into try-catch is not a good solution for me, as I would like to distingwish between the missing installation and the other errors that may occur. </p>
<p>My idea is to check whether the node with the COM class id exists in the registry under the <em>HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface</em> path. But is there a better approach?</p>
|
<p>I think the best way, unfortunately, is to try and instantiate it. Checking in the registry does not guarantee that the component is actually there at all (e.g. the file may have been deleted or moved post registration).</p>
|
<p>You might also instantiate an object of the com class you want to check in a try/catch block so as to warn your user in the catch block. Blunt solution, I agree.</p>
<p>Checking the registry seems the most reasonable approach to me, as an unregistered com component is pretty useless.</p>
| 38,233
|
<p>Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a <code>using</code> block, or omit the proper Dispose call in a <code>finally</code> block?</p>
|
<p>Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal. </p>
<p>That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.</p>
|
<p>You could design a small add-in to R# that you could have run inside the code editor that scans the code and updates the code analysis to reflect that you an object who's missing the structure you've just described. </p>
<p>I'd look into the R# plugin architecture if you decide to go that route.</p>
| 12,713
|
<p>Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates?</p>
<p>Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "_$PropertyName$ where the first character is made lowercase.</p>
<p>I can't afford R#. Please help :)</p>
|
<p>Unfortunately there seems to be no way. Snippets offer amazingly limited support for <a href="http://msdn.microsoft.com/en-us/library/ms242312(VS.80).aspx" rel="noreferrer">transformation functions</a> as you can see.</p>
<p>You have to stick with the VS standard solution, which is to write two literals: one for the property name, and the other for the member variable name.</p>
|
<p>a "fix" may be to use a prefix in the naming or the member variable, i.e.:</p>
<pre><code>string m_$name$;
string $name$
{
get{return m_$name$;}
set{m_$name$=value;}
};
</code></pre>
| 19,904
|
<p>I need to understand a good way to design a web page with dynamically updated graphs. It should be something close to what stock market graphs look like (e.g. <a href="http://finance.google.com/finance?q=NASDAQ%3AGOOG" rel="nofollow noreferrer">Google Finance</a>), although with a bit more complicated functionality, which is not the point. Naturally I am thinking of writing an ajaxy-style flash control, which would communicate with the server through, okay, something like XMLHttpRequest, but from within flash code, and draw things basing on data received. Is this doable with flash? Does security model allow such kind of client-server interaction? If yes, could you think of any references for me to get started (similar opensource projects, articles, whatever)? Or should I forget about flash and use a Java applet right away?</p>
<p>An important thing to note: I don't think I can use Google charting API, because I need also to have user interaction. In the link above to Google Finance the user can drag the graph to and forth with the mouse, that's close to what I need (I will also need to implement some actions from the dropdown menu).</p>
<p>Thanks for your answers and opinions!</p>
|
<p>I have used the <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">Google Charts API</a> to do this sort of thing. For a simple example, see my <a href="http://hewgill.com/sunriseset/" rel="nofollow noreferrer">Sunrise and Sunset</a> page. This page calculates sunrise and sunset times for a given latitude and longitude, all in Javascript, then uses the Google Chart API to replace the graph on the page with the requested data.</p>
<p><strong>Update</strong>: The Stack Overflow reputation graph (see your user page) isn't Flash and yet allows interactive dragging. (Click and drag on the left to update the posts on the right that reflect the highlighted reputation region.) Perhaps you could look at how that is implemented.</p>
|
<p>I'm not sure about the Flash side of things, but this would be pretty simple to do in Silverlight. I am pretty sure you'd easily be able to make a server request in Flash too.</p>
<p>I'd do some searching for long polling.</p>
| 40,887
|
<p>I have an web application using asp.net 2.0 and vb.net I wrote a bat file to use GPG to encryt a file and call it whithin asp.net shell(pathname & filename).
when I double click on the bat file from cmd windows it works fine but when I call it in the application everything command that I pass is executed perfectly except the gpg command. I make sure the user under which the application is running as all rights and privileges to run the commands I import, trust and verify all the keys and in fact the bat file works fine when double click on it but why it did successfully execute the GPG function. It did not return any error just did not encrypt any file</p>
<p>gpg -e --always-trust -r <> Filename</p>
<p>any help will be appreciated.</p>
<p>Thank you!</p>
|
<p>I had a similar problem:</p>
<p><a href="https://stackoverflow.com/questions/34183/cnet-why-is-my-processstart-hanging">C#.Net: Why is my Process.Start() hanging?</a></p>
<p>It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:</p>
<p><a href="http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx" rel="nofollow noreferrer">http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx</a></p>
|
<p>Not sure how you are using 'shell()' but <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx?ppud=4" rel="nofollow noreferrer">Process.Start</a> is the way to go.</p>
| 18,762
|
<p>Under FreeCAD, I sketched on the face of a solid as follows :</p>
<p><a href="https://i.stack.imgur.com/Qe4nu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qe4nu.png" alt="sketch"></a></p>
<p>My problem is, when I use "Pad a selected sketch", the solid created comprises also the original solid.</p>
<p><a href="https://i.stack.imgur.com/pHI59.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHI59.png" alt="created solid"></a></p>
<p>It prevents me, for instance, to get the difference with the first one.</p>
<p>Any idea what may be causing this? How to prevent it?</p>
<p>MyFreeCAD config:</p>
<pre><code>OS: Ubuntu 16.04.1 LTS
Word size of OS: 64-bit
Word size of FreeCAD: 64-bit
Version: 0.15.4671 (Git)
Branch: releases/FreeCAD-0-15
Hash: 244b3aef360841646cbfe80a1b225c8b39c8380c
Python version: 2.7.11
Qt version: 4.8.7
Coin version: 4.0.0a
OCC version: 6.8.0.oce-0.17
</code></pre>
|
<p>Ok, I got help on <a href="http://forum.freecadweb.org/viewtopic.php?f=3&t=19756" rel="nofollow noreferrer">this forum thread</a></p>
<p>Using <code>Part Extrude</code> instead of <code>Pad a selected sketch</code> on the sketch will create an independent solid.</p>
<p>It also turns out that, instead of creating the second solid to do a boolean difference, the good way to "cut" my solid is using the <code>PartDesign Pocket</code> tool.</p>
|
<p>If you just select the face, and pad the face (versus padding the solid), you should not have this problem. </p>
| 483
|
<p>I have spent a long time searching for a product that would bring functionality similar to matplotlib to the .NET framework. From what I can tell, nothing really measures up. Is this an accurate assessment? Here is what I have found:</p>
<p>Commercial:</p>
<ul>
<li>ChartFX</li>
<li>Dundas</li>
<li>KitWare's ActiViz (basically a managed version of VTK)</li>
</ul>
<p>Open Source:</p>
<ul>
<li>NPlot</li>
<li>Various projects on CodePlex, notably VSLab</li>
</ul>
<p>I think it would be tremendously valuable to have a .NET project which provided the ability to interactively plot data from languages like F# and IronPython. Does anyone know of such a project?</p>
|
<p>You could also look at <a href="http://www.ffconsultancy.com/products/fsharp_for_visualization/index.html" rel="noreferrer">F# for Visualization</a>, I've got the beta and it's quite good for some basic stuff - not (yet) so good if you want more control over the presentation.</p>
<p>Another possibility (which I haven't tried at all yet, but I intend to soon) is <a href="http://www.microsoft.com/downloads/details.aspx?familyid=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en" rel="noreferrer">Microsoft Chart Controls</a> (previously known as Dundas...), which have been released independently of SQL Server. There's an article <a href="http://thevalerios.net/matt/2008/11/using-the-microsoft-charting-library-from-f/" rel="noreferrer">here</a> about using them from F# - as you will see from the example code, you have more control over presentation, but it comes at a price...</p>
<p><strong>UPDATE</strong> I did end up trying the Microsoft Chart Controls, and to be honest, it blows F# for Visualization out of the water (sorry Jon!). However, Luca Bolognese has gone a step further and made a <a href="http://lucabolognese.wordpress.com/2010/02/17/lchart-displaying-charts-in-f-part-ii/" rel="noreferrer">very usable wrapper</a>. The paint is still wet, but it's definitely worth a try.</p>
|
<p>At <a href="http://www.resolversystems.com" rel="nofollow noreferrer">Resolver Systems</a> we're working on a project called <a href="http://code.google.com/p/ironclad" rel="nofollow noreferrer">Ironclad</a>, which will eventually (hopefully) allow you to use cPython extensions like matplotlib and numpy transparently from IronPython.</p>
<p>At the moment we're focusing on numpy (large parts of it are usable now), but matplotlib and friends are also high on the list.</p>
<p>It's an open-source project, and we could do with help. You should have a look at whether it could be useful.</p>
| 40,735
|
<p>The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?</p>
|
<p>Does it have to be an Image Web Part? If not I would simply use a <a href="http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx" rel="noreferrer">Content Editor Web Part</a> and paste the required HTML there.</p>
<pre><code><a href="http://www.google.com"><img src="urlToImage" /></a>
</code></pre>
|
<p>what if it have to?
users need to have an opportunity to change the link and the image themselves and not to disturb an administrator.</p>
| 14,484
|
<p>I need to match and remove all tags using a regular expression in Perl. I have the following:</p>
<pre><code><\\??(?!p).+?>
</code></pre>
<p>But this still matches with the closing <code></p></code> tag. Any hint on how to match with the closing tag as well?</p>
<p>Note, this is being performed on xhtml.</p>
|
<p>I came up with this:</p>
<pre><code><(?!\/?p(?=>|\s.*>))\/?.*?>
x/
< # Match open angle bracket
(?! # Negative lookahead (Not matching and not consuming)
\/? # 0 or 1 /
p # p
(?= # Positive lookahead (Matching and not consuming)
> # > - No attributes
| # or
\s # whitespace
.* # anything up to
> # close angle brackets - with attributes
) # close positive lookahead
) # close negative lookahead
# if we have got this far then we don't match
# a p tag or closing p tag
# with or without attributes
\/? # optional close tag symbol (/)
.*? # and anything up to
> # first closing tag
/
</code></pre>
<p>This will now deal with p tags with or without attributes and the closing p tags, but will match pre and similar tags, with or without attributes.</p>
<p>It doesn't strip out attributes, but my source data does not put them in. I may change this later to do this, but this will suffice for now.</p>
|
<p>You should probably also remove any attributes on the <p> tag, since someone bad could do something like:</p>
<pre><code><p onclick="document.location.href='http://www.evil.com'">Clickable text</p>
</code></pre>
<p>The easiest way to do this, is to use the regex people suggest here to search for &ltp> tags with attributes, and replace them with <p> tags without attributes. Just to be on the safe side.</p>
| 4,970
|
<p>I'm using Windows XP and I want to know if the local area is available or not?</p>
<p>And if I'm using another OS would that affect on my code?</p>
|
<p>Use the following code</p>
<pre><code>using System.Net.NetworkInformation; //(Add reference of System.Net.dll)
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if(e.IsAvailable)
{
//connected
}
else
{
//disconnected
}
}
}
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/325872/detect-an-internet-connection-activation-with-delphi">Here's how to do it in Delphi.</a></p>
| 47,651
|
<p>If I target the x86 platform for my .NET app, will it run properly on AMD chips? I know that it will work with Intel chips, and that Vista 64 has the ability to run x86 apps in a special mode, but I don't know how much of that is hardware and how much of that is the OS. </p>
<p>I've tested it on Vista 64 with an Intel chip and it works perfectly, but I don't have an AMD machine to test. </p>
|
<p>Yes - they are binary compatible, otherwise they wouldn't be drop-in replacements for each other :)</p>
<p>Unless you mean IA64 vs AMD64 - those are incompatible architectures.</p>
|
<p>It will work fine</p>
| 40,736
|
<p>I don't like paper documents. I like everything stored on a server. I'd like to avoid printing, signing, and scanning, if possible.</p>
<p><b>How do I get signatures from people to sign-off on forms and still keep it digital?</b></p>
<p>The purpose of signing is to prove that certain departments have OK'd the document. Most of these people are non-technical.</p>
<p>The ideal is that each person would open the document and type in their name and close the document. The problem is that how do I know that Fred didn't sign for Ralph.</p>
|
<p>There are myriad approaches discussed in Schneier's <em>Applied Cryptography</em>.</p>
<p>Much of what you're looking for comes down to a Digital Signature Algorithm (DSA) - of which NIST has one, asymetric encryption algorithms can provide, etc.</p>
<p>The simple route would be to collect delivery and read receipts on email, but that's not fool-proof.</p>
|
<p>Having been searching for a system to this, I've just found docshaker.com on killerstartups. It pretty much allow you to do as you've just described Neall.</p>
| 22,210
|
<p>I am searching for a way to compress JavaScript code for the iPhone. Is there a way to avoid using a lot of CPU time on the small and rather slow device?</p>
|
<p>Use <a href="http://www.crockford.com/javascript/jsmin.html" rel="nofollow noreferrer">JSMin</a> and avoid <a href="http://dean.edwards.name/packer/" rel="nofollow noreferrer">packer</a> which is really more CPU consuming and slower to "deflate"</p>
|
<p>Making sure your webserver properly serves stuff gzipped/deflated when the client supports it is usually more effective than minifying the program code itself. Of course, using both tends to give even smaller sizes.</p>
| 14,017
|
<p>Does visual studio 2008 support classic asp development?</p>
<p>It's been years since I created a classic ASP website and I was wondering if I can use my current toolset or if I have to resign myself to notepad.</p>
<p>Thanks</p>
<p>Matt</p>
|
<p>I know VS 2008 now includes Intellisense and Debugging feature for classic ASP, so thats make me think Yes.</p>
<p>Be sure you get the Service Pack 1 version.</p>
|
<p>This is a good reference for setting up a classic ASP site in Visual Studio 2008:</p>
<p><a href="http://www.codeproject.com/KB/debug/DebugVBScriptVS2008.aspx" rel="nofollow">http://www.codeproject.com/KB/debug/DebugVBScriptVS2008.aspx</a></p>
<p>Additionally, I had to give "Everyone" access to the Virtual Directory in IIS that I setup in my local machine for it to run correctly:</p>
<p><a href="http://answers.google.com/answers/threadview?id=181211" rel="nofollow">http://answers.google.com/answers/threadview?id=181211</a></p>
| 29,779
|
<p>Is there a way to check to see if a date/time is valid you would think these would be easy to check:</p>
<pre><code>$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;
if(strtotime($dateTime)) {
// why is this valid?
}
</code></pre>
<p>what really gets me is this:</p>
<pre><code>echo date('Y-m-d', strtotime($date));
</code></pre>
<p>results in: "1999-11-30",</p>
<p>huh? i went from 0000-00-00 to 1999-11-30 ???</p>
<p>I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?</p>
<p>Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux</p>
|
<p>From <a href="http://php.net/manual/en/function.checkdate.php#78362" rel="noreferrer">php.net</a></p>
<pre><code><?php
function isValidDateTime($dateTime)
{
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
?>
</code></pre>
|
<pre><code><?php
function is_date( $str ) {
$stamp = strtotime( $str );
if (!is_numeric($stamp)) {
return FALSE;
}
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year)) {
return TRUE;
}
return FALSE;
}
?>
</code></pre>
| 17,071
|
<p>In Eclipse 3.3.2, I would like to replace a character (say ',') by a new line in a file.
What should I write in the "Replace with" box in order to do so ?</p>
<p>EDIT : Many answers seems to be for Eclipse 3.4. Is there a solution for Eclipse 3.3.X ?</p>
|
<p>Check box 'Regular Expressions' and use '\R' in the 'Replace with' box</p>
<p>It's a new feature introduced with Eclipse 3.4, See <a href="http://download.eclipse.org/eclipse/downloads/drops/R-3.4-200806172000/whatsnew3.4/eclipse-news-part1.html" rel="noreferrer">What's New in 3.4</a></p>
|
<p>I've just found <a href="http://www.andyjarrett.co.uk/2006/11/02/eclipse-regex-and-newline-bug/" rel="nofollow noreferrer">an article about that problem</a>. It seems to be a bug.</p>
<p>There's a workaround which is to copy a new line in clipboard and then paste it inside the "replace" box.</p>
| 18,961
|
<p>Our usage case is a database responsible for accounts, sessions, licenses, etc. — it needs to be polled upon client startup, so high reliability is crucial. As such, we'd like to replicate across different servers in physically separate networks, just in case an entire datacenter happens to go down. I have successfully set up a push subscription to another server in the same network, so this generally works. It's the connection to servers <em>outside</em> the network that I need to get working now.</p>
<p>Replication doesn't work directly across networks. Microsoft <a href="http://msdn.microsoft.com/en-us/library/ms151319(SQL.90).aspx" rel="noreferrer">suggests either a VPN or web replication</a>. The latter strikes me as inefficient (and they do say "Note: Web synchronization is designed for synchronizing data with portable computers, handheld devices, and other clients. Web synchronization is not intended for high-volume server-to-server applications.")</p>
<p>The former, a VPN, would work, but I still consider it a needlessly complex solution (not to mention the added potential for security issues) to continuously run a VPN connection. <strong>I'd much rather just run an SSH tunnel.</strong> Yet, I can't find any article that explains how to do this and isn't about MySQL.</p>
<p>I've got an SSH server set up on the subscriber, and have used PuTTY to establish a tunnel from <code><publisher>:1434</code> to <code><subscriber>:1433</code>. I cannot, however, get SQL Server Management Studio to connect this way (I'm not sure it supports the <code>:</code> port syntax). I've also set up an alias on <code><publisher></code>'s SQL Server Configuration Manager, with <code>@@servername</code> of <code><subscriber></code>, pointing to <code>localhost:1434</code>. Connecting to that doesn't appear to work either.</p>
<p>I used the push subscription option, so I figure the publisher needs to connect to the subscriber, not the other way 'round.</p>
<p>Both servers use the default instance, and run SQL Server 2005 SP 2 on Windows Server 2003 SP 2. The SSH server on the subscriber is freeSSHd 1.2.1.</p>
<p>Is this possible at all? Is there another way I can leverage SSH to pretend the machine exists within the same network? Or do I have to go with a VPN?</p>
|
<p>When you talk about different locations for the servers, does it also mean different domains? Your comment on web replication is true, but applies only to the daily changes made to the database. Your initial snapshot can be of any size, even if it is a huge database. If your daily updates are limited (a few 1000's seems ok to me), go for it. It is quick!</p>
<p>EDIT: </p>
<p>There is a major domain/security issue when you begin to think about exchanging data between servers. If you need to connect servers belonging to different domains through a VPN or any dedicated link, and if you don't want to go through SQL Security (avoid it!), you will face specific (and licensing!) issues related to domain trust. One of the smart sides of Web replication is to avoid this kind of issue (and extra cost) by securing the connection through https protocol.</p>
|
<p>I know this is an old post but hopefully this helps: SQL Server Management Studio uses a comma to separate the host from the port. </p>
<p><a href="https://stackoverflow.com/questions/89576/how-do-you-specify-a-different-port-number-in-sql-management-studio">How do you specify a different port number in SQL Management Studio?</a></p>
| 29,238
|
<p>I'm relatively new to the Windows Server world (coming from *nix land). I'm used to analyzing a web-server's configuration by grepping through an apache config file. </p>
<p>Is there an equivalent file/group-of-files for IIS? Lacking that, is there an official scripting interface for IIS?</p>
|
<p>PowerShell would be the way to go.</p>
<p>Here are some stack overflow posts:</p>
<p><a href="https://stackoverflow.com/questions/tagged/powershell+iis6">https://stackoverflow.com/questions/tagged/powershell+iis6</a></p>
<p>Also, googling <strong>powershell IIS</strong> will get you started.</p>
|
<p>Default scripting tool in IIS is the ADSUTIL.VBS script in the \InetPubs\Scripts directory. </p>
<p><a href="http://technet.microsoft.com/en-us/library/cc781546.aspx" rel="nofollow noreferrer">Using the Adsutil.vbs Administration Script</a></p>
<p>You can pretty much do anything to the IIS metabase with that tool.</p>
| 44,903
|
<p>JSF is setting the ID of an input field to <code>search_form:expression</code>. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?</p>
<pre><code>input#search_form:expression {
///...
}
</code></pre>
|
<p>Backslash: </p>
<pre><code>input#search_form\:expression { ///...}
</code></pre>
<ul>
<li>See also <em><a href="http://msdn.microsoft.com/en-us/library/ms762307(VS.85).aspx" rel="noreferrer">Using Namespaces with CSS</a></em> (MSDN)</li>
</ul>
|
<p>I found only this format worked for me for IE7 (Firefox too), and I use JSF/Icefaces 1.8.2.</p>
<pre>
Say form id=FFF, element id=EEE
var jq=jQuery.noConflict();
jq(document).ready(function() {
jq("[id=FFF:EEE]").someJQueryLibFunction({ jQuery lib function options go here })
});
</pre>
| 14,864
|
<p>I have a dev branch that hasn't been touched for a while. I merged the trunk into it to integrate many fixes/changes in the main line since it was branched out, but now I have many small conflicts (merge-left/merge-right).</p>
<p>I want the latest trunk revision to be used to resolve each conflict. Is there a command I can run that will resolve all conflicts under a working copy in one direction automatically (merge-right should be used for all conflicts)?</p>
<p>EDIT:
As indicated in the comments, I tried reverting and then running svn merge with the --accept option, only apparently there is no such option in SVN 1.0. Still looking for a solution.</p>
|
<p>I think you can use the "--accept theirs-full" option when you issue the svn merge command.
That should do what you want...</p>
|
<p>I think TSVN could do this if you do a "Check for modifications", which will show you all the files including the conflicted ones, select them all, and then choose 'resolve using theirs'. </p>
<p>Not sure if TSVN is relevant for your platform, or it that's actually exactly what you want to to do, but it might be helpful...</p>
| 42,592
|
<p>I have the following <code>before_filter</code>:</p>
<pre><code> def find_current_membership
respond_to do |wants|
wants.html { @current_membership = @group.memberships.for(@current_user) }
wants.rss {}
wants.js { @current_membership = @group.memberships.for(@current_user) }
end
end
</code></pre>
<p>I would like to share the code for the HTML and JS blocks. Is there a better way than just throwing the code into a method? I was hoping this would work:</p>
<pre><code> def find_current_membership
respond_to do |wants|
wants.rss {}
wants.all { @current_membership = @group.memberships.for(@current_user) }
end
end
</code></pre>
<p>But alas, it did not.</p>
|
<p>If I'm reading this right, it looks like <code>find_current_membership</code> is your <code>before_filter</code> method, is that right? eg:</p>
<pre><code>class SomeController < ApplicationController
before_filter :find_current_membership
...
</code></pre>
<p>I think it's a bit non-standard to use <code>respond_to</code> inside a <code>before_filter</code>, they are meant to just do something and render on failure. It seems to me like you want something more like this</p>
<pre><code> class SomeController < ApplicationController
before_filter :find_current_membership
def some_action
# stuff, or maybe nothing
end
private
def find_current_membership
@current_membership = @group.memberships.for(@current_user) unless request.format.rss?
end
end
</code></pre>
|
<p>How about this simple solution!?</p>
<pre><code>def find_current_membership
@current_membership = @group.memberships.for(@current_user)
respond_to do |wants|
wants.html
wants.rss {}
wants.js
end
end
</code></pre>
| 30,357
|
<p>I have a question regarding a symptom of my misuse of CreateProcess. I'm using the lpcommandline parameter to feed the path to my executable and parameters. My misuse is that I have not surrounded the path to the exe with quotes. </p>
<p>My question is, why does the CreateProcess work just fine on most computers and not others? I know that the path will have a space in most of the time, yet on 90% of XP machines it works. I of course found out my issue on those 10% where it did not. But I'm wondering what is different on the machines where it does not work? Is there a setting or a policy that any of you folks know about. And yes, I am going to fix the quote issue. Just curious about why something like this would not have just failed off the bat. </p>
<p>So the code would look something like below and the szCommandLine Parameter would be something like below. Notice no quotes around the path to the exe.</p>
<p>"C:\Program Files\My Company\doit.exe parameter1 parameter2"</p>
<pre><code>CreateProcess(
NULL,
szCommandLine,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&pi )
</code></pre>
|
<p>As the document Martin York linked to hinted, CreateProcess() has some behaviour for back-compat with pre-long-name programs.</p>
<p>"c:\program files\sub dir\program name arg1 arg2" will look for:</p>
<blockquote>
<pre><code>"c:\program.exe" files\sub dir\program name arg1 arg2
"c:\program files\sub.exe" dir\program name arg1 arg2
"c:\program files\sub dir\program.exe" name arg1 arg2
"c:\program files\sub dir\program name.exe" arg1 arg2
</code></pre>
</blockquote>
<p>So if any of these files exist, Windows will to call them, not your program. Also, I would assume if you did not have read access to any of the folders these possible matches are in, CreateProcess() may fail out immediatly, instead of checking if you have read to the later possible matches. (Windows by default checks read access only the final folder.)</p>
|
<p>A good way to diagnose something like that is to build in to your application error and reporting mechanism. This helps for so many purposes- mainly for bugs that you may never see yourself and which some users may just ignore and not report to you. This way you can diagnose what these parameters were when the command was called and the failure occurred.</p>
<p>Additionally, you can try exploring further the MSDN site and the advanced features associated with this method. You left most of them NULL. By exploring these extended features you will learn and maybe able to find out yourself why there may be that discrepency.</p>
<p>Another generic answer but I hope this helps you to evaluate your particular situation.</p>
| 33,305
|
<p>Typically in a large network a computer needs to operate behind an authenticated proxy - any connections to the outside world require a username/password which is often the password a user uses to log into email, workstation etc.</p>
<p>This means having to put the network password in the <code>apt.conf</code> file as well as typically the <code>http_proxy, ftp_proxy</code> and <code>https_proxy</code> environment variables defined in <code>~/.profile</code></p>
<p>I realise that with <code>apt.conf</code> that you could set <code>chmod 600</code> (which it isn't by default on Ubuntu/Debian!) but on our system there are people who need root priveleges .</p>
<p>I also realise that it is technically impossible to secure a password from someone who has root access, however I was wondering if there was a way of <i>obscuring</i> the password to prevent accidental discovery. Windows operates with users as admins yet somehow stores network passwords (probably stored deep in the registry obscured in some way) so that in typical use you won't stumble across it in plain text</p>
<p>I only ask since the other day, I entirely by accident discovered somebody elses password in this way when comparing configuration files across systems.</p>
<p>@monjardin - Public key authentication is not an alternative on this network I'm afraid. Plus I doubt it is supported amongst the majority of commandline tools.</p>
<p>@Neall - I don't mind the other users having web access, they can use my credentials to access the web, I just don't want them to happen across my password in plain text.</p>
|
<p>With the following approach you never have to save your proxy password in plain text. You just have to type in a password interactively as soon as you need http/https/ftp access:</p>
<ul>
<li>Use openssl to encrypt your plain text proxy password into a file, with e.g. AES256 encryption:</li>
</ul>
<blockquote>
<p>openssl enc -aes-256-cbc -in pw.txt -out pw.bin</p>
</blockquote>
<ul>
<li>Use a (different) password for protecting the encoded file</li>
<li>Remove plain text pw.txt</li>
<li>Create an alias in e.g. ~/.alias to set your http_proxy/https_proxy/ftp_proxy environment variables (set appropriate values for $USER/proxy/$PORT)</li>
</ul>
<blockquote>
<p>alias myproxy='PW=`openssl aes-256-cbc -d -in pw.bin`; PROXY="http://$USER:$PW@proxy:$PORT"; export http_proxy=$PROXY; export https_proxy=$PROXY; export ftp_proxy=$PROXY'</p>
</blockquote>
<ul>
<li>you should source this file into your normal shell environment (on some systems this is done automatically)</li>
<li>type 'myproxy' and enter your openssl password you used for encrypting the file</li>
<li>done.</li>
</ul>
<p><strong>Note:</strong> the password is available (and readable) inside the users environment for the duration of the shell session. If you want to clean it from the environment after usage you can use another alias:</p>
<blockquote>
<p>alias clearproxy='export http_proxy=; export https_proxy=; export
ftp_proxy='</p>
</blockquote>
|
<p>Is public key authentication a valid alternative for you?</p>
| 3,945
|
<p>What algorithms and processes are involved in storing revision changes like stackoverflow and wikipedia do?</p>
<p>Is only one copy of the message kept? And if so is it only the latest copy? Then only changes to go back to the previous version(s) are stored from there? (This would make for a faster display of the main message).
Or are complete messages stored? And if so is the compare done between these on each display?</p>
<p>What algorithms are best used to determine the exact changes in the message? How is this data stored in a database?</p>
<p>If anyone knows exactly what wikipedia or stackoverlfow does I'd love to know.</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/Diff#Algorithm" rel="nofollow noreferrer">longest common substring algorithm</a> can be used to detect differences between versions, but it is limited. For example, it does not detect the moving around of text as such, but it would see this as unrelated removals and insertions.</p>
<p>I suppose that websites normally store the latest copy in full, and apply reverse diffs from there. This is also the way <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a> works, but <a href="http://en.wikipedia.org/wiki/Subversion_(software)" rel="nofollow noreferrer">Subversion</a> uses forward diffs, which results in slower checkouts.</p>
<p>To store this in a database, one could maintain a main table with the latest versions, and have a separate table with the reverse differences. This table would have rows in the format <code>(article_id, revision_id, differences)</code>.</p>
|
<p>Typical revision changes are stored using a delta algorithm, so the only data stored are the changes in each revision in relation to the original. I am unsure of wikipedia or stackoverflow how they have it implemented.</p>
| 10,557
|
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p>
<p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p>
<p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p>
<p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p>
<p>E.g., it should ideally be able to:</p>
<ul>
<li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li>
<li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li>
<li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li>
<li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li>
<li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li>
<li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li>
<li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li>
<li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li>
</ul>
<p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p>
<p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
|
<p>web2py does most of what you ask:</p>
<p>Based on a field type and its validators it will render the field with the appropriate widget. You can override with</p>
<pre><code>db.table.field.widget=...
</code></pre>
<p>and use a third party widget.</p>
<p>web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation.</p>
<p>There is <code>IS_EMPTY_OR(...)</code> validator.</p>
<p>The DAL prevents SQL injections since everthing is escaped when goes in the DB.</p>
<p>web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}}</p>
<p>Error messages are arguments of validators for example</p>
<pre><code>db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here'))
</code></pre>
<p>T is for internationalization.</p>
|
<p>I believe that Django models does not support composite primary keys (see <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields" rel="nofollow noreferrer">documentation</a>). But perhaps you can use SQLAlchemy in Django? A <a href="http://www.google.com/search?q=sqlalchemy+django" rel="nofollow noreferrer">google search</a> indicates that you can. I have not used Django, so I don't know.</p>
<p>I suggest you take a look at:</p>
<ul>
<li><a href="http://toscawidgets.org/" rel="nofollow noreferrer">ToscaWidgets</a></li>
<li><a href="http://code.google.com/p/dbsprockets/" rel="nofollow noreferrer">DBSprockets</a>, including <a href="http://code.google.com/p/dbsprockets/wiki/DBMechanic" rel="nofollow noreferrer">DBMechanic</a></li>
<li><a href="http://www.checkandshare.com/catwalk/" rel="nofollow noreferrer">Catwalk</a>. Catwalk is an application for TurboGears 1.0 that uses SQLObject, not SQLAlchemy. Also check out this <a href="http://www.checkandshare.com/blog/?p=41" rel="nofollow noreferrer">blog post</a> and <a href="http://www.checkandshare.com/CATWALK2/lview/index.html" rel="nofollow noreferrer">screencast</a>.</li>
<li><a href="http://docs.turbogears.org/1.0/DataController" rel="nofollow noreferrer">FastData</a>. Also uses SQLObject.</li>
<li><a href="http://code.google.com/p/formalchemy/" rel="nofollow noreferrer">formalchemy</a></li>
<li><a href="http://rumdemo.toscawidgets.org/" rel="nofollow noreferrer">Rum</a></li>
</ul>
<p>I do not have any deep knowledge of any of the projects above. I am just in the process of trying to add something similar to one of my own applications as what the original question mentions. The above list is simply a list of interesting projects that I have stumbled across.</p>
<p>As to web application frameworks for Python, I recommend TurboGears 2. Not that I have any experience with any of the other frameworks, I just like TurboGears...</p>
<p>If the original question's author finds a solution that works well, please update or answer this thread.</p>
| 6,498
|
<p>I'm sure there is a good (or at least decent) reason for this. What is it?</p>
|
<blockquote>
<p>I think this is a brilliant question -
and I think there is need of a better
answer.</p>
<p>Surely the only reason is that there
is something in a framework somewhere
that isn't very thread-safe. </p>
</blockquote>
<p>That "something" is almost every single instance member on every single control in System.Windows.Forms.</p>
<p>The MSDN documentation for many controls in System.Windows.Forms, if not all of them, say <em>"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."</em></p>
<p>This means that instance members such as <code>TextBox.Text {get; set;}</code> are not <strong><em>reentrant</em></strong>.</p>
<p>Making each of those instance members thread safe could introduce a lot of overhead that most applications do not need. Instead the designers of the .Net framework decided, and I think correctly, that the burden of synchronizing access to forms controls from multiple threads should be put on the programmer.</p>
<p>[Edit]</p>
<p>Although this question only asks "why" here is a link to an article that explains "how":</p>
<p><em>How to: Make Thread-Safe Calls to Windows Forms Controls</em> on MSDN</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms171728.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms171728.aspx</a></p>
|
<p>Hmm I'm not pretty sure but I think that when we have a progress controls like waiting bars, progress bars we can update their values from another thread and everything works great without any glitches. </p>
| 3,158
|
<p>I'd be leading a new project soon. And I've been pondering over what are the basic infrastructure for a software project. These are the stuff that I think every project should have:</p>
<p>-Coding style conventions</p>
<p>-Naming conventions</p>
<p>-Standard project directory structure(eg maven standard dir layout, etc)</p>
<p>-Project management and issue tracking(eg trac, redmine, etc)</p>
<p>-Continuous Integration server(eg, hudson, cruise control, etc)</p>
<p>I'm not sure if I missed out anything. Would anyone like to add?</p>
|
<p>As a preliminary answer, check out the Joel test:
<a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="noreferrer">http://www.joelonsoftware.com/articles/fog0000000043.html</a></p>
<p>Just an appetizer:</p>
<blockquote>
<ol>
<li>Do you use source control?</li>
<li>Can you make a build in one step?</li>
<li>Do you make daily builds?</li>
<li>Do you have a bug database?</li>
<li>Do you fix bugs before writing new code?</li>
<li>Do you have an up-to-date schedule?</li>
<li>Do you have a spec?</li>
<li>Do programmers have quiet working conditions?</li>
<li>Do you use the best tools money can buy?</li>
<li>Do you have testers?</li>
<li>Do new candidates write code during their interview?</li>
<li>Do you do hallway usability testing? </li>
</ol>
</blockquote>
|
<p>Knowledge management is crucial. As you already plan to use wiki (like Trac or <a href="http://www.redmine.org/" rel="nofollow noreferrer">Redmine</a>) you could use it for KM as well.</p>
| 11,642
|
<p>We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. </p>
<p>We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.</p>
<p>We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.</p>
<p>Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?</p>
|
<p>Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have </p>
<pre><code>string sRemove;
number nBuffer;
nBuffer = 256;
if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then
//do something
endif;
</code></pre>
<p>I get "undefined identifier". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning.</p>
<p>So the correct answer would be that you don't have to do anything for the code in the DefaultFeature_Installed event not to be called on uninstall.</p>
|
<p>There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is taking place. The Installed property will be true if the product is already there, so you can use it in a Boolean expression (Ex: Not Installed). The REMOVE property will be set to "ALL" if an uninstall is taking place. You might be able to condition your Firebird installation logic on these properties, which you can retrieve using the <a href="http://msdn.microsoft.com/en-us/library/aa370134(VS.85).aspx" rel="nofollow noreferrer">MsiGetProperty</a> function.</p>
<p>Note: Property names mean different things based on case, so make sure you use the cases above.</p>
<p>I couldn't find any reference in the IS online help or Google to the DefaultFeatureInstalled event. Is your InstallShield project Basic MSI or InstallScript?</p>
| 15,854
|
<p>I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?</p>
|
<p>Hierarchical namespaces do have a use in that they allow progressively more refined definitions. Certainly a single provider may produce two classes with the same name. Often the first level is occupied by the company name, the second specifies the product, the third (and possibly more) my provide the domain.</p>
<p>There are also other uses of namespace segregation. One popular situation is placing the base classes for a factory pattern in its own namespace and then derived factories in their own namespaces by provider. E.g. <code>System.Data</code>, <code>System.Data.SqlClient</code> and <code>System.Data.OleDbClient</code>.</p>
|
<p>It depends on your needs and programming style. But one of the benefits of <code>namespace</code> is to help partition name space (hence the name). With a single namespace, as your project is increases in size and complexity, so does the likelihood of name-collision.</p>
<p>If you're writing code that's meant to be shared or reused, this becomes even more important.</p>
| 14,266
|
<p>I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threads that they should also begin processing. The current solution involves the monitor thread setting a global variable and having the other threads loop and check that, ie in the monitor thread:</p>
<pre><code>CheckIfWorkAvailable() {
while(true) {
if (queue.Empty != true) {
workToBeDone = true;
}
}//end while loop
}
</code></pre>
<p>and then in the worker threads:</p>
<pre><code>DoWork() {
while(true) {
if (workToBeDone == true) {
//do work...
}
else {
Thread.Sleep(x seconds)
}
}//end while loop
}
</code></pre>
<p>Can the monitor thread notify the worker threads when there is work to do instead of having them just loop and sleep? The worker threads also set a counter indicating they are working and the decrement it when their work is done so the workToBeDone flag can be set to false.</p>
|
<p>Check out <a href="http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx" rel="nofollow noreferrer">WaitHandle</a> and its descending classes. <a href="http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx" rel="nofollow noreferrer">EventWaitHandle</a> may suit your needs.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80).aspx</a></p>
<p>You can use AutoReset Events</p>
| 25,779
|
<p>How can I get line numbers to <code>print</code> in <strong>Visual Studio 2005</strong> when printing <code>code</code> listings?</p>
|
<p>There is an option in the Print Dialog to do the same (in VS 2005 and 2008 atleast)!</p>
|
<p>Isn't there an option in the Print Dialog?</p>
<p>Edit: There is. Go to File => Print, and then in the bottom left there is "Print what" and then "Include line Numbers"</p>
| 2,586
|
<p>I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.</p>
<p>After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:</p>
<pre><code>// Get the parent entry node of this link element
$importnode = $objReplyXML->importNode($link->parent_node(), true);
</code></pre>
|
<p><a href="http://no2.php.net/manual/en/class.domelement.php" rel="noreferrer">DOMElement</a> is a subclass of <a href="http://no2.php.net/manual/en/class.domnode.php" rel="noreferrer">DOMNode</a>, so it does have parent_node property. Just use $domNode->parentNode; to find the parent node.</p>
<p>In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.</p>
|
<p>I'm not entirely sure how your code works, but it seems like you have a small error in your code. </p>
<p>On the line you posted in your question you have <code>$link->parent_node()</code>, but in the answer with the entire code snippet you have <code>$link**s**->parent_node()</code>. </p>
<p>I don't think the <code>s</code> should be there. </p>
<p><strong>Also, I think you should use $link->parentNode, not $link->parent_node().</strong></p>
| 4,852
|
<p>I am finding that calling a stored proc in Excel is not as easy as it should be, but calling a view, or a direct table is very easy. So, how can I create a view that will call a stored proc with no params?</p>
<p>I know I won't be able to pass any values into the view, and I don't need or want to, Just want to wrap a stored proc in a view.</p>
<p>something like <code>select exec MyStoredProc()</code> would be great.</p>
|
<p>iirc (I don't have a copy to hand) if you happen to be in T-SQL it should be possible to select * from a <strong>user defined table function</strong> (which are for most intents and purposes identical to sprocs) which returns a table variable.</p>
|
<p>You should be able to put a trigger on a dummy table, and call the proc inside the trigger.</p>
<p>This is definitely a hack, and you would want to really lock down permissions on the table and proc.</p>
| 45,547
|
<p>I would like to retrieve at runtime the values for the "dialect" and "connection.driver_class" properties specified in the configuration file.</p>
<p>Do you know how to do that?</p>
<p>Many thanks,
Nicola</p>
|
<p>thanks for your answer.
One thing that I don't like in that solution is that I need to keep the configuration and pass it around in the methods that need the knowledge of the dialect.</p>
<p>I found a couple of other ways that need only a reference to the ISession of of the ISessionFactory.</p>
<p>From the ISession:</p>
<pre><code> public static Dialect GetDialect(ISession session)
{
Dialect dialect = session.GetSessionImplementation().Factory.Dialect;
return dialect;
}
</code></pre>
<p>From the ISessionFactory:</p>
<pre><code> public static Dialect GetDialect(ISessionFactory sessionFactory)
{
var implementor = sessionFactory as ISessionFactoryImplementor;
Dialect dialect = implementor.Dialect;
return dialect;
}
</code></pre>
|
<p>When you build the Configuration object and load the XML and eventually build the SessionFactory, hang on to the Configuration object reference you have.</p>
<p>You can use the Properties object of the Configuration reference you have, or you can do something like Dialect.GetDialect(_configuration.Properties).</p>
| 35,559
|
<p>I know that I am supposed to use <code>delete []</code> after I use <code>new []</code>, so using <code>auto_ptr</code> with <code>new []</code> is not such a bright idea.</p>
<p>However, while debugging <code>delete []</code> (using Visual Studio 2005), I noticed that the call went into a function that looked like this:</p>
<pre><code>void operator delete[]( void * p )
{
RTCCALLBACK(_RTC_Free_hook, (p, 0))
operator delete(p);
}
</code></pre>
<p>Does this mean, the <code>[]</code> syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?</p>
|
<p>Consider this code:</p>
<pre><code>class DeleteMe
{
public:
~DeleteMe()
{
std::cout << "Thanks mate, I'm gone!\n";
}
};
int main()
{
DeleteMe *arr = new DeleteMe[5];
delete arr;
return 0;
}
</code></pre>
<p>If you run that in VS2005 it will print:</p>
<pre>Thanks mate, I'm gone!</pre>
<p>If you change <code>main()</code> to correctly adhere to the C++ standard:</p>
<pre><code>int main()
{
DeleteMe *arr = new DeleteMe[5];
delete[] arr;
return 0;
}
</code></pre>
<p>It will print:</p>
<pre>Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!</pre>
<p>Don't shoot yourself in the foot. VS2005 will <b>NOT</b> do the correct thing if you mismatch different flavors of new/delete. Neither will any other C++ standard conformant compiler.</p>
<p>There's some compiler magic going on around <code>operator new</code> and <code>operator delete</code> (and their different flavors), basically the call to the ctors and dtors are added behind the scenes. This magic depends on those small brackets [], so don't lose them or you'll lose the magic.</p>
|
<p>Just because they might work the same now, doesn't mean you can necessarily treat them the same - the behaviour could change. And besides, who cares - you should write your code so you don't have to remember.</p>
<p>Additionally, you can use <a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/scoped_array.htm" rel="nofollow noreferrer">scoped_array</a> for array deletion.</p>
| 38,652
|
<p>Is there any way to view the activity log for the integrate SourceSafe inside Visual Studio 2005 Pro? I'd like to be able to quickly see the results of any Get Latest Version, Check In and Checkout actions, and I can't find a way to get that information without having to open the VSS client.</p>
|
<p>The output window (View - Output) echoes a lot. If it isn't verbose enough though I don't know how one would configure that.</p>
|
<p>That's what I was missing - I never saw the [Source Control] option for the "Show output from:" setting in the Output window. Great, thanks.</p>
| 17,124
|
<p>Is there a way to compress a VMWare image on a ESXi server for archival purposes?</p>
|
<p>What is wrong with simply using your faviourite archiver/compressor utility?</p>
|
<p>I concur with <a href="https://stackoverflow.com/questions/148999/archiving-vmware-images-on-esxi#149059">@Sec</a> - I use .tar.gz or .tar.bz2.</p>
| 17,954
|
<p>I have a Team Foundation Server 2008 Installation and a separate machine with the Team Build service.</p>
<p>I can create team builds and trigger them manually in Visual Studio or via the command line (where they complete successfully). However check ins to the source tree do not cause a build to trigger despite the option to build every check in being ticked on the build definition. <strong>Update: To be clear I had a fully working build definition with the CI option enabled.</strong></p>
<p>The source tree is configured is a pretty straight forward manner with code either under a <em>Main</em> folder or under a <em>Branch\branchName</em> folder. Each branch of code (including main) has a standard Team Build definition relating to the solution file contained within. The only thing that is slightly changed from default settings is that the build server working folder; i.e. for main this is <em>Server:"$\main" Local:"c:\build\main"</em> due to path length. </p>
<p>The only thing I've been able to guess at (possible red herring) is that there might be some oddity with the developer workspaces. Currently each developer maps Server:"$\" to local:"c:\tfs\" so that there is only one workspace for all branches. This is mainly to avoid re-mapping problems that some of the developers had previously gotten themselves into. But I can't see how this would affect CI.</p>
<p><strong>UPDATE: Ifound the answer indirectly; please read below</strong></p>
|
<p>Ok I have found the answer myself after several dead ends. In the end I fixed this unintentionally while fixing another issue. Basically we had just turned on the automatic execution of unit tests for our builds. The test would run sucessfully but then immediately the build would bomb out with a message saying it was unable to report to the build drop folder. </p>
<p>What was happening was that while the Build service runs under one account and has a set of rights; some of the functionality is actually driven through the TFSService account. fter wading a heap of permissions I had my tests being reported. Then I noticed that builds had started to trigger on check-ins; I can't tell you exactly which permission fixed this but hopefully this answer will at least set people down the right path.</p>
<p>One other note a few of the builds started failing due to conflicting workspace mappings - this was a separate issue that I resolved by deleting some obsolete workspaces using the Attrice Sidekicks for Team Foundation tool.</p>
<p>Hope this helps somebody else.</p>
|
<p>Select your team project from team explorer, then right click on the Builds folder. Select a new build definition and then select the trigger tab. Move the radio button to "Build each check-in (more builds)"</p>
<p>More info can be found here</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms181716.aspx" rel="nofollow noreferrer">MSDN How to: Create a Build Definition</a></p>
| 6,543
|
<p>I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this...</p>
<pre><code>text="<%$ Resources: Namespace.ResourceFileName, NAME %>"
</code></pre>
<p>or some other similar method in the view page.</p>
|
<pre class="lang-cs prettyprint-override"><code><%= Resources.<ResourceName>.<Property> %>
</code></pre>
|
<p>If you are using ASP.NET 2.0 or higher, after you compile with the resource file, you can reference it through the Resources namespace:</p>
<pre><code>text = Resources.YourResourceFilename.YourProperty;
</code></pre>
<p>You even get Intellisense on the filenames and properties.</p>
| 8,852
|
<p>I need to upload images using FileUpload without postback(using Ajax).I tried many examples.But in all postback is coming or they are using PHP.Can anyone help me to do single file upload or multi file upload using ajax in ASP.Net with C#.</p>
|
<p>SWFUpload</p>
<p><a href="http://demo.swfupload.org/v220beta3/simpledemo/index.php" rel="noreferrer">http://demo.swfupload.org/v220beta3/simpledemo/index.php</a></p>
<p><a href="http://swfupload.org/" rel="noreferrer">http://swfupload.org/</a></p>
<p>Javascript and Flash, there's no post-back :) and there's .NET implementations available on the site.</p>
|
<p>There is no such thing as a ajax file upload. The components that you see either use flash swfupload or a hidden iframe that they post a form to that give the impression it is happening in an ajax manner. There are many plugins avaiable to help you do this. My favourite is <a href="http://jquery.webunity.nl/" rel="nofollow noreferrer">this</a> that uses jquery and swfupload</p>
| 43,642
|
<p>I have a page where I combine labels, input boxes and text areas to display some content.
I would like all of them to have the same font-family and font-size.
I have played with the <em>font-family: inherit</em> style but this doesn't seem to work for the input and text areas.
What would be the easiest way to ensure the same font / size over the whole page.</p>
|
<p>Ok ... this does the trick:</p>
<pre><code>*
{
font-family: arial;
}
input
{
font-family: inherit;
font-size: 100%
}
textarea
{
font-family: inherit;
font-size: 100%
}
</code></pre>
|
<p>I think most CSS devs will do something like </p>
<pre><code>body {font: normal 10pt Arial}
</code></pre>
<p>At the top of the CSS file.</p>
<p>If you want to change labels from this, just add a </p>
<pre><code>label, input, textarea {font-family:Georgia}
</code></pre>
<p>somewhere down the road.</p>
| 49,745
|
<p>If I have a button like the one in this image :</p>
<p><strong><a href="http://www.freeimagehosting.net/image.php?4cd775814c.png" rel="nofollow noreferrer">http://www.freeimagehosting.net/image.php?4cd775814c.png</a></strong></p>
<p>how could I make the text display itself vertically ? As in </p>
<pre>
j
B
u
t
t
o
n
1
</pre>
<p>I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ?</p>
<p><strong>EDIT:</strong> how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .</p>
|
<p>You can use HTML for JButton or JLabel. So </p>
<pre><code>button = new JButton("<html>J<br>b<br>u<br>t<br>t<br>o<br>n<br>1</html>");
</code></pre>
<p>should do the trick.</p>
|
<p>I don't know if this is useful to you, but <a href="http://www.codeguru.com/java/articles/199.shtml" rel="noreferrer">this sample</a> shows how to make a vertical label. The difference is that it rotates all of the text (and/or the icon) instead of stacking the letters. I don't know how difficult it would be to modify it to do what you're asking.</p>
<p>The advantage of doing it this way is if your labels can change at runtime; generating big HTML strings might be a pain compared to a simple <code>label.setUI(new VerticalLabelUI(true));</code> (and you don't have to worry about <> in the label text).</p>
| 32,477
|
<p>When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.</p>
<p>Is there a way, in HTTP headers or equivalents, to change this behaviour?</p>
|
<pre><code><input autocomplete="off">
</code></pre>
|
<p>I wonder, if you set the page not to be cached through meta tags, will that fix the problem? <a href="http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html" rel="nofollow noreferrer">http://lists.evolt.org/archive/Week-of-Mon-20030106/131984.html</a> If it does, it'll have the benefit of working on browser's with Javascript disabled.</p>
| 7,546
|
<p>How do I limit a SQL Server Profiler trace to a specific database? I can't see how to filter the trace to not see events for all databases on the instance I connect to.</p>
|
<p>Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.</p>
|
<p>Create a new template and check DBname. Use that template for your tracefile.</p>
| 34,338
|
<p>I have a need to populate a Word 2007 document from code, including repeating table sections - currently I use an XML transform on the document.xml portion of the docx, but this is extremely time consuming to setup (each time you edit the template document, you have to recreate the transform.xsl file, which can take up to a day to do for complex documents).</p>
<p>Is there any better way, preferably one that doesn't require you to <em>run</em> Word 2007 during the process?</p>
<p>Regards
Richard</p>
|
<p>I tried myself to write some code for that purpose, but gave up. Now I use a 3rd party product: <a href="http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx" rel="nofollow noreferrer"><strong>Aspose Words</strong></a> and am quite happy with that component.</p>
<p>It doesn't need Microsoft Word on the machine.</p>
<p><em>"Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word®."</em></p>
<p><em>"Aspose.Words supports a wide array of features including document creation, content and formatting manipulation, powerful mail merge abilities, comprehensive support of DOC, OOXML, RTF, WordprocessingML, HTML, OpenDocument and PDF formats. Aspose.Words is truly the most affordable, fastest and feature rich Word component on the market."</em></p>
<p><strong>DISCLAIMER</strong>: I am not affiliated with that company.</p>
|
<p>Have you considered using VB? You could create a separate assembly to populate your document.</p>
<p>I know you are looking for a C# solution, but the XML literal support is one area where XML literal support could help you populate the document. Create a document in Word to server as a template, unzip the docx, paste the relevant XML section you want to change into you VB code, and add code to fill in the parts you wish to change. It's difficult to say from your description if this would meet your requirements but I would suggest looking into it.</p>
| 36,941
|
<p>I need to display many pages of news in a site. Should I do the pagination in the database query using <code>LIMIT</code> or with the PHP script after getting all the results?</p>
|
<p>Use limit in SQL! Every time!</p>
<p>Otherwise you're throwing around considerably more data than you need to, which makes your scripts unnecessarily slow, and will lead to scalability problems as the amount of data in your tables increases.</p>
<p>Limit is your friend!</p>
|
<p>Personally, I would use the query to do it. Obviously, that can change if your dealing with AJAX and such, but just doing a basic limit in the query and outputting the results is simple and efficient.</p>
| 13,429
|
<p>I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.</p>
|
<p>The base <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.utilities.task.aspx" rel="noreferrer">Task</a> class has a <code>Log</code> property you can use:</p>
<pre><code>Log.LogMessage("My message");
</code></pre>
|
<p>For unit testing purposes, I wrap the logger around a helper class</p>
<pre><code>public static void Log(ITask task, string message, MessageImportance importance)
{
try
{
BuildMessageEventArgs args = new BuildMessageEventArgs(message, string.Empty,
task.ToString(), importance);
task.BuildEngine.LogMessageEvent(args);
}
catch (NullReferenceException)
{
// Don't throw as task and BuildEngine will be null in unit test.
}
}
</code></pre>
<p>Nowadays I'd probably convert that into an extension method for convenience.</p>
| 19,769
|
<p>I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I <a href="http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference" rel="noreferrer">can't rely on Number.toFixed</a> </p>
<blockquote>
<p>The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not supported in Mozilla until Firefox version 1.5 (although IE supported the methods since version 5.5). While it's mostly safe to use these methods, older browsers WILL break so if you are writing a public program it's recommended you provide your own prototypes to provide functionality for these methods for older browser.</p>
</blockquote>
<p>I'm considering using something like</p>
<pre><code>Math.round(N*1000000)/1000000
</code></pre>
<p>What is the best method for providing this a prototype to older browsers?</p>
|
<p>Try this:</p>
<pre><code>if (!Number.prototype.toFixed)
Number.prototype.toFixed = function(precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power)/power);
}
</code></pre>
|
<p>I think Firefox 1.5 and IE 5 are pretty much no longer used, or by a very minor quantity of people.<br>
It is a bit like coding to support Netscape Navigator... :-)<br>
Unless some other major browser (Opera? Safari? unlikely...) doesn't support this, or if your Web logs show lot of legacy browser use, you can probably just use these methods.<br>
Sometime, we have to move on. ^_^</p>
<p>[EDIT] Works fine on Opera 9.50 and Safari 3.1</p>
<pre><code>javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));
</code></pre>
<p>The article you reference is a year and half ago, an eternity in IT industry... I think that, unlike IE users, Firefox users often go to the latest version.</p>
| 43,738
|
<p>Recently, I have heard people talking about masterspool, when talking about 3D printing filament.</p>
<ul>
<li>What <em>exactly</em> is master spool?</li>
<li>Where did the idea come from and when?</li>
<li>Is it being widely adopted? Or to be specific, how many distributors/manufacturers have adopted this already, and is it gaining traction?</li>
<li><strike>Is this something that I should get excited by?</strike></li>
<li><strike>If so, why is it such a good idea?</strike></li>
</ul>
|
<p>A masterspool is the practice of printing your own spool out of filament, which will then be used to support your filament you purchase without a spool attached. The main idea is to create a reusable spool and create less waste. </p>
<p>(<em>NOTE: I'm in no way affiliated with MatterHackers.com, nor am I an endorser of their products.</em> There is also a version which <a href="https://www.villageplastics.com/the-filament-koil/" rel="nofollow noreferrer">Village Plastics</a> has created.)</p>
<p>On <a href="https://www.matterhackers.com/articles/tech-breakdown-the-master-spool" rel="nofollow noreferrer">MatterHackers.com</a> website, they state:</p>
<blockquote>
<p>Filament without a spool? Why are we making this? The short answer: because the community wants it. We had enough questions, comments and plenty of tweets asking if we had plans to pick up the Master Spool concept. Seeing the response and interest within the community made it clear to us: we needed to bring this idea to the States. With a joint effort between MatterHackers and Village Plastics, you can now purchase Master Spool refills from within the US.</p>
</blockquote>
<p>They are tying to apply the <em>Reduce, Reuse, Recycle</em> mantra to create a cleaner environment for the rest of the world. While they are not the first to create or use a printable spool, they are pretty happy to be pressing forward with the idea of having a reusable spool and selling filament without a spool attached.</p>
<p>MatterHackers go on to state:</p>
<blockquote>
<p>What are the benefits of the Master Spool? Not only is there the benefit of reducing plastic waste, using a Master Spool will also reduces shipping costs for new spools, and limits the clutter from amassing of a huge collection of used or empty spools. Rather than throwing away, trying to recycle dozens of spools, or trying to come up with a way to reuse them in some (like the Spool Tool), using the Master Spool means you can use all those filament scraps you have laying around on something useful and have one spool for all of your filament.</p>
</blockquote>
<p>As far as where it started, it appears to have originated with <a href="https://www.thingiverse.com/thing:1738730" rel="nofollow noreferrer">this print on Thiniverse</a> created by <a href="https://www.thingiverse.com/Dingoboy71/about" rel="nofollow noreferrer">Dingoboy71</a>. A well known 3D printer named <em>RichRap</em> created the reusable spool which MatterHacker promotes, though they say there are several which will work with their product (Village Plastic says pretty much the same). </p>
<p>If you get excited about saving the planet, then you should be excited about this. If you are a robust printer, going through tons (hopefully not literally) of filament per year, this method will save a lot of waste in the long run.</p>
<p>Realize there are (as of this writ) only limited suppliers of spool-less filament, though I think the trend for this type of product will increase in the future as the idea catches on. I guess time will tell. </p>
|
<p>One key difference between a 'masterspool' and any old spare empty reel you have left over is that the masterspool is a 2-part design which can be fitted over an existing roll of filament without needing to un-spool and re-spool the whole roll.</p>
<p>The idea being that filament can be packaged and secured for shipment (with cable ties or the like) without needing to include a whole spool every time. The end user can buy/print only as many spools as they need.</p>
<p>This concept also allows for 'extra' features to be included in the spool (such as retention for loose ends) without these features being wasted on every discarded spool.</p>
| 991
|
<p>I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.</p>
<p>The custom list defines an iterator;</p>
<pre><code>class Iterator: public std::iterator<std::forward_iterator_tag, T> {
// ...
}
Iterator begin() {
return (Iterator(root));
}
Iterator end() {
return (Iterator(NULL));
}
</code></pre>
<p>with the appropriate operators overloaded. </p>
<p>Ideally, I would like to do this;</p>
<pre><code>class Foo {
public:
Foo() {
std::list<int> x;
std::vector<int> y;
custom_list<int> z;
iter = x.begin(); // OR
iter = y.begin(); // OR
iter = z.begin();
// ...
};
private:
std::iterator<int> iter;
};
</code></pre>
<p>But obviously these are all iterators of different types. I can assume all the containers are of the same type however.</p>
<p>Is there an elegant way to solve this problem?</p>
|
<p>Here are some articles you might find of interest</p>
<p><a href="http://accu.org/index.php/journals/479" rel="noreferrer">Giving STL Iterators a Base Class</a></p>
<p><a href="http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/start_page.html" rel="noreferrer">Type Erasure for C++ Iterators</a></p>
<p><a href="http://stlab.adobe.com/classadobe_1_1any__iterator.html" rel="noreferrer">any_iterator Class Reference</a></p>
|
<p>Better late than never...</p>
<p>The latest issue of <a href="http://accu.org/index.php/aboutus/aboutjournals" rel="nofollow noreferrer">C-Vu</a> turned up and guess what was in it: That's right, iterators that do <em>exactly</em> what you wanted.</p>
<p>Unfortunately you need to become a member of the <a href="http://accu.org/" rel="nofollow noreferrer">ACCU</a> to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so <a href="http://accu.org/index.php/joining" rel="nofollow noreferrer">what are you waiting for</a>?</p>
| 3,126
|
<p>I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.</p>
<p>I'm in the middle of designing an app that does something like portfolio management. The design I have so far is</p>
<ul>
<li>Problem: a problem that needs to be solved</li>
<li>Solution: a proposed solution to one or more problems</li>
<li>Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into:
<ul>
<li>Parent-child - some sort of categorization / tree hierarchy</li>
<li>Overlap - the degree to which two solutions or two problems really address the same concept</li>
<li>Addresses - the degree to which a problem addresses a solution</li>
</ul></li>
</ul>
<p>My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.</p>
<p>So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?</p>
<p><em>Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.</em></p>
<p>I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?</p>
<h2>1: Problems (and separately, Solutions) are self-referential in versioning.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id
</code></pre>
<p>This is problematic because every time I want a new version, I have to duplicate the entire row, including that long <code>description</code> column.</p>
<h2>2: Create a new Relationship type: Version.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at
</code></pre>
<p>This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.</p>
<h2>3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.</h2>
<pre><code>table problems
int id
table attributes
int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id
foreign key previous_version_id -> attributes.id
</code></pre>
<p>This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That <code>value</code> column has to be free-text. I can make the <code>name</code> column a reference into a separate <code>attribute_names</code> table that has a <code>type</code> column, but that doesn't <em>force</em> the correct type in the <code>attributes</code> table.</p>
<p><em>later still: response to @Eric Beard's comments about multi-table foreign keys:</em></p>
<p>Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be <em>extremely</em> wasteful to do combine them into one table.</p>
|
<p>Hmm, sounds kind of like this site...</p>
<p>As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this.</p>
|
<p>I suppose there's</p>
<h2>Option 4: the hybrid</h2>
<p>Move the common Thing attributes into a single-inheritance table, then add an <code>custom_attributes</code> table. This makes foreign-keys simpler, reduces duplication, and allows flexibility. It doesn't solve the problems of type-safety for the additional attributes. It also adds a little complexity since there are two ways for a Thing to have an attribute now.</p>
<p>If <code>description</code> and other large fields stay in the Things table, though, it also doesn't solve the duplication-space problem.</p>
<pre><code>table things
int id | int type | string name | text description | datetime created_at | other common fields...
foreign key type -> thing_types.id
table custom_attributes
int id | int thing_id | string name | string value
foreign key thing_id -> things.id
</code></pre>
| 3,277
|
<p>I'm creating a user-based website. For each user, I'll need a few MySQL tables to store different types of information (that is, userInfo, quotesSubmitted, and ratesSubmitted). Is it a better idea to:</p>
<p>a) Create one database for the site (that is, "mySite") and then hundreds or thousands of tables inside this (that is, "userInfo_bob", "quotessubmitted_bob", "userInfo_shelly", and"quotesSubmitted_shelly")</p>
<p>or</p>
<p>b) Create hundreds or thousands of databases (that is, "Bob", "Shelly", etc.) and only a couple tables per database (that is, Inside of "Bob": userInfo, quotesSubmitted, ratesSubmitted, etc.)</p>
<p><strong>Should I use one database, and many tables in that database, or many databases and few tables per database?</strong></p>
<hr>
<p>Edit:</p>
<p>The problem is that I need to keep track of who has rated what. That means if a user has rated 300 quotes, I need to be able to know exactly which quotes the user has rated.</p>
<p>Maybe I should do this?</p>
<p>One table for quotes. One table to list users. One table to document ALL ratings that have been made (that is, Three columns: User, Quote, rating). That seems reasonable. Is there any problem with that?</p>
|
<p>Use one database.</p>
<p>Use one table to hold users and one table to hold quotes.</p>
<p>In between those two tables you have a table that contains information to match users to quotes, this table will hold the rating that a user has given a quote.</p>
<p>This simple design will allow you to store a practically unlimited number of quotes, unlimited users, and you will be able to match up each quote to zero or more users and vice versa.</p>
<p>The table in the middle will contain <em>foreign keys</em> to the user and quote tables.</p>
<p>You might find it helpful to review some database design basics, there are plenty of related questions here on stackoverflow.</p>
<p>Start with these...</p>
<p><a href="https://stackoverflow.com/questions/246701/what-is-normalisation-or-normalization-why-is-it-important">What is normalisation?</a></p>
<p><a href="https://stackoverflow.com/questions/141126/what-is-important-to-keep-in-mind-when-designing-a-database">What is important to keep in mind when designing a database</a></p>
<p><a href="https://stackoverflow.com/questions/220613/how-many-fields-is-too-many-in-a-table">How many fields is 'too many'?</a></p>
<p><a href="https://stackoverflow.com/questions/59482/whats-the-better-database-design-more-tables-or-more-columns">More tables or more columns?</a></p>
|
<p>Use one database and one table. You will require a table "User" and this table will be linked (Primary--Foreign key) to these table.</p>
| 42,487
|
<p>I'm trying to be a good developer and create some documentation before I start programming my next project.</p>
<p>I have created a database schema diagram in Visio and created relationships between columns.</p>
<p>However, I am looking for a way to make the relationships between columns more clear. I want the arrow to connect column to column.</p>
<p>Is there a way to do this in Visio?</p>
<p><img src="https://i.stack.imgur.com/sj0Bo.jpg" alt="http://i.stack.imgur.com/sj0Bo.jpg"></p>
|
<p>You can use the Visio Drawing tools to force the Relationship Connector to glue to particular Connection Points on the Table Shapes:</p>
<ol>
<li>Turn on Connection Points in the View menu.</li>
<li>On the standard toolbar find the Connector Tool just to the right of the Pointer Tool. Click on the little arrow and change to the Connection Point Tool.</li>
<li>Hold Ctrl and click on one of the Table Shapes at the point where you want to join the Relationship Connector.</li>
<li>Do the same on the other Table Shape.</li>
<li>Glue the ends of the Relationship Connector to the Connection Points you just added.</li>
<li>You will have broken the relationship. To fix it, select the Relationship Connector and view the definition of the relationship in the Database Properties Window. </li>
<li>Associate the fields again.</li>
</ol>
<p>(This was tested with Visio Enterprise 2003.)</p>
|
<p>To my knowledge this is how visio draws it, and it is not possible to get it to point at an exact column. its kinda annoying, but I guess you learn to live with the FK markings</p>
| 25,245
|
<p>If I have class names such as "left", "right", "clear" and xhtml like</p>
<pre><code><a href="index.php" class="right continueLink">Continue</a>
</code></pre>
<p>With CSS like</p>
<pre><code>.right {
float: right;
}
</code></pre>
<p>I know it's not a semantic name, but it does make things much easier sometimes.</p>
<p>Anyway, what are your thoughts?</p>
|
<p>I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change <code>.right</code> to <code>{float:left;}</code> (obviously a bad idea) or go through all your HTML files and change <code>right</code> to <code>left</code>.</p>
<p>Why do you want that particular link to be floated right, and the other <code>.continueLink</code>'s not to? Use the answer to that question to choose a more descriptive class name for that link.</p>
|
<p>.right and other classes like that, certainly makes it quick to write create a tag with a <code>float:right</code> rule attached to it, but I think this method has more disadvantages than advantages:</p>
<p>Often a class-style with a single <code>float:right;</code> in it will lack something, your example wil only float right if the other class rule contains a <code>display:block</code> in it, since an "a" tag is not a block level element. Also floating elements more often than not needs to have width an height attached. This means that the code in your example needs additional code to do what it says, and you have to search in two places when you have to change your css.</p>
<p>I tend to style my html by dividing the page into different div-tags with unique id's, and then styling elements in these div by inheritance like this.</p>
<pre><code>div#sidebar { float:right; width:200px; }
div#sidebar ul { list-style-type:none; }
</code></pre>
<p>This makes it possible to partition my css files, so that it is easy to find the css-code that styles a particular tag, but if you introduce .right and other classes you are starting to disperse the rules into different areas of the css file, making the site more difficult to maintain.</p>
<p>I think the idea of having a very generic classes is born from the wish of making it possible to change the entire layout of the site by changing a couple of rules in a stylesheet, but I must say that in my 8 years of website development with 30+, different sites under my belt i haven't once changed the layout of a website and reused the HTML. </p>
<p>What I have done countless times is making small adjustments to regions of pages, either due to small changes in the design or to the introduction of new browsers. So I'm all for keeping my css divided into neat chunks that makes it easy to find the rules I am looking for, and not putting the code in different places to achieve a shorter stylesheet.</p>
<p>Regards
Jesper Hauge</p>
| 29,982
|
<p>In C#, I'm creating an XML file from a DataTable using dataTable.WriteXml(filePath), and get the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
<ExperienceProfile>
<Col1>blah</Col1>
<Col2>4ed397bf-a4d5-4ace-9d44-8c1a5cdb0f34</Col2>
</ExperienceProfile>
</ExperienceProfiles>
</code></pre>
<p>How can I get it to write the XML in the following format?:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
<ExperienceProfile Col1="blah"
Col2="blah" ></ExperienceProfile>
</ExperienceProfiles>
</code></pre>
|
<p>What you want is some way to tell the DataSet the expected format of your data. You're in luck, the DataSet supports just this feature.</p>
<p>You will need to create an XML schema for your data and load it into the DataSet before you write out the XML. In the schema define Col1 and Col2 as attributes of the ExperienceProfile element and the DataSet will know to format the output document to meet the requirements specified in the schema.</p>
<p>If you are not comfortable with creating a schema you can create a sample of the XML file the way that you want it to be formatted, then take a look at the XmlSchemaInference class in the framework. This class can be used to automatically generate your schema, you may need to tweak the output a little but it can help if you are not familiar with XSD.</p>
|
<blockquote>
<p>Short answer: you can't, using the
WriteXml method of a DataTable.</p>
<p>Long answer (which is not very long):
Just roll your own.</p>
</blockquote>
<p>Retract my answer, as per above :)</p>
| 46,192
|
<p>Does anyone know what substantial differences there are between the <a href="http://www.postgresql.org" rel="noreferrer">regular PostgreSQL</a> and <a href="http://www.enterprisedb.com/products/postgres_plus.do" rel="noreferrer">Postgres Plus</a>?</p>
|
<p>The database is the same, meaning that the SQL is fully compatible to any other PostgreSQL installation around (save for the GIS data formats). </p>
<p>The main difference is that there is a bunch of modules and tools bundled with Postgres Plus that you would have to collect and install separately and by yourself otherwise. Thus the main advantage is easy and speedy installation.</p>
<p>Most of the bundled stuff looks like it's freely available from other sources. That Postgres Studio application looks suspiciously close to pgAdmin III.</p>
|
<p>I used 8.2 and when was the time to switch to 8.3 I tried PostGresPlus.</p>
<p>The Speed was a lot <strong>faster</strong>. LOT I mean queries that took 30 secs, takes now less than 2 seconds. I am not sure if it's 8.3 that is faster or the Enterprise Plus but I can tell you that I was impressed. </p>
<p>Other thing that I like is that I can <strong>debug</strong> proc stored. It cames with more tools.</p>
| 44,744
|
<p>Can anybody help me to build an XSD file to validate XMLs like these:</p>
<pre><code>[test]
[a/]
[b/]
[a/]
[b/]
[/test]
[test]
[a/]
[a/]
[b/]
[/test]
</code></pre>
<p>Basically, I can have any number of <code><a></code> and/or <code><b></code> nodes without any other rule (can't use <code><xs:sequence></code>).</p>
|
<p>It isn't going to very fast if you have a lot of <strong>a</strong> or <strong>b</strong> nodes but this validates against what you've described.</p>
<pre><code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="test">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="a"/>
<xs:element name="b"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code></pre>
|
<p>If you paste the sample XML, we can help you better. However, <a href="https://stackoverflow.com/questions/288236/xsd-code-generator">Microsoft has an XSD code generator</a> that generates an XSD based on an XML file that you pass in as an argument.</p>
| 46,170
|
<p>See title. By lightweight markup I mean something like markdown or wikitext.</p>
|
<p>Well, silverstripe <a href="http://www.silverstripe.com/" rel="nofollow noreferrer">http://www.silverstripe.com/</a> is thought to be a good option for people who care about web standards , as is modx <a href="http://modxcms.com/" rel="nofollow noreferrer">http://modxcms.com/</a> </p>
<p>For a lighter editor, check out textpattern.com which uses textile (like markdown). If you're on rails, <a href="http://webby.rubyforge.org/" rel="nofollow noreferrer">http://webby.rubyforge.org/</a> might do the trick. </p>
<p><a href="http://www.madebyfrog.com" rel="nofollow noreferrer">http://www.madebyfrog.com</a> is a port of the ruby CMS radiant that aims to be fast, light, and minimal. </p>
|
<p>I am a user of Joomla. I think Joomla is in the top five CMS.</p>
| 13,078
|
<p>I have a simple database with two tables. Users and Configurations. A user has a foreign key to link it to a particular configuration.</p>
<p>I am having a strange problem where the following query always causes an inner join to the Configuration table regardless of the second parameter value. As far as I can tell, even though the "UserConfiguration =" part of the object initialisation is conditional, LINQ doesn't see that and determines that a relationship is followed in any case.</p>
<p>If I actually remove that last initialisation, the whole thing works as expected. It doesn't inner join when loadConfiguration == false and it does join when loadConfiguration == true.</p>
<p>Anyone got any ideas about this? Is this syntax just not going to work? The only thought I have now is to wrap the return in a basic if statement - I just wanted to avoid the duplicated lines.</p>
<pre><code>public UserAccount GetByUsername(string username, bool loadConfiguration)
{
using (Database database = new Database())
{
if (loadConfiguration)
{
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<User>(c => c.Configuration);
database.LoadOptions = loadOptions;
}
return (from c in database.Users
where c.Username == username
select new UserAccount
{
ID = c.ID,
ConfigurationID = c.ConfigurationID,
Username = c.Username,
Password = c.Password.ToArray(),
HashSalt = c.HashSalt,
FirstName = c.FirstName,
LastName = c.LastName,
EmailAddress = c.EmailAddress,
UserConfiguration = (loadConfiguration) ? new ApplicationConfiguration
{
ID = c.Configuration.ID,
MonthlyAccountPrice = c.Configuration.MonthlyAccountPrice,
TrialAccountDays = c.Configuration.TrialAccountDays,
VAT = c.Configuration.VAT,
DateCreated = c.Configuration.DateCreated
} : null
}).Single();
}
}
</code></pre>
<p>Thanks in advance,</p>
<p>Martin.</p>
|
<p>switch() needs an integral type (like int, char, ...)</p>
<p>string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement</p>
|
<p>The easiest alternative BTW is a <code>std::map<std::string, boost::function> StringSwitch;</code></p>
<p>This lets you say <code>StringSwitch["Some string"](arguments...)</code></p>
| 39,760
|
<p>Does anyone know of an MD5/SHA1/etc routine that is easily used with GLib (i.e. you can give it a GIOChannel, etc)?</p>
|
<p>Unless you have a <em>very</em> good reason, use glib's built-in MD5, SHA1, and SHA256 implementations with <a href="http://developer.gnome.org/glib/unstable/glib-Data-Checksums.html#GChecksum" rel="nofollow noreferrer"><code>GChecksum</code></a>. It doesn't have a built-in function to construct a checksum from an IO stream, but you can write a simple one in 10 lines, and you'd need to write a complex one yourself anyway.</p>
|
<p>You normally have to do library glue stuff yourself...</p>
<pre><code>void get_channel_md5( GIOChannel* channel, unsigned char output[16] )
{
md5_context ctx;
gint64 fileSize = <get file size somehow?>;
gint64 filePos = 0ll;
gsize bufferSize = g_io_channel_get_buffer_size( channel );
void* buffer = malloc( bufferSize );
md5_starts( &ctx );
// hash buffer at a time:
while ( filePos < fileSize )
{
gint64 size = fileSize - filePos;
if ( size > bufferSize )
size = bufferSize;
g_io_channel_read( channel, buffer );
md5_update( &ctx, buffer, (int)size );
filePos += bufferSize;
}
free( buffer );
md5_finish( &ctx, output );
}
</code></pre>
| 13,788
|
<p>I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <code><cfqueryparam</code>> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?</p>
<p>If my query looks like this:</p>
<pre><code>select * from Foo where name like '%Bob%'
</code></pre>
<p>what should my <code><cfqueryparam</code>> tag look like?</p>
|
<p>@Joel, I have to disagree.</p>
<pre><code>select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" />
</code></pre>
<ol>
<li><p>Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!)</p></li>
<li><p>The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.</p></li>
<li><p>When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.</p></li>
</ol>
|
<pre><code>select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="cf_sql_varchar" value="%Bob%" />;
</code></pre>
| 6,872
|
<p>in web.xml i set my welcome file to a jsp within web.xml</p>
<pre><code><welcome-file>WEB-INF/index.jsp</welcome-file>
</code></pre>
<p>inside index.jsp i then forward on to a servlet </p>
<pre><code><% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %>
</code></pre>
<p>however the application tries to find the servlet at the following path </p>
<pre><code>applicationName/WEB-INF/myServlet
</code></pre>
<p>the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?</p>
|
<p>I use the <a href="http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html" rel="nofollow noreferrer">Tomcat jasper ANT tasks</a> in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml.</p>
<pre><code> <?xml version="1.0"?>
<project name="jspc" basedir="." default="all">
<import file="${build.appserver.home}/bin/catalina-tasks.xml"/>
<target name="all" depends="jspc,compile"></target>
<target name="jspc">
<jasper
validateXml="false"
uriroot="${build.war.dir}"
webXmlFragment="${build.war.dir}/WEB-INF/generated_web.xml"
addWebXmlMappings="true"
outputDir="${build.src.dir}" />
</target>
<target name="compile">
<javac destdir="${build.dir}/classes"
srcdir="${build.src.dir}"
optimize="on"
debug="off"
failonerror="true"
source="1.5"
target="1.5"
excludes="**/*.smap">
<classpath>
<fileset dir="${build.war.dir}/WEB-INF/classes">
<include name="*.class" />
</fileset>
<fileset dir="${build.war.lib.dir}">
<include name="*.jar" />
</fileset>
<fileset dir="${build.appserver.home}/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${build.appserver.home}/bin">
<include name="*.jar"/>
</fileset>
</classpath>
<include name="**" />
<exclude name="tags/**"/>
</javac>
</target>
<target name="clean">
<delete>
<fileset dir="${build.src.dir}"/>
<fileset dir="${build.dir}/classes/org/apache/jsp"/>
</delete>
</target>
</project>
</code></pre>
<p>If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.</p>
|
<p>There is the <strong>jasper2</strong> ant task others have noted. I thought I'd mention a couple of other options I've found.</p>
<p>One is cactus' <strong>webxmlmerge</strong> ant task, which uses org.codehaus.cargo.module.webapp.WebXmlMerger </p>
<p>Another would be to use <strong>JAXB</strong> to manipulate the web.xml; Sebastien Dionne's <a href="http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator" rel="nofollow noreferrer">dtd-schemas-generator</a> demo does this. Not sure what the license is though.</p>
<p>fwiw having considered these options i think I'm going to use the ant <strong>XSLT</strong> task.</p>
| 19,603
|
<p>So I am missing small sections of a layer when it prints, after a retraction for a layer change or a move, the extruder stops moving (no it isn't clicking or anything else. Just not moving). Which is fine for a few millimeters because the pressure inside the Bowden setup keeps pushing enough filament through. However, once that isn't enough it starts to make very thin lines with beads of plastic just barely holding things together. Basically this ends up as a good 2 cm or more at times of highly under extruded lines.
This happens in the slowdown after the retraction when it is restarting.
it simply doesn't move the extruder at all.
The reason I know this is because I can see the extruder not moving, in that brief period. I know it is not the extruder clicking or anything else because I can disengage the extruder spring and push filament through manually during this time with no issues.</p>
<p>I am using Ideamaker currently because I like it. </p>
<p>I have looked at this <a href="https://3dprinting.stackexchange.com/questions/313/holes-missing-layers-after-retraction-in-3d-printed-objects">Holes/ missing layers (after retraction) in 3d printed objects</a>
which is somewhat similar in appearance, but not in reason. <a href="https://i.stack.imgur.com/Eq26y.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Eq26y.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Ag8OA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Ag8OA.jpg" alt="Just a better image from the other side of the print"></a></p>
<p><strong>EDIT:</strong> So I figure it is some form of coasting that IdeaMaker has implemented for their Raise printers. I am going to try and reduce the length of the coaster attempt to convert my Bowden to a direct drive with titan extruder. I have the Titan already, but it has been giving me issues with not having enough power to push filament without ripping it to shreds. That's another thing I have to look at at some point when I have the time.</p>
|
<p>I have made some learning on mechanical setup and discovered some issues on my printer, there are few:</p>
<ol>
<li>Bed warped, even with glass (thin thickness), making BAL confused with Z-movement over the bed.</li>
<li>Overextrusion making layer oversized in terms of thickness.</li>
<li>Some of missing mechanical fine adjustments.</li>
</ol>
<p>The main reason for this symptom was the overextrusion (that made my X and Y axis jump some steps when hotend collapses in the already-printed materials on their movements).</p>
<p>I hope this helps some of those who have this similar problem!</p>
|
<p>The first picture seems to show layer shift. Usual causes include:</p>
<ol>
<li>Missed Z movement, so the nozzle hits the build and the layer is offset.</li>
<li>Bad acceleration in X/Y, so there is missed X/Y movement, and the layer is offset.</li>
</ol>
<p>Adjustment: reduce Z G0 speed, and reduce X/Y speeds (G0 and G1) and acceleration, and then repeat.</p>
<p>Hopefully, correcting this will make the issue in the second picture easier to diagnose.</p>
| 698
|
<p>I've created a script that runs every night on my Linux server that uses <code>mysqldump</code> to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to <code>mailx</code> like so:</p>
<pre><code>$ cat mysqldbbackup.sql | mailx backup@email.example
</code></pre>
<p><code>cat</code> echoes the backup file's text which is piped into the <code>mailx</code> program with the recipient's email address passed as an argument.</p>
<p>While this accomplishes what I need, I think it could be one step better, <strong>Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an <em>attachment</em>?</strong> This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.</p>
|
<p>None of the mutt ones worked for me. It was thinking the email address was part of the attachment. Had to do:</p>
<pre><code>echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- recipient@domain.example
</code></pre>
|
<p>If mutt is not working or not installed,try this-</p>
<pre><code>*#!/bin/sh
FilePath=$1
FileName=$2
Message=$3
MailList=$4
cd $FilePath
Rec_count=$(wc -l < $FileName)
if [ $Rec_count -gt 0 ]
then
(echo "The attachment contains $Message" ; uuencode $FileName $FileName.csv ) | mailx -s "$Message" $MailList
fi*
</code></pre>
| 3,802
|
<p>Best way to center a <code><div></code> element on a page both vertically and horizontally?</p>
<p>I know that <code>margin-left: auto; margin-right: auto;</code> will center on the horizontal, but what is the best way to do it vertically, too?</p>
|
<h2>The best and most flexible way</h2>
<p>The main trick in this demo is that in the normal flow of elements going from top to bottom, so the <code>margin-top: auto</code> is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified <code>top</code> and <code>bottom</code> (does not work in IE7).</p>
<p>##This trick will work with any sizes of <code>div</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code></pre>
</div>
</div>
</p>
|
<p>This solution worked for me</p>
<pre><code> .middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
</code></pre>
<p>(or height : 70% / bottom : 15% </p>
<p>height : 40% / bottom :30% ...) </p>
| 46,527
|
<p>What is the best way to convert a double to a long without casting?</p>
<p>For example:</p>
<pre><code>double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);
</code></pre>
|
<p>Assuming you're happy with truncating towards zero, just cast:</p>
<pre><code>double d = 1234.56;
long x = (long) d; // x = 1234
</code></pre>
<p>This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.</p>
|
<p>Simply put, casting is more efficient than creating a Double object.</p>
| 41,623
|
<p>We are currently designing a website that will be accessed from kiosks in a museum. Users will need to be able to browse through a number of different web pages that will currently contain static HTML content as well as go through various interactive presentations that will be based on flash and run in flash player. Users may need to input some information into a simple registration form from the kiosk as well. </p>
<p>One reason that we are currently designing this to run in a browser is because the same site and interactive presentations that are being accessed from the kiosks will also be available on the web.</p>
<p>Does anyone have recommendations on whether this design will even work or whether we should simply build two versions of the content, one for web and one for kiosk? What experiences has anyone had with building a website that is available on touchscreen and via the web? </p>
<p>This is a first time effort both for myself and for my company so any warnings, suggestions, recommendations at all would be greatly appreciated.</p>
<p><em>Note:</em> We are currently working with Flash to build our interactive content and a LAMPP stack for the server-side everything so SilverLight is not really an option.</p>
|
<p>You can have the same content, but you should have different CSS files. The touchscreen version will need to employ much larger fonts, and in some cases a touchscreen keyboard, whereas the home users won't need that.</p>
<p>Further, you may want to promote museum events on the sidebar of the home version to get people to come into the museum, whereas these would be a needless distraction at the kiosks.</p>
<p>Further, you may want to link to external websites and resources for the home user, but prevent external web browsing from inside the museum, so the stylesheet may also be used to deactivate links to external resources, without removing the text.</p>
<p>Keep them separate using stylesheets and/or JavaScript, but try to keep the content pages the same so you don't have to maintain two sets of content.</p>
<p>-Adam</p>
|
<p>Using a browser for your UI seems like a good decision, the things I would be worried about would be other apps or even browser pop-ups coming up that would interfere with the usability of your kiosk. Possible mitigation for this is to create your own browser app using the Microsoft WebBrowser control to ensure there won't be any popups, and store all the files locally on the kiosk machine so that as long as it has power it will be able to run (and you won't have to worry about network accessibility errors being displayed to the user).</p>
| 29,122
|
<p>These seem to mean the same thing. But what term is more appropriate in what context?</p>
|
<p>In general terms (and in normal English usage) the terms mean the same thing.</p>
<p>In the specific context of HTML / Javascript the terms get confused because the HTML representation of a DOM element has <em>attributes</em> (that being the term used in XML for the key/value pairs contained within a tag) but when represented as a JavaScript object those attributes appear as object <em>properties</em>.</p>
<p>To further confuse things, changes to the properties will typically update the attributes.</p>
<p>For example, changing the <code>element.href</code> <em>property</em> will update the <code>href</code> <em>attribute</em> on the element, and that'll be reflected in a call to <code>element.getAttribute('href')</code>.</p>
<p>However if you subsequently <em>read</em> that property, it will have been normalised to an absolute URL, even though the <em>attribute</em> might be a relative URL!</p>
|
<p>Delphi used properties and they have found their way into .NET (because it has the same architect).</p>
<p>In Delphi they are often used in combination with runtime type information such that the integrated property editor can be used to set the property in designtime.</p>
<p>Properties are not always related to fields. They can be functions that possible have side effects (but of course that is very bad design).</p>
| 32,268
|
<p>I have a Rake task (in lib/tasks directory) that I run with cron on my shared web hosting. The problem is that I want to compare a UTF-8 string using case statment but my source code is not UTF-8 encoded. If I save source code as UTF-8 there is error when I try to start it :(</p>
<p>What I have to do? </p>
<p>May be read this strings from external UTF-8 txt file?</p>
<p>P.S. I'm using Ruby 1.8</p>
<p>P.S. I mean compare this way:</p>
<pre><code>result = case utf8string
when 'АБВ': 1
when 'ГДИ': 2
when 'ЙКЛ': 3
when 'МНО': 4
else 5
end
</code></pre>
|
<p>I found that my problem was not in case statment</p>
<p>The problem was that when I save my source code in UTF-8 format, my text editor add 3 bytes (BOM) at the beginning to indicate that encoding is UTF-8.</p>
<blockquote>
<p><strong>Q: What is a BOM?</strong></p>
<p><strong>A:</strong> A byte order mark (BOM) consists of the character code
U+FEFF at the beginning of a data stream, where it can be used as a
signature defining the byte order and encoding form, primarily of unmarked
plaintext files. Under some higher level protocols, use of a BOM may be
mandatory (or prohibited) in the Unicode data stream defined in that protocol.</p>
</blockquote>
<p><a href="http://unicode.org/faq/utf_bom.html#BOM" rel="nofollow noreferrer">UTF-8, UTF-16, UTF-32 & BOM</a></p>
<p>The error that I get was:</p>
<pre><code>1: Invalid char `\357' in expression
1: Invalid char `\273' in expression
1: Invalid char `\277' in expression
</code></pre>
|
<p>Try using the <code>mb_chars</code> method from Rails' <a href="http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Chars.html" rel="nofollow noreferrer">ActiveSupport</a> framework:</p>
<pre><code>result = case utf8string.mb_chars
when 'АБВ': 1
when 'ГДИ': 2
when 'ЙКЛ': 3
when 'МНО': 4
else 5
end
</code></pre>
| 46,013
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.