input
stringlengths
51
42.3k
output
stringlengths
18
55k
Ant and the available task - what if something is not available? <p>When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined.</p> <p>When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name.</p> <p>Is there a way to set the property to some value if the resource is <em>not</em> available? I have tried setting the property explicitly before the available check, but then ant complains:</p> <pre> [available] DEPRECATED - used to override an existing property. [available] Build file should not reuse the same property name for different values. </pre>
<p>You can use a condition in combination with not:</p> <p><a href="http://ant.apache.org/manual/Tasks/condition.html">http://ant.apache.org/manual/Tasks/condition.html</a></p> <pre><code> &lt;condition property="fooDoesNotExist"&gt; &lt;not&gt; &lt;available filepath="path/to/foo"/&gt; &lt;/not&gt; &lt;/condition&gt; </code></pre>
Why shouldn't Helpers have html in them? <p>I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?</p> <p>Thanks!</p> <p>-fREW</p>
<p>My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).</p> <p>I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it. </p> <p>Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.</p>
Running subversion under apache and mod_python <p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
<p>It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so:</p> <pre><code>svn --config-dir /home/myuser/.subversion checkout http://example.com/path </code></pre> <p>While not fixing your enviornment, it will at least allow you to have your script run properly...</p>
Reddit's commenting system (hierarchial) <p>For those of you who have looked at Reddit's source code, where exactly is the logic where it manages the comments hierarchial structure?</p> <p>I downloaded the code, but couldn't even find the database structure let alone where the reads and writes are for the commenting.</p> <p>Is it doing updates on lots of comments if someone replies to someone mid-way through a thread?</p>
<p>The class definition for the Comment model is in <a href="https://github.com/reddit/reddit/blob/master/r2/r2/models/link.py#L591" rel="nofollow">r2/models/link.py</a> .</p>
What are the best/most popular ways to do aspect-oriented programming (AOP) in C#/.Net? <p>What are the best/most popular ways to do aspect-oriented programming (AOP) in C#/.Net?</p>
<ul> <li><a href="http://www.castleproject.org/projects/dynamicproxy/" rel="nofollow">DynamicProxy</a> from Castle is probably the most used tool for doing AOP on the CLR.</li> <li><a href="http://www.springframework.net/docs/1.2.0-M1/reference/html/aop.html" rel="nofollow">Spring framework</a> also offers AOP capabilities through its <code>Spring.Aop</code> namespace.</li> </ul>
What's the best practice to fork an open source project? <p>I need to customize an open-source project. The changes are for a specific organization and will not be useful to the public project. The code changes include disabling features not needed by the organization (affecting 5% of the code), customizing other features for the organization (affecting 20% of the code), and adding new custom features (adding about 10% new code).</p> <p>I could start with the current version and customize from there. However, the original project continues to make advances and introduce new features, and I would like to be able to incorporate these improvements as they come along.</p> <p>What's the best way to manage this? Right now, I can only get release versions as they become available, but I should soon have read-only access to the original project's Subversion repository. I'm new to using Subversion repositories, but have them available to use for my code as well.</p>
<p>The best thing to do is not to fork it. Why not figure out how to improve it so it will do what you want it to do and not lose any existing functionality. If code size is an issue, maybe you can spend some of the time you would spend forking it on improving the existing projects efficiency.</p>
Sharepoint: How to set the permission to edit WSS user profile <p>I'm running a SharePoint Application on a MOSS 2007 with a form based user authentication without using the MySite feature. So all the settings on the SSP administration site which only concern the user profile on the MySites should normally not affect the user profile of the application as these should be managed from WSS.</p> <p>But where could I define the settings for the WSS user profiles? At the moment a user can only edit the attributes in his profile which are listed as additional columns for the application's user list (WebsiteAction --> WebisteSettings --> Users and Groups --> All users --> ListSettings). So all other attributes like first, surname, info, title etc. are partly imported form our identity directory (LDAP) but are not editable for the users. </p> <p>So are there any options to define which of the attributes should be editable for the users and which one should not be? It would also be interesting if there are any options to define which LDAP attributes are mapped to the which WSS profile attribute.</p> <p>Bye, Flo</p>
<p>Those things are handled by your shared service provider. So gå there then:</p> <p>User profiles and properties -> View profile properties</p> <p>You can also do all sorts of other stuff regarding profiles, mysites, etc there.</p>
Where to put controller parent class in CakePHP? <p>I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.</p>
<p>In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers/components. For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php. </p> <pre><code>&lt;?php class UtilComponent extends Object { function yourMethod($param) { // logic here....... return $param; } } ?&gt; </code></pre> <p>Then, in your controller classes, you would add:</p> <pre><code>var $components = array('Util'); </code></pre> <p>Then you call the methods like:</p> <pre><code>$this-&gt;Util-&gt;yourMethod($yourparam); </code></pre> <p>More Info:</p> <p><a href="http://book.cakephp.org/view/315/Components">Documentation</a></p>
Source Control for multiple projects/solutions with shared libraries <p>I am currently working on a project to convert a number of Excel VBA powered workbooks to VSTO solutions. All of the workbooks will share a number of class libraries and third party assemblies, in fact most of the work is done in the class libraries. I currently have my folder structure laid out like this.</p> <pre><code>Base Libraries Assemblies Workbooks Workbook1 Workbook2 </code></pre> <p>Each of the workbooks will be its own solution, and the workbook solutions just reference the assemblies in the folder structure. My question is how would you lay out the source control? Would you start the repository at the base? Or would you create a repository for each workbook solution? Would you rearrange the folders? </p> <p>Now that we have the initial development done, we're about to have a bunch of outside developers come on to the project to helps us convert the rest of the workbooks and I really like the idea of them being able to check out from the base directory and having all of the dependencies ready to go. I also worry that there are other concerns that come with having 20+ solutions/projects under one source control repository. </p> <p>I want everything to be as simple as possible for people joining the project but I don't want to sacrifice long term usability. In my mind I've been going back and forth, what's simpler one repository or one repository per solution?</p> <p>I'd appreciate and insight you have, because I'm fresh out. </p> <p>Additional Information: Currently, I am using Mercurial personally, but the project will probably get moved to StarTeam unless I can make some convincing arguments for something else.</p>
<p>You don't mention in your question what source control you are using. As it doesn't sound like you need to limit your outside developers access to the rest of the repository I would not bother with setting up multiple repositories. I would assume that unless your code runs into the millions of lines size that repository size is not an issue.</p> <p>It all depends what functionality your revision control system supports. In subversion you can declare other folders as external and provide a file URL for the content of that folder, this will cause subversion to deal with that folder as a separate repository even though it is within your folder structure.</p>
Show weights in JgraphT <p>I have implemented this Graph: </p> <pre><code>ListenableDirectedWeightedGraph&lt;String, MyWeightedEdge&gt; g = new ListenableDirectedWeightedGraph&lt;String, MyWeightedEdge&gt;(MyWeightedEdge.class); </code></pre> <p>In order to show what the class name says; a simple listenable directed weighted graph. I want to change the label of the edges and instead of the format </p> <pre><code>return "(" + source + " : " + target + ")"; </code></pre> <p>I want it to show the weight of the edge. I realise that all actions on the nodes, e.g. the <code>getEdgesWeight()</code> method, are delegated from the graph and not the edge. How can I show the weight of the edge? Do I have to pass in the Graph to the edge somehow? </p> <p>Any help is appreciated. </p>
<p>I assume that the class MyWeightedEdge already contains a method such as </p> <pre><code>public void setWeight(double weight) </code></pre> <p>If this is indeed the case, then what you need to do is:</p> <p>Derive your own subclass from <em>ListenableDirectedWeightedGraph</em> (e.g., <em>ListenableDirectedWeightedGraph</em>). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class.</p> <p>Create the graph as in your question, but using the new class</p> <pre><code>ListenableDirectedWeightedGraph g = new CustomListenableDirectedWeightedGraph( MyWeightedEdge.class); </code></pre> <p>Override the method <em>setEdgeWeight</em> as follows:</p> <pre><code>public void setEdgeWeight(E e, double weight) { super.setEdgeWeight(e, weight); ((MyWeightedEdge)e).setWeight(weight); } </code></pre> <p>And, last but not least, override the <em>toString</em> method of the class <em>MyWeightedEdge</em> to return the label you want the edge to have (presumably including the weight, which is now available to it).</p> <p>I hope this helps.</p>
Integrate StackOverflow into IDEs? <p>Okay, this is just a crazy idea I have. StackOverflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a StackOverflow plugin for, say, Eclipse? </p> <p>Which features of StackOverflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?</p> <p>EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful.</p>
<p>Following up on Josh's answer. This VS Macro will search StackOverflow for highlighted text in the Visual Studio IDE. Just highlight and press Alt+F1</p> <pre><code>Public Sub SearchStackOverflowForSelectedText() Dim s As String = ActiveWindowSelection().Trim() If s.Length &gt; 0 Then DTE.ItemOperations.Navigate("http://www.stackoverflow.com/search?q=" &amp; _ Web.HttpUtility.UrlEncode(s)) End If End Sub Private Function ActiveWindowSelection() As String If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then Return OutputWindowSelection() End If If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then Return HTMLEditorSelection() End If Return SelectionText(DTE.ActiveWindow.Selection) End Function Private Function HTMLEditorSelection() As String Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object Dim tw As TextWindow = hw.CurrentTabObject Return SelectionText(tw.Selection) End Function Private Function OutputWindowSelection() As String Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) Dim ow As OutputWindow = w.Object Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name) Return SelectionText(owp.TextDocument.Selection) End Function Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String If sel Is Nothing Then Return "" End If If sel.Text.Length = 0 Then SelectWord(sel) End If If sel.Text.Length &lt;= 2 Then Return "" End If Return sel.Text End Function Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection) Dim leftPos As Integer Dim line As Integer Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint() sel.WordLeft(True, 1) line = sel.TextRanges.Item(1).StartPoint.Line leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset pt.MoveToLineAndOffset(line, leftPos) sel.MoveToPoint(pt) sel.WordRight(True, 1) End Sub </code></pre> <p>To install:</p> <ol> <li>go to Tools - Macros - IDE</li> <li>create a new Module with a name of your choice under "MyMacros". Or use an existing module.</li> <li>paste the above code into the module</li> <li>add a reference to the System.Web namespace (for HttpUtility) to the module</li> <li>close the macro IDE window</li> <li>go to Tools - Options - Environment - Keyboard</li> <li>type "google" in the Show Commands Containing textbox. The SearchGoogleForSelectedText macro should show up</li> <li>click in the Press Shortcut Keys textbox, then press ALT+F1</li> <li>click the Assign button</li> <li>click OK</li> </ol> <p>This is all taken from Jeff Atwood's <a href="http://www.codinghorror.com/blog/archives/000428.html">Google Search VS Macro</a> post, just modified to search StackOverflow instead.</p>
Applescriptable mySQL client - low cost or free? <p>Can anyone recommend a MySQL front end client or OS X that is AppleScriptable? Preferably low cost or free.</p>
<p>I would suggest just using the command-line mysql client and using the <code>do shell script</code> command in applescript to invoke it:</p> <pre><code>do shell script "mysql -e 'select * from customer'" </code></pre>
How to search through archived files with Perl <p>What is your preferred method for reading through the contents of zipped directories with Perl ?</p>
<p>There are several modules on CPAN for working with various archive formats (zip, tar, etc.), the one you're probably after is <a href="http://search.cpan.org/~adamk/Archive-Zip-1.24/lib/Archive/Zip.pm" rel="nofollow">Archive::Zip</a>.</p>
DataGrid Edit Problem <p>I have a DataGrid, with an ItemTemplate that has an image and label. In the EditItemTemplate the label is replaced by a textbox. My problem is that the edit template only shows when I click the Edit button the second time. What gives?</p>
<p>Make sure you check for Page.IsPostback before binding your datagrid. It may be the case that you are binding during every page load.</p> <pre><code>If Not Page.IsPostBack() Then DoDataBinding() End If </code></pre>
What is a good alternative for SourceSafe on a USB Drive? <p>I like to keep my source files on a USB drive for the portability. To date I have been using Visual SourceSafe for this purpose. What is a good alternative to VSS that fulfils these criteria:</p> <ul> <li>Entire database can be held on a USB "pen" drive</li> <li>Code / documentation duplicated on local drives</li> <li>Does not require a central server</li> <li>Easy to backup and restore using standard backup tools</li> <li>Integrates with Visual Studio</li> <li>Has a small footprint</li> <li>Easy to clean the database and keep small</li> <li>Compatible with Windows XP, Vista and Vista x64</li> </ul> <p>A good reference on setup would be good too.</p> <h2>UPDATE</h2> <p>I went with Subversion in the end (TortoiseSVN). It has been pretty robust so far so I would recommend it for people with the same problem.</p>
<p>I would use SVN (Subversion). </p> <p>You can use SVN in "file" mode (w/o using the network). combine this with tortoiseSVN, which integrates to explorer, and you have a nice little portable repository.</p> <p>For Visual Studio integration, there is the commercial($49) VisualSVN (which I believe is the setup used to develop StackOverflow).</p> <p>Someone also mentioned AnkhSVN which I haven't used, but some people find it less than satisfying.</p>
How to prevent blank xmlns attributes in output from .NET's XmlDocument? <p>When generating XML from XmlDocument in .NET, a blank <code>xmlns</code> attribute appears the first time an element <em>without</em> an associated namespace is inserted; how can this be prevented?</p> <p>Example:</p> <pre><code>XmlDocument xml = new XmlDocument(); xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0")); xml.DocumentElement.AppendChild(xml.CreateElement("loner")); Console.WriteLine(xml.OuterXml); </code></pre> <p>Output:</p> <pre><code>&lt;root xmlns="whatever:name-space-1.0"&gt;&lt;loner xmlns="" /&gt;&lt;/root&gt; </code></pre> <p><em>Desired</em> Output:</p> <pre><code>&lt;root xmlns="whatever:name-space-1.0"&gt;&lt;loner /&gt;&lt;/root&gt; </code></pre> <p>Is there a solution applicable to the <code>XmlDocument</code> code, not something that occurs <em>after</em> converting the document to a string with <code>OuterXml</code>?</p> <p>My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank <code>xmlns</code> attribute <em>may</em> not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.</p>
<p>Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank <code>xmlns</code> attributes: pass in the root node's namespace when creating any child node you want <em>not</em> to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to <em>also</em> not have prefixes.</p> <p>Fixed Code:</p> <pre><code>XmlDocument xml = new XmlDocument(); xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0")); xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); Console.WriteLine(xml.OuterXml); </code></pre> <p>Thanks everyone to all your answers which led me in the right direction!</p>
How can I script a no-cost notification of batch file errors/returns? <p>I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. </p> <p>Here's the scenario, I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.</p> <p>Here's the 'servstop.txt' file contents:</p> <blockquote> <p>[SC] StartService FAILED 1058:</p> <p>The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.</p> </blockquote> <p>I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058" and the body to contain the entire error message above.</p> <p>I will put my current method in an answer below using a program called blat to send me the result.</p>
<p>Here's how I'm doing this. First I got <a href="http://blat.net" rel="nofollow">blat mail</a> (public domain smtp mailer) and dropped it into d:\blat directory. My Exchange server allows me to email without id/password and just assumes that I am the person in the 'from' field of the blat command.</p> <pre><code>@echo off sc start Alerter &gt;servstop.txt SetLocal EnableDelayedExpansion set content= set subj= for /F "delims=" %%i in (servstop.txt) do set content=!content! %%i for /f "tokens=1 delims=:" %%s in ("%content%") do set subj=%%s d:\blat\blat.exe -body "%content%" -to my-email@foo.bar -f my-email@foo.bar -server smtp.foo.bar -s "Alert Service Start:%subj% " -log d:\blat\blat.log EndLocal </code></pre>
Advantages to Using Private Static Methods <p>When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?</p> <p>Example:</p> <pre><code>foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample")) { string first = GetInnerXml(element, ".//first"); string second = GetInnerXml(element, ".//second"); string third = GetInnerXml(element, ".//third"); } </code></pre> <p>...</p> <pre><code>private static string GetInnerXml(XmlElement element, string nodeName) { return GetInnerXml(element, nodeName, null); } private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue) { XmlNode node = element.SelectSingleNode(nodeName); return node == null ? defaultValue : node.InnerXml; } </code></pre> <p>Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/ms245046.aspx">FxCop rule page</a> on this:</p> <blockquote> <p>After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.</p> </blockquote>
Semantic merge tool <p>Background: In my job, we use SVN, C# and VisualStudio. Part of my task regularly involves global renames. Often I end up with a broken build after renaming something and then merging in changes.</p> <p>The question: is there a solution out there that can look at my changes, notice the global rename and then apply that to the edit that others have made while merging them in?</p> <p>Another way to get much the same effect would be some sort of refactor log and then apply that to the incoming edits.</p> <p>The tool need not be perfect, even if it just noted any references in their edits that referred to something that I have edited would be valuable.</p> <p><strong>Edit</strong> I'm aware of VS's refactor tools. What I'm looking for is something that will allow me to, after I have refactored my working copy, apply the same refactorings to other peoples edits that I now need to merge in.</p> <p>The ideal solution would be to make sure there are no outstanding edits when I do the refactoring, but that would prevent anyone else from getting anything done for the next week or more. (Because they would have to sync every half hour or so for the next week)</p>
<p>There is a commercial tool for exactly that use case called <a href="http://www.semanticmerge.com/" rel="nofollow">Semantic Merge</a>. They provide a 15-day free trial, open source projects may use it for free (<a href="http://www.semanticmerge.com/pricing.html" rel="nofollow">contact the support</a>).</p>
Mathematica Downvalue Lhs <p>Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in</p> <p>For example:</p> <pre><code>a[1]=2; a[2]=3; </code></pre> <p><code>BuiltInIDoNotKnowOf[a]</code> returns <code>{1,2}</code></p>
<p>This is like <code>keys()</code> in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say <code>a[1] = 2</code> and you have a hash. [1] To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:</p> <pre><code>keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *) </code></pre> <p>(Or the following pure function version is supposedly slightly faster:</p> <pre><code>keys = DownValues[#][[All,1,1,1]]&amp;; (* Keys of a hash/dictionary. *) </code></pre> <p>)</p> <p>Either way, <code>keys[a]</code> now returns what you want. (You can get the values of the hash with <code>a /@ keys[a]</code>.) If you want to allow for higher arity hashes, like <code>a[1,2]=5; a[3,4]=6</code> then you can use this:</p> <pre><code>SetAttributes[removeHead, {HoldAll}]; removeHead[h_[args___]] := {args} keys[f_] := removeHead @@@ DownValues[f][[All,1]] </code></pre> <p>Which returns <code>{{1,2}, {3,4}}</code>. (In that case you can get the hash values with <code>a @@@ keys[a]</code>.)</p> <p>Note that <code>DownValues</code> by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do <code>Sort@keys[f]</code>. So I would actually recommend this version:</p> <pre><code>keys = DownValues[#,Sort-&gt;False][[All,1,1,1]]&amp;; </code></pre> <p>Interestingly, there is no mention of the <code>Sort</code> option in the <code>DownValues</code> documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.) <hr/></p> <p>Footnotes:</p> <p>[1] What's really handy is that you can mix and match that with function definitions. Like:</p> <pre><code>fib[0] = 1; fib[1] = 1; fib[n_] := fib[n-1] + fib[n-2] </code></pre> <p>You can then add memoization by changing that last line to</p> <pre><code>fib[n_] := fib[n] = fib[n-1] + fib[n-2] </code></pre> <p>which says to cache the answer for all subsequent calls.</p>
Will my index be used if all columns are not used? <p>I have an index on columns A, B, C, D of table T</p> <p>I have a query that pulls from T with A, B, C in the WHERE clause.</p> <p>Will the index be used or will a separate index be needed that only includes A, B, C?</p>
<p>It depends!</p> <pre><code>WHERE A like '%x%' and B = 1 and C = 1 // WHERE A = 1 OR B = 1 OR C = 1 // WHERE DateAdd(dd, 1, A) = '2008-01-01' AND B = 1 AND C = 1 </code></pre> <p>These will not rely on the index, because the index is not useful.</p> <p>Click on "display estimated execution plan" to confirm potential index usage.</p>
Tips for budgeting QA hours <p>Sometimes for QA it gets difficult to budget and track the QA hours as a person can spend enormous amount of time retesting the defects and performing regression if any. We can take ,as an example, a web application with 50 use cases. </p> <p>What are some tips for budgeting QA hours?</p>
<p>Past history is a good indication of future performance. How long did the last regression take?</p>
Reproducing the blocked exe "unblock" option in file properties in windows 2003 <p>When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".</p> <p>I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. </p> <p>But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.</p> <p>How can I get the unblock to appear on my exe so I can test this functionality?</p>
<p>This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:</p> <pre><code>[ZoneTransfer] ZoneId=3 </code></pre> <p>The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.</p> <p>Zone.Identifier.txt:</p> <pre><code>[ZoneTransfer] ZoneId=3 </code></pre> <p>Command:</p> <pre><code>more Zone.Identifier.txt &gt; file.exe:Zone.Identifier </code></pre> <p>Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.</p> <p>It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run.</p>
Structure of projects in version control - .NET specific <p>This post is similar to <a href="http://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">this previously asked question.</a> I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?</p> <hr> <p>Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app_data, etc.). But I want my repository structure to look like...</p> <pre> StackOverflowIsAwesome /trunk /bin /app_data /tags /branches </pre> <p>So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work?</p>
<p>We went with a very simplistic approach:</p> <p><strong>File Structure:</strong></p> <ul> <li>Solution Folder (contains solution file, build scripts, maybe more?) <ul> <li>Project Folder</li> <li>Project Folder 2</li> <li>References (contains shared assemblies for the solution).</li> </ul></li> </ul> <p>Then we just check the entire solution folder's contents into our repository. We use one repository for each solution. I'm not sure if this is the optimal way to organize the solution, but it works for us.</p> <p>Also, we branch at the highest level, not per project.</p>
What are the different types of indexes, what are the benefits of each? <p>What are the different types of indexes, what are the benefits of each?</p> <p>I heard of covering and clustered indexes, are there more? Where would you use them?</p>
<ul> <li>Unique - Guarantees unique values for the column(or set of columns) included in the index</li> <li>Covering - Includes all of the columns that are used in a particular query (or set of queries), allowing the database to use only the index and not actually have to look at the table data to retrieve the results</li> <li>Clustered - This is way in which the actual data is ordered on the disk, which means if a query uses the clustered index for looking up the values, it does not have to take the additional step of looking up the actual table row for any data not included in the index.</li> </ul>
Prevent visual studio creating browse info (.ncb) files <p>Is there a way to prevent VS2008 creating browse info file files for C++ projects.<br /> I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.</p> <p>EDIT - it's also needed for go to declaration/definition</p>
<p>In the project properties, you will find the browse information under:</p> <p>Configuration Properties -> C/C++ -> Browse Information</p> <p>Just tell it not to generate browse information. All it is used for is quickly browsing between code components (like using 'Go to Definition') and so forth. I personally like being able to quickly jump between the components, but if it is adding unnecessary time to your compile don't worry about turning it off.</p>
What is the best approach to centralzing error messages in an application? <p>All throughout an application wherever error messages (or other user messages) are used I typically hard-code a string. Obviosly this can be really bad (especially when you may have to come back and localize an app). What is the best approach to centralize these strings? A static class? Constants? An XML File? Or a combination (like creating a static class with constants that are used to read from an xml file).</p>
<p>Create the strings in a resource file. You can then localise by adding additional resource files.</p> <p>Check out <a href="http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx" rel="nofollow">http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx</a></p>
How to configure Tomcat JULI logging to roll log files? <p>I have a several webapps which use java.util.logging. Tomcat 5.5 is configured to use the Juli logger so that each webapp has its own log file. The problem is that Juli does not have properties for maximum file size and file count. Using Juli the files will grow unbounded and only roll at the end of the day. Also, an unlimited number of log files are retained.</p> <p>You can see the FileHandler properties on this page - <a href="http://tomcat.apache.org/tomcat-5.5-doc/logging.html">Apache Tomcat 5.5 Documentation</a><br /> There is no limit or count property (the following lines do nothing)<br /> <code>org.apache.juli.FileHandler.limit=102400</code><br /> <code>org.apache.juli.FileHandler.count=5</code></p> <p>Without changing the webapps is there a way to get unique log files for each application with some type of bounds on the log file sizes?</p> <p><strong>UPDATE:</strong> The solution I found was not use the Juli logger at all! <code>java.util.logging.FileHandler.limit=102400</code><br /> <code>java.util.logging.FileHandler.count=5</code> </p> <p>Thanks,</p> <p>Greg</p>
<p><strong>Update:</strong> I see your point now after reading more. "Tomcat's JULI implementation is not intended to be a fully-featured logging libary, only a simple bridge to those libraries. However, JULI does provide several properties for configuring the its handlers. These are listed below." Funny that they say that the default java.util.Logging implementation is too limited then they work around it by providing an even more limiting implementation.</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/logging/FileHandler.html" rel="nofollow">FileHandler javadocs</a></p> <ul> <li>java.util.logging.FileHandler.limit specifies an approximate maximum amount to write (in bytes) to any one file. If this is zero, then there is no limit. (Defaults to no limit).</li> <li>java.util.logging.FileHandler.count specifies how many output files to cycle through (defaults to 1). </li> </ul> <p>for the one file per web app, you probably want to separate it by the name of the logger and it depends on how the loggers are created for each app. If they're based off the package or class name then you can filter the logs based on that. It looks like the sample on the link you provided tells how to do this</p> <pre><code>org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \ 2localhost.org.apache.juli.FileHandler </code></pre>
Does XSLT have a Split() function? <p>I have a string in a node and I'd like to split the string on '?' and return the last item in the array.</p> <p>For example, in the block below:</p> <pre><code>&lt;a&gt; &lt;xsl:attribute name="href"&gt; /newpage.aspx?&lt;xsl:value-of select="someNode"/&gt; &lt;/xsl:attribute&gt; Link text &lt;/a&gt; </code></pre> <p>I'd like to split the <code>someNode</code> value.</p> <p>Edit: Here's the VB.Net that I use to load the Xsl for my Asp.Net page:</p> <pre><code>Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl") Dim myXsltSettings As New XsltSettings() Dim myXMLResolver As New XmlUrlResolver() myXsltSettings.EnableScript = True myXsltSettings.EnableDocumentFunction = True myXslDoc = New XslCompiledTransform(False) myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver) Dim myStringBuilder As New StringBuilder() Dim myXmlWriter As XmlWriter = Nothing Dim myXmlWriterSettings As New XmlWriterSettings() myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto myXmlWriterSettings.Indent = True myXmlWriterSettings.OmitXmlDeclaration = True myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings) myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter) Return myStringBuilder.ToString() </code></pre> <p><strong>Update:</strong> here's <a href="http://gist.github.com/360186">an example of splitting XML on a particular node</a></p>
<p>Use a recursive method:</p> <pre><code>&lt;xsl:template name="output-tokens"&gt; &lt;xsl:param name="list" /&gt; &lt;xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" /&gt; &lt;xsl:variable name="first" select="substring-before($newlist, ' ')" /&gt; &lt;xsl:variable name="remaining" select="substring-after($newlist, ' ')" /&gt; &lt;id&gt; &lt;xsl:value-of select="$first" /&gt; &lt;/id&gt; &lt;xsl:if test="$remaining"&gt; &lt;xsl:call-template name="output-tokens"&gt; &lt;xsl:with-param name="list" select="$remaining" /&gt; &lt;/xsl:call-template&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre>
How to have a Label inherite a Composite's GC in SWT <p>I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites. </p> <p>I wrote the following code:</p> <pre><code>composite.addListener (SWT.Paint, new Listener () { public void handleEvent (Event e) { GC gc = e.gc; Rectangle rect = composite.getClientArea (); Color color1 = new Color (display, 0, 0, 0); Color color2 = new Color (display, 255, 255, 255); gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true); } }); </code></pre> <p>This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite. </p> <p>In these areas, the background is just the plain gray you get when drawing an empty canvas. </p> <p>I've tried forcing the Labels to inherit the background like so:</p> <pre><code>label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either </code></pre> <p>But this leaves me with the same default gray and no gradient behind the components on top of the Composite. </p> <p>Any suggestions for getting the gradient to be the background of each element?</p> <p>I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements. </p> <p>Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient. </p> <p>[edit] I uploaded an example upto twitpic <a href="http://twitpic.com/d5qz" rel="nofollow">here</a>.</p> <p>Thanks,</p> <p>Brian Gianforcaro</p>
<p>Use <strong>composite.setBackgroundMode(SWT.INHERIT_DEFAULT)</strong>, but do not paint the composite directly - paint an image and set it as the background image using <strong>composite.setBackgroundImage(Image)</strong>. Unless I'm missing a trick, this means you only have to regenerate the image when the composite is resized too.</p> <p>You should be able to cut'n'paste this code as is to see what I mean:</p> <pre><code>import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /** * SWT composite with transparent label * * @author McDowell */ public class Sweet { private Image imageGradient; private Label label; private Composite composite; private void createComponents(Shell parent) { composite = new Composite(parent, SWT.NONE); composite.addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { changeImage(); } }); composite.setLayout(new FormLayout()); composite.setBackgroundMode(SWT.INHERIT_DEFAULT); label = new Label(composite, SWT.None); label.setText("Hello, World!"); } private void changeImage() { Image oldImage = imageGradient; Display display = composite.getDisplay(); Rectangle rect = composite.getClientArea(); imageGradient = new Image(display, rect.width, rect.height); GC gc = new GC(imageGradient); try { Color color1 = new Color(display, 200, 200, 255); try { Color color2 = new Color(display, 255, 255, 255); try { gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height, true); } finally { color2.dispose(); } } finally { color1.dispose(); } } finally { gc.dispose(); } composite.setBackgroundImage(imageGradient); if (oldImage != null) { oldImage.dispose(); } } private void openShell(Display display) { Shell shell = new Shell(display); try { shell.setSize(200, 100); shell.setLayout(new FillLayout()); createComponents(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } finally { if (!shell.isDisposed()) { shell.dispose(); } } } public void run() { Display display = Display.getDefault(); try { openShell(display); } finally { display.dispose(); } } public void dispose() { if (imageGradient != null) { imageGradient.dispose(); } } public static void main(String[] args) { Sweet sweet = new Sweet(); try { sweet.run(); } finally { sweet.dispose(); } } } </code></pre>
Long compile times and lost productivity <p>How long can a compile time get before it starts becoming a <a href="http://xkcd.com/303/">distraction</a> to you?</p> <p>For me:</p> <ul> <li>&lt;1 sec, I don't notice</li> <li>>1 min, I'm going for coffee</li> <li>>10 min, S.O. here I come</li> </ul> <p>(any other programming task that involves letting the computer do it's thing also apropos)</p>
<p>Certainly its never short enough not to <a href="http://xkcd.com/303/" rel="nofollow">distract me from working</a>.</p>
How to check for null values before doing .AddDays() in SSRS? <p>I have the following as the value for my textbox in SSRS report: </p> <pre><code> =iif(IsNothing(Fields!MyDate.Value), "", Format(Fields!MyDate.Value.AddDays(30), "MMMM dd, yyyy")) </code></pre> <p>It gives me an "#Error" every time MyDate is null.</p> <p>How do i work around this?</p> <p>UPDATE:</p> <p>i wrote this custom function, it got rid of the error, but returns January 31, 0001 when null date is passed.</p> <pre><code>Public Shared Function NewDate(myDate as DateTime, days as integer) AS string IF ISNOTHING(myDate) OR ISDBNULL(myDate) Then NewDate = " " ELSE NewDate = Format(myDate.AddDays(days), "MMMM dd, yyyy") END IF End Function </code></pre> <p>@<a href="#136854" rel="nofollow">Matt Hamilton</a>: DateAdd("d", 30,Fields!MyDate.Value)</p>
<p>The problem, of course, is that VB's IIF statement evaluates both sides regardless of the outcome. So even if your field is null it's still evaluating the "Value.DateAdd" call.</p> <p>If I recall correctly, SSRS has its own "DateAdd" function that you can use instead. So you can do something like this (check the documentation 'coz this is from memory):</p> <pre><code>=Iif(IsNothing(Fields!MyDate.Value), "", Format(DateAdd("d", 30, Fields!MyDate.Value), "MMMM dd, yyyy")) </code></pre>
Sell me on const correctness <p>So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:</p> <ol> <li><p>It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change <em>another</em> function somewhere else. Is this something that just gets easier with experience?</p></li> <li><p>Are the benefits of using const <em>really</em> enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?</p></li> </ol> <p>I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.</p> <p><strong>EDIT</strong>: I'm told that the correct term is const correctness, so that's what the title is now.</p>
<p>This is the definitive article on "const correctness": <a href="https://isocpp.org/wiki/faq/const-correctness">https://isocpp.org/wiki/faq/const-correctness</a>.</p> <p>In a nutshell, using const is good practice because...</p> <ol> <li>It protects you from accidentally changing variables that aren't intended be changed, </li> <li>It protects you from making accidental variable assignments, and </li> <li><p>The compiler can optimize it. For instance, you are protected from</p> <pre><code>if( x = y ) // whoops, meant if( x == y ) </code></pre></li> </ol> <p>At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good.</p> <p>You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest.</p>
GUI Design: How do you do it? <p>Do you draw your windows before constructing them? What do you use?</p> <p>I've tried the Pencil plugin for FF. I've tried MS Visio. I've tried paper &amp; pencil. I've tried Designer Vista. etc. etc. etc.</p> <p>I'm currently leaning toward paper &amp; pencil, but what about you; what's your preference?</p>
<p>Balsamiq Mockups looks pretty nice</p> <p><a href="http://www.balsamiq.com/products/mockups" rel="nofollow">http://www.balsamiq.com/products/mockups</a></p>
What's the best way to read and parse a large text file over the network? <p>I have a problem which requires me to parse several log files from a remote machine. There are a few complications: 1) The file may be in use 2) The files can be quite large (100mb+) 3) Each entry may be multi-line</p> <p>To solve the in-use issue, I need to copy it first. I'm currently copying it directly from the remote machine to the local machine, and parsing it there. That leads to issue 2. Since the files are quite large copying it locally can take quite a while.</p> <p>To enhance parsing time, I'd like to make the parser multi-threaded, but that makes dealing with multi-lined entries a bit trickier. </p> <p>The two main issues are: 1) How do i speed up the file transfer (Compression?, Is transferring locally even neccessary?, Can I read an in use file some other way?) 2) How do i deal with multi-line entries when splitting up the lines among threads?</p> <p>UPDATE: The reason I didnt do the obvious parse on the server reason is that I want to have as little cpu impact as possible. I don't want to affect the performance of the system im testing.</p>
<p>If you are reading a sequential file you want to read it in line by line over the network. You need a transfer method capable of streaming. You'll need to review your IO streaming technology to figure this out.</p> <p>Large IO operations like this won't benefit much by multithreading since you can probably process the items as fast as you can read them over the network.</p> <p>Your other great option is to put the log parser on the server, and download the results.</p>
Too many "pattern suffixes" - design smell? <p>I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:</p> <p><a href="http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern" rel="nofollow">http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern</a></p> <p>Is this a design smell? Should I impose a limit on this number? </p> <p>I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)</p> <p>All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.</p>
<p>A good tip is: Your class public API (and that includes it's name) should reveal intention, not implementation. I (as a client) don't care whether you implemented the builder pattern or the factory pattern.</p> <p>Not only the class name looks bad, it also tells nothing about what it does. It's name is based on its implementation and internal structure.</p> <p>I rarely use a pattern name in a class, with the exception of (sometimes) Factories.</p> <p>Edit:</p> <p>Found an interesting <a href="http://www.codinghorror.com/blog/archives/000553.html">article</a> about naming on Coding Horror, please check it out!</p>
What's the difference between the open source licences <p>I read all the licenses, and frankly I am kindda baffled by the many choices available. I know some relax the limitation of the license so that open source stuff can be used in commercial applications.<br> But other than that, why are there so many licenses out there? Is there any <strong>major</strong> difference between them. How do I go about choosing the right one for me?</p> <p>To not make this too general and complicated I'll just throw in some licenses here and you guys can tell me what's the main point of each</p> <ol> <li>gpl (v2/v3)</li> <li>Apache license</li> <li>BSD license</li> <li>The MIT license</li> <li>The mozilla license</li> </ol> <p>Edit: (Pointed out to me, by 3 people, no less) whether or not a license allows a user to use the software in a commercial software is covered <a href="http://stackoverflow.com/questions/137048/how-do-i-tell-if-i-can-re-use-a-free-software-library-in-a-commercial-app">in this question</a>. But, as stated, I'm also looking if someone can shed light on the difference other than that. In context of choosing one for my own project rather than in the context of whether or not I can use the software within my own commercial software ( like I believe the other thread is about )</p>
<p>Yes, there are important differences among the different licenses available. To explain them here, as you asked, would be like reinventing the wheel.</p> <p>I suggest looking at the site @raphael75 suggested: <a href="http://choosealicense.com/" rel="nofollow">Choose an open source license</a></p>
Is there a way to add a Subversion section to the right click menu for TextMate? <p>I'd like to be able to click on a file to revert it, or check in a directory, etc. It would be much more convenient to have these available from the right click menu.</p>
<p>Have you seen this?</p> <p><strong>ProjectPlus</strong></p> <p>ProjectPlus is a plug-in for TextMate which extends the functionality of project-related features.</p> <p>Feature list: * SCM status badges: * Support for SVN, Git, Mercurial, Bazaar and Svk * Displayed in the project file list and the window proxy icon </p> <p><a href="http://ciaranwal.sh/projectplus" rel="nofollow">http://ciaranwal.sh/projectplus</a></p>
What are the dangers of making a method virtual? <p>I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.</p> <p>I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?</p>
<p>Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:</p> <pre><code>class Base { public Base() { InitializeComponent(); } protected virtual void InitializeComponent() { ... } } class Derived : Base { private Button button1; public Derived() : base() { button1 = new Button(); } protected override void InitializeComponent() { button1.Text = "I'm gonna throw a null reference exception" } } </code></pre> <p>The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.</p>
Could a truly random number be generated using pings to psuedo-randomly selected IP addresses? <p>The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device.</p> <p>This was the only suggestion which didn't depend on non-commodity-class hardware.</p> <p>Subsequently nobody would put their reputation on the line to argue definitively for or against it. </p> <p>Anyone care to make a stand for or against. If so, how about a mention as to a possible implementation?</p>
<p>I'll put my rep on the line (at least, 2 points of it per downvote).</p> <p>No.</p> <p>A malicious machine on your network could use ARP spoofing (or a number of other techniques) to intercept your pings and reply to them after certain periods. They would then not only know what your random numbers are, they would control them.</p> <p>Of course there's still the question of how deterministic your local network is, so it might not be as easy as all that in practice. But since you get no benefit from pinging random IPs on the internet, you might just as well draw entropy from ethernet traffic. </p> <p>Drawing entropy from devices attached to your machine is a well-studied principle, and the pros and cons of various kinds of devices and methods of measuring can be e.g. stolen from the implementation of /dev/random.</p> <p>[<strong>Edit</strong>: as a general principle, when working in the fundamentals of security (and the only practical needs for significant quantities of truly random data are security-related) you MUST assume that a fantastically well-resourced, determined attacker will do everything in their power to break your system.</p> <p>For practical security, you can assume that nobody wants your PGP key that badly, and settle for a trade-off of security against cost. But when inventing algorithms and techniques, you need to give them the strongest security guarantees that they could ever possibly face. Since I can believe that someone, somewhere, might want someone else's private key badly enough do build this bit of kit to defeat your proposal, I can't accept it as an advance over current best practice. AFAIK /dev/random follows fairly close to best practice for generating truly random data on a cheap home PC]</p> <p>[<strong>Another edit</strong>: it has suggested in comments that (1) it is true of any TRNG that the physical process could be influenced, and (2) that security concerns don't apply here anyway.</p> <p>The answer to (1) is that it's possible on any realistic hardware to do so much better than ping response times, and gather more entropy faster, that this proposal is a non-solution. In CS terms, obviously you can't generate random numbers on a deterministic machine, which is what provoked the question. But then in CS terms a machine with any external input stream is non-deterministic by definition, so if we're talking about ping then we aren't talking about deterministic machines. So it makes sense to look at the real inputs that real machines have, and consider them as sources of randomness. No matter what your machine, raw ping times are not high on the list of sources available, so they can be ruled out before worrying about good the better ones are. Assuming that a network is not subverted is a much bigger (and unnecessary) assumption than assuming that your own hardware is not subverted.</p> <p>The answer to (2) is philosophical. If you don't mind your random numbers having the property that they can be chosen at whim instead of by chance, then this proposal is OK. But that's not what I understand by the term 'random'. Just because something is inconsistent doesn't mean it's necessarily random.</p> <p>Finally, to address the implementation details of the proposal as requested: assuming you accept ping times as random, you still can't use the unprocessed ping times as RNG output. You don't know their probability distribution, and they certainly aren't uniformly distributed (which is normally what people want from an RNG). </p> <p>So, you need to decide how many bits of entropy per ping you are willing to rely on. Entropy is a precisely-defined mathematical property of a random variable which can reasonably be considered a measure of how 'random' it actually is. In practice, you find a lower bound you're happy with. Then hash together a number of inputs, and convert that into a number of bits of output less than or equal to the total relied-upon entropy of the inputs. 'Total' doesn't necessarily mean sum: if the inputs are statistically independent then it is the sum, but this is unlikely to be the case for pings, so part of your entropy estimate will be to account for correlation. The sophisticated big sister of this hashing operation is called an 'entropy collector', and all good OSes have one.</p> <p>If you're using the data to seed a PRNG, though, and the PRNG can use arbitrarily large seed input, then you don't have to hash because it will do that for you. You still have to estimate entropy if you want to know how 'random' your seed value was - you can use the best PRNG in the world, but its entropy is still limited by the entropy of the seed.]</p>
Is there any way in .NET to programmatically listen to HTTP traffic? <p>I'm using browser automation for testing web sites but I need to verify HTTP requests from the browser (i.e., images, external scripts, XmlHttpRequest objects). Is there a way to programmatically instantiate a proxy for the browser to use in order to see what its sending?</p> <p>I'm already using Fiddler to watch the traffic but I want something that's UI-less that I can use in continuous build integration.</p>
<p>I have briefly looked into the same thing and have considered two solutions (but haven't tried them yet).</p> <p>The first suggestion I have would be to use the HttpListener class (and possibly Webclient or other System.Net http related classes to re-post the requests to your application) as a proxy for the WebBrowser test calls. I have no experience with HttpListener, but it looks like a simple and promising way to proxy calls through to your app.</p> <p>The second suggestion I have is to do what Fiddler does: tap into the WinINET Http stack on your test machine to act as a proxy (with some sort of filter to narrow it down to JUST your WebBrowser's calls). Unforunately, the best example of this I have been able to find is Fiddler itself and the only way I know to get the code is Reflector. It might be possible to get to the Fiddler proxy code another way, but I did not have time to investigate this path fully.</p> <p>HTH!, Richard</p>
NLP: Building (small) corpora, or "Where to get lots of not-too-specialized English-language text files?" <p>Does anyone have a suggestion for where to find archives or collections of everyday English text for use in a small corpus? I have been using Gutenberg Project books for a working prototype, and would like to incorporate more contemporary language. A <a href="http://stackoverflow.com/questions/122595/nlp-qualitatively-positive-vs-negative-sentence#126378">recent answer</a> here pointed indirectly to a great <a href="http://us.imdb.com/Reviews/" rel="nofollow">archive of usenet movie reviews</a>, which hadn't occurred to me, and is very good. For this particular program technical usenet archives or programming mailing lists would tilt the results and be hard to analyze, but any kind of general blog text, or chat transcripts, or anything that may have been useful to others, would be very helpful. Also, a partial or downloadable research corpus that isn't too marked-up, or some heuristic for finding an appropriate subset of wikipedia articles, or any other idea, is very appreciated.</p> <p>(BTW, I am being a good citizen w/r/t downloading, using a deliberately slow script that is not demanding on servers hosting such material, in case you perceive a moral hazard in pointing me to something enormous.)</p> <p><strong>UPDATE</strong>: User S0rin points out that wikipedia requests no crawling and provides <a href="http://en.wikipedia.org/wiki/Special:Export" rel="nofollow">this export tool</a> instead. Project Gutenberg has a policy specified <a href="http://www.gutenberg.org/wiki/Gutenberg:Information%5FAbout%5FRobot%5FAccess%5Fto%5Four%5FPages" rel="nofollow">here</a>, bottom line, try not to crawl, but if you need to: "Configure your robot to wait at least 2 seconds between requests."</p> <p><strong>UPDATE 2</strong> The wikpedia dumps are the way to go, thanks to the answerers who pointed them out. I ended up using the English version from here: <a href="http://download.wikimedia.org/enwiki/20090306/" rel="nofollow">http://download.wikimedia.org/enwiki/20090306/</a> , and a Spanish dump about half the size. They are some work to clean up, but well worth it, and they contain a lot of useful data in the links.</p> <p><hr /></p>
<ul> <li>Use the <a href="http://en.wikipedia.org/wiki/Wikipedia:Database_download">Wikipedia dumps</a> <ul> <li>needs lots of cleanup</li> </ul></li> <li>See if anything in <a href="http://prdownloads.sourceforge.net/nltk/nltk-data-0.9.5.zip">nltk-data</a> helps you <ul> <li>the corpora are usually quite small</li> </ul></li> <li>the <a href="http://wacky.sslmit.unibo.it/doku.php?id=start">Wacky</a> people have some free corpora <ul> <li>tagged</li> <li>you can spider your own corpus using their toolkit</li> </ul></li> <li><a href="http://www.statmt.org/europarl/">Europarl</a> is free and the basis of pretty much every academic MT system <ul> <li>spoken language, translated</li> </ul></li> <li>The <a href="http://trec.nist.gov/data/reuters/reuters.html">Reuters Corpora</a> are free of charge, but only available on CD</li> </ul> <p>You can always get your own, but be warned: HTML pages often need heavy cleanup, so restrict yourself to RSS feeds.</p> <p>If you do this commercially, the <a href="http://www.ldc.upenn.edu/">LDC</a> might be a viable alternative.</p>
What's the difference between a worker thread and an I/O thread? <p>Looking at the processmodel element in the Web.Config there are two attributes.</p> <pre><code>maxWorkerThreads="25" maxIoThreads="25" </code></pre> <p>What is the difference between worker threads and I/O threads?</p>
<p>Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data.</p> <p>I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput.</p> <p>Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used.</p> <p>Worker threads are threads upon which regular "work" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput.</p> <p>[Edit]: I also found this link which is particularly relevant to this question: <a href="http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx">http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx</a></p>
Why is my stored procedure receiving a null parameter? <p>Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as <code>null</code>, even though it's definitely being sent <code>1</code>.</p> <p>The Delphi code uses a TADOQuery to execute the stored procedure (anonymized):</p> <pre><code> ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy"; ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction()); // other parameters all set similarly ADOQuery1.ExecSQL; </code></pre> <p><code>Integer(SomeFunction())</code> currently always returns 1 - I checked with the debugger.</p> <p>However, in my stored proc ( altered for debug purposes ):</p> <pre><code>create procedure MyStoredProcedure ( @Foo int, @Bar int, @Baz int, @Qux int, @Smang int, @Jimmy varchar(20) ) as begin -- temp debug if ( @Foo is null ) begin insert into TempLog values ( "oh crap" ) end -- do the rest of the stuff here.. end </code></pre> <p><code>TempLog</code> does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?).</p> <p>Here's an example trace from profiler:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p3 int set @p3=NULL exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int', @p3 output,1,1,1,0,200 select @p3 </code></pre> <p>This looks a little strange to me. Notice that it's using @p3 <em>and</em> @P3 - could this be causing my issue? </p> <p>The other strange thing is that it seems to depend on which TADOConnection I use. </p> <p>The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection.</p> <p>If instead of using this connection, I first do this:</p> <pre><code>ConnectionNew := TADOQuery.Create(ConnectionOld.Owner); ConnectionNew.ConnectionString := ConnectionOld.ConnectionString; TADOQuery1.Connection := ConnectionNew; </code></pre> <p>Then the issue does not occur! The trace from this situation is this:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p1 int set @p1=64 exec sp_prepare @p1 output, N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', 1 select @p1 SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF exec sp_unprepare 64 SET NO_BROWSETABLE OFF exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', 1,1,1,3,0,'400.00' </code></pre> <p>Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this?</p> <p>Does anyone have any ideas?</p> <p><strong>Edit:</strong> <a href="http://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214">Update below</a> (didn't want to make this question any longer :P)</p>
<p>In my programs, I have <strong>lots</strong> of code very similar to your first snippet, and I haven't encountered this problem.</p> <p>Is that <strong>actually</strong> your code, or is that how you've represented the problem for us to understand? Is the text for the SQL stored in your DFM or populated dynamically? </p> <p>I was wondering if perhaps somehow the Params property of the query had already got a list of parameters defined/cached, in the IDE, and that might explain why P1 was being seen as output (which is almost certainly causing your NULL problem).</p> <p>Just before you set the ParamByName.Value, try</p> <pre> ParamByName("Foo").ParamType=ptInput; </pre> <p>I'm not sure why you changing the connection string would also fix this, unless it's resetting the internal sense of the parameters for that query.</p> <p>Under TSQLQuery, the Params property of a query gets reset/recreated whenever the SQL.Text value is changed (I'm not sure if that's true for a TADOQuery mind you), so that first snippet of yours ought to have caused any existing Params information to have been dropped.</p> <p>If the 'ParamByname.ParamType' suggestion above does fix it for you, then surely there's something happening to the query elsewhere (at create-time? on the form?) that is causing it to think Foo is an output parameter...</p> <p>does that help at all? :-)</p>
What is the best web based Subversion client? <p>What is your favorite web-based svn client? I'd like one that supports commits via the web.</p> <p>One tool per post please! Please include platform and notable features (e.g. read-write support).</p> <p>I'm referring to browser-based clients that users would go to like any other website--not accessing the repo via http.</p>
<p>All web clients that I know of are read only, meaning that you can only browse the files, make diffs, set up RSS feeds, but you can not modify the repository in any way.</p> <p><a href="http://www.websvn.info/" rel="nofollow">WebSVN</a> is the PHP interface that I installed at the office and that I use everyday. It has everything I have ever needed. <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a> is quite good also, but it is a complete project management suite, since it has also features like bug tracking or release planning. It is able to manage only one repository for each installation (but you can have multiple ones on the same machine). Many others are available, you can find <a href="http://en.wikipedia.org/wiki/Comparison_of_Subversion_clients" rel="nofollow">a list</a> on Wikipedia (look for 'web-based').</p> <p>The http interface available via WebDAV can be used with a common browser, you can see any revision with adding query param ?p=@REV. However you can customize the page layouts, as is explained <a href="http://svnbook.red-bean.com/nightly/en/svn.serverconfig.httpd.html#svn.serverconfig.httpd.extra.browsing.xslt" rel="nofollow">here</a>.</p>
Is programming a subset of math? <p>I've heard many times that all programming is really a subset of math. <a href="http://c2.com/cgi-bin/wiki?ProgrammingIsMath">Some suggest</a> that OO, at its roots, is mathematically based, but I don't get the connection, aside from some obvious examples:</p> <ul> <li>using induction to prove a recursive algorithm,</li> <li>formal correctness proofs,</li> <li>functional languages,</li> <li>lambda calculus,</li> <li>asymptotic complexity,</li> <li>DFAs, NFAs, Turing Machines, and theoretical computation in general,</li> <li>and the fact that everything on the box is binary.</li> </ul> <p>I know math is very important to programming, but I struggle with this "subset" view. In what ways is programming a subset of math?</p> <p>I'm looking for an explanation that might have relevance to enterprise/OO development, if there is a strong enough connection, that is.</p>
<p>It's math in the sense that it requires abstract thought about algorithms etc.<br /> It's engineering when it involves planning schedules, deliverables, testing.<br /> It's art when you have no idea how it's going to eventually turn out.</p>
How can I perform a HEAD request with the mechanize library? <p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p> <p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p> <p>Any suggestions how I could accomplish this?</p>
<p>Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:</p> <pre><code>import mechanize class HeadRequest(mechanize.Request): def get_method(self): return "HEAD" request = HeadRequest("http://www.example.com/") response = mechanize.urlopen(request) print response.info() </code></pre>
Encapsulating SQL in a named_scope <p>I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.</p>
<p>While you can put any SQL you like in the conditions of a named scope, if you then call <code>find_by_sql</code> then the 'scopes' get thrown away.</p> <p>Given:</p> <pre><code>class Item # Anything you can put in an sql WHERE you can put here named_scope :mine, :conditions=&gt;'user_id = 12345 and IS_A_NINJA() = 1' end </code></pre> <p>This works (it just sticks the SQL string in there - if you have more than one they get joined with AND)</p> <pre><code>Item.mine.find :all =&gt; SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1) </code></pre> <p>However, this doesn't</p> <pre><code>Items.mine.find_by_sql 'select * from items limit 1' =&gt; select * from items limit 1 </code></pre> <p>So the answer is "No". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together.<br /> When you create normal queries, the <code>select</code>, <code>joins</code>, <code>conditions</code>, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how <code>with_scope</code> and <code>named_scope</code> work).</p> <p>With <code>find_by_sql</code> however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work.</p>
Where does Console.WriteLine go in ASP.NET? <p>In a J2EE application (like one running in WebSphere), when I use <code>System.out.println()</code>, my text goes to standard out, which is mapped to a file by the WebSphere admin console.</p> <p>In an ASP.NET application (like one running in IIS), where does the output of <code>Console.WriteLine()</code> go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here?</p> <p>I'm <strong>not asking</strong> if I should log there (I use log4net), but where does the output go? My best info came from this <a href="http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html">discussion</a> where they say <code>Console.SetOut()</code> can change the <code>TextWriter</code>, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.</p>
<p>If you use <code>System.Diagnostics.Debug.WriteLine(...)</code> instead of <code>Console.WriteLine()</code>, then you can see the results in the <strong>Output</strong> window of Visual Studio.</p>
Which distro of Linux is best suited for Java web apps? <p>There are so many Linux distributions to choose from! What is the "best" linux flavor for a web hosting environment running primarily: Apache HTTP, Tomcat or JBoss, MySQL and Alfresco (not necessarily all in the same instance).</p> <p>Are there any significant differences in terms of ease of administration and configuration, performance and stability for such applications, etc.?</p> <p>What would you recommend?</p> <p>Thanks! Mike</p>
<p>They all use similar tools to administer things like webmin, and sshd.</p> <p>What are you more familiar with. Red Hat based systems(fedora, mandriva) or Debian based systems(Ubuntu). This family divide will determine a few things. First rpm packaging vs deb packaging.</p> <p>You also want to look at the level of activity of the project. Mandriva and Ubuntu are two examples of active distributions. That try to keep up with current releases of software.</p> <p>Other than that most stuff performs with little difference.</p>
How do I upload a HTML form with a username, password, multiple file uploads and then process it with PHP? <p>How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.</p>
<p>first off check out these pages on PHP.net</p> <ol> <li><a href="http://us3.php.net/features.file-upload">file upload info</a></li> <li><a href="http://us3.php.net/manual/en/function.move-uploaded-file.php"><code>move_uploaded_file</code></a></li> </ol> <p>But to get you started here's a couple stub files.</p> <p><strong>uploadForm.html</strong></p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;form action="processStuff.php" enctype="multipart/form-data" method="POST"&gt; username: &lt;input type="text" name="username" /&gt; password: &lt;input type="password" name="password" /&gt; &lt;p&gt; &lt;input type="file" name="uploadFile[]" /&gt;&lt;br /&gt; &lt;input type="file" name="uploadFile[]" /&gt;&lt;br /&gt; &lt;input type="file" name="uploadFile[]" /&gt;&lt;br /&gt; &lt;!-- Add as many of these as you want --&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="submit" /&gt; &lt;/p&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>processStuff.php</strong></p> <pre><code>&lt;pre&gt; &lt;?php echo '&lt;h2&gt;Username &amp; password&lt;/h2&gt;' echo "Username: {$_POST['username']}\nPassword: {$_POST['password']}"; echo '&lt;hr /&gt;'; echo '&lt;h2&gt;Uploaded files&lt;/h2&gt;' foreach($_FILES['uploadFile']['tmp_name'] as $i =&gt; $tempUploadPath) { if (empty($tempUploadPath)) { // this &lt;input type="file" /&gt; was "blank"... no file selected } else { // a file was uploaded echo '&lt;strong&gt;A file named "', $_FILES['uploadFile']['name'][$i], "\" was uploaded&lt;/strong&gt;\n"; echo "\ttemporarily stored at: ", $tempUploadPath, "\n"; echo "\tmime type: ", $_FILES['uploadFile']['type'][$i], "\n"; echo "\tsize: ", $_FILES['uploadFile']['size'][$i], " bytes\n"; echo "\terror code", ((empty($_FILES['uploadFile']['size'][$i]) ? '&lt;em&gt;no errror&lt;/em&gt;' : $_FILES['uploadFile']['size'][$i])), "\n\n"; // do something useful with the uploaded file // access it via $tempUploadPath and use move_uploaded_file() to move // it out of the temp path before you manipulate it in any way!!!!! // see http://us3.php.net/features.file-upload // and http://us3.php.net/manual/en/function.move-uploaded-file.php } } ?&gt; &lt;/pre&gt; </code></pre> <p>The HTML file shows how to set the <code>enctype</code> of the <code>&lt;form&gt;</code> &amp; the second form show you how to access the submitted username &amp; password &amp; finally how to loop thru every uploaded file.</p> <p>As noted you MUST move the file(s) ASAP. They're uploaded to a temp location and the system will delete them unless you deal with them. So move 'em somewhere first then do whatever you need w/ them.</p> <p>Hoep this helps</p> <p>Arin</p>
Moving WCF service from IIS to a Windows service <p>We have an existing WCF service that makes use of wsDualHttpBinding to enable callbacks to the client. I am considering moving it to netTcpBinding for better performance, but I'm quite wary of moving away from the IIS-hosted service (a "comfort zone" we currently enjoy) into having our own Windows service to host it. I was hoping we could still host this on IIS 7 but Win2K8 won't be reality for us for some time.</p> <p>What things should I watch out for when creating our own Windows service to host our WCF service? Things like lifetime management and request throttling are features that come free with IIS hosting so I'd also like to know how we can effectively host our service on our own without the convenience of having IIS do the hard work for us. Thanks! :)</p>
<p>So as you cannot host using WAS there are a couple of things to realise.</p> <ul> <li>If the service crashes it doesn't restart by default (although you can change this in service properties)</li> <li>IIS will recycle the application pool if it hangs or grows too big; you must do this yourself if you want the same sort of reliability.</li> <li>You must create an account for the service to run under, or use one of the default services. Resit the temptation to run the service as SYSTEM or under an administrator account; if you want to use a built in account use NETWORK SERVICE.</li> <li>It becomes harder to debug in situ.</li> <li>Consider using a error logger such as log4net</li> </ul> <p>Having said that I deployed a WCF/Windows service combination for a customer 9 months ago; it's heavily used and hasn't died once.</p> <p>You can <a href="http://www.iserviceoriented.com/blog/post/Configuring+Performance+Options+-+WCF+Gotcha+3.aspx">request throttle</a> in a Windows service, it's part of the WCF configuration. Note the defaults are very low, it is likely you will have to increase these. </p>
How to change directory security attributes using InstallShield? <p>I'd like to change the security attribute of a directory that InstallShield creates under the <code>CSIDL_COMMON_APPDATA</code> - can someone please advise on how to do that during the installation process?</p> <p>It's a script-defined folder.</p> <p>Thank you.</p>
<p>Under InstallShield 2008 it's </p> <pre><code>Installation Designer &gt; Components &gt; [somecomponent] &gt; Destination Permissions </code></pre> <p>Note that the directory properties are attached to the component, while individual File permissions are set under the 'Files' node</p> <p>This assumes you are letting InstallShield / Windows Installer handle directory creation. If you're creating the directory in a script then things start getting tricky if you need to ensure a clean uninstall.</p>
How can you automate Firefox from C# application? <p>Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE. </p>
<p><a href="http://watin.sourceforge.net/" rel="nofollow">WatiN</a> has support for Firefox.</p>
How does cherrypy handle user threads? <p>I'm working on a django app right and I'm using cherrypy as the server. Cherrypy creates a new thread for every page view. I'd like to be able to access all of these threads (threads responsible for talking to django) from within any of them. More specifically I'd like to be able to access the thread_data for each of these threads from within any of them. Is this possible? If so, how do I do it?</p>
<p>CherryPy's wsgiserver doesn't create a new thread for every request--it uses a pool. Each of those worker threads is a subclass of threading.Thread, so all of them should be accessible via threading.enumerate().</p> <p>However, if you're talking specifically about cherrypy.thread_data, that's something else: a threading.local. If you're using a recent version of Python, then all that's coded in C and you (probably rightfully) don't have cross-thread access to it from Python. If you <em>really</em> need it and <strong>really</strong> know what you're doing, the best technique is usually to stick an additional reference to such things in a global container at the same time that they are inserted into the thread_data structure. I recommend dicts with weakrefs as keys for those global containers--there are enough Python ORM's that use them for connection pools (see my own Geniusql, for example) that you should be able to learn how to implement them fairly easily.</p>
How to make XMLHttpRequest work over HTTPS on Firefox? <p>When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.</p> <p>But when sent over HTTPS, different browsers gave different results:</p> <p>On Firefox 3.0.2: - The GET request doesn't reach the web server.</p> <p>On IE 7: - The GET request reached the web server.</p> <p>Does this have something to do with Firefox 3 getting stricter with untrusted certificates? Is there a way around this?</p> <p>I've already added the URL as an exception in Firefox's Certificate Manager. The error console doesn't report any error. I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.</p> <p>Using both absolute and relative URL path doesn't work.</p> <p>Here's the code snippet:</p> <pre><code> var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); xmlHttp.send(null); } catch (e) { alert('Error sending HTTP GET request!'); return false; } </code></pre> <p>Thanks, Kenneth</p>
<p>Try placing your closure after the open:</p> <pre><code>// send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); } catch (e) { alert('Error sending HTTP GET request!'); return false; } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // Then send it. xmlHttp.send(null); </code></pre> <p>A little googling found confirmation: <a href="http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html" rel="nofollow">http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html</a></p> <p>Although that document says to attach the function after .send(null), I've always attached after open.</p>
How to create a resizable CDialog in MFC? <p>I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?</p>
<p>In addition to setting the style to <code>WS_THICKFRAME</code>, you'll probably also want to have a system to move and resize the controls in a dialog as the dialog is resized. For my own personal use I've created a base class to replace CDialog that has this capability. Derive from this class and in your <code>InitDialog</code> function call the <code>AutoMove</code> function for each child control to define how much it should move and how much it should resize relative to the parent dialog. The size of the dialog in the resource file is used as a minimum size.</p> <p>BaseDialog.h:</p> <pre><code>#if !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_) #define AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_ #if _MSC_VER &gt; 1000 #pragma once #endif // _MSC_VER &gt; 1000 #include &lt;vector&gt; class CBaseDialog : public CDialog { // Construction public: CBaseDialog(UINT nIDTemplate, CWnd* pParent = NULL); // standard constructor void AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBaseDialog) protected: //}}AFX_VIRTUAL protected: //{{AFX_MSG(CBaseDialog) virtual BOOL OnInitDialog(); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: bool m_bShowGripper; // ignored if not WS_THICKFRAME private: struct SMovingChild { HWND m_hWnd; double m_dXMoveFrac; double m_dYMoveFrac; double m_dXSizeFrac; double m_dYSizeFrac; CRect m_rcInitial; }; typedef std::vector&lt;SMovingChild&gt; MovingChildren; MovingChildren m_MovingChildren; CSize m_szInitial; CSize m_szMinimum; HWND m_hGripper; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_) </code></pre> <p>BaseDialog.cpp:</p> <pre><code>#include "stdafx.h" #include "BaseDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CBaseDialog::CBaseDialog(UINT nIDTemplate, CWnd* pParent /*=NULL*/) : CDialog(nIDTemplate, pParent), m_bShowGripper(true), m_szMinimum(0, 0), m_hGripper(NULL) { } BEGIN_MESSAGE_MAP(CBaseDialog, CDialog) //{{AFX_MSG_MAP(CBaseDialog) ON_WM_GETMINMAXINFO() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CBaseDialog::AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct) { ASSERT((dXMovePct + dXSizePct) &lt;= 100.0); // can't use more than 100% of the resize for the child ASSERT((dYMovePct + dYSizePct) &lt;= 100.0); // can't use more than 100% of the resize for the child SMovingChild s; GetDlgItem(iID, &amp;s.m_hWnd); ASSERT(s.m_hWnd != NULL); s.m_dXMoveFrac = dXMovePct / 100.0; s.m_dYMoveFrac = dYMovePct / 100.0; s.m_dXSizeFrac = dXSizePct / 100.0; s.m_dYSizeFrac = dYSizePct / 100.0; ::GetWindowRect(s.m_hWnd, &amp;s.m_rcInitial); ScreenToClient(s.m_rcInitial); m_MovingChildren.push_back(s); } BOOL CBaseDialog::OnInitDialog() { CDialog::OnInitDialog(); // use the initial dialog size as the default minimum if ((m_szMinimum.cx == 0) &amp;&amp; (m_szMinimum.cy == 0)) { CRect rcWindow; GetWindowRect(rcWindow); m_szMinimum = rcWindow.Size(); } // keep the initial size of the client area as a baseline for moving/sizing controls CRect rcClient; GetClientRect(rcClient); m_szInitial = rcClient.Size(); // create a gripper in the bottom-right corner if (m_bShowGripper &amp;&amp; ((GetStyle() &amp; WS_THICKFRAME) != 0)) { SMovingChild s; s.m_rcInitial.SetRect(-GetSystemMetrics(SM_CXVSCROLL), -GetSystemMetrics(SM_CYHSCROLL), 0, 0); s.m_rcInitial.OffsetRect(rcClient.BottomRight()); m_hGripper = CreateWindow(_T("Scrollbar"), _T("size"), WS_CHILD | WS_VISIBLE | SBS_SIZEGRIP, s.m_rcInitial.left, s.m_rcInitial.top, s.m_rcInitial.Width(), s.m_rcInitial.Height(), m_hWnd, NULL, AfxGetInstanceHandle(), NULL); ASSERT(m_hGripper != NULL); if (m_hGripper != NULL) { s.m_hWnd = m_hGripper; s.m_dXMoveFrac = 1.0; s.m_dYMoveFrac = 1.0; s.m_dXSizeFrac = 0.0; s.m_dYSizeFrac = 0.0; m_MovingChildren.push_back(s); // put the gripper first in the z-order so it paints first and doesn't obscure other controls ::SetWindowPos(m_hGripper, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); } } return TRUE; // return TRUE unless you set the focus to a control } void CBaseDialog::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { CDialog::OnGetMinMaxInfo(lpMMI); if (lpMMI-&gt;ptMinTrackSize.x &lt; m_szMinimum.cx) lpMMI-&gt;ptMinTrackSize.x = m_szMinimum.cx; if (lpMMI-&gt;ptMinTrackSize.y &lt; m_szMinimum.cy) lpMMI-&gt;ptMinTrackSize.y = m_szMinimum.cy; } void CBaseDialog::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); int iXDelta = cx - m_szInitial.cx; int iYDelta = cy - m_szInitial.cy; HDWP hDefer = NULL; for (MovingChildren::iterator p = m_MovingChildren.begin(); p != m_MovingChildren.end(); ++p) { if (p-&gt;m_hWnd != NULL) { CRect rcNew(p-&gt;m_rcInitial); rcNew.OffsetRect(int(iXDelta * p-&gt;m_dXMoveFrac), int(iYDelta * p-&gt;m_dYMoveFrac)); rcNew.right += int(iXDelta * p-&gt;m_dXSizeFrac); rcNew.bottom += int(iYDelta * p-&gt;m_dYSizeFrac); if (hDefer == NULL) hDefer = BeginDeferWindowPos(m_MovingChildren.size()); UINT uFlags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER; if ((p-&gt;m_dXSizeFrac != 0.0) || (p-&gt;m_dYSizeFrac != 0.0)) uFlags |= SWP_NOCOPYBITS; DeferWindowPos(hDefer, p-&gt;m_hWnd, NULL, rcNew.left, rcNew.top, rcNew.Width(), rcNew.Height(), uFlags); } } if (hDefer != NULL) EndDeferWindowPos(hDefer); if (m_hGripper != NULL) ::ShowWindow(m_hGripper, (nType == SIZE_MAXIMIZED) ? SW_HIDE : SW_SHOW); } </code></pre>
TFS Build Server drop location error <p>We're using TFS Build Server to ensure that all files checked in by developers are going to compile to a working source tree, cuz there's nothing worse than a broken build!</p> <p>Anyway we've having some problems with the drop location that Build Server wants to use, we keep getting this error:</p> <blockquote> <p>TFS209011: Could not create drop location \build-server\drops\project\BuildNumber. No more connections can be mades to this remote computer at this time because there are already as many connections as the computer can accept</p> </blockquote> <p>Since this is being used in a pilot program at the moment we only have 2 projects which are using the Build Server. I've checked the network share and the allowed number of connections is about 100 so I don't really get what the problem is.</p> <p>Only occationally does the problem raise it's head, quite often we'll not have one for days, and then we'll have a bunch in a row.</p> <p>I can't seem to find much info on this either.</p>
<p>I'm pretty good with TFS - but a dev not a network guy. I would GUESS that while the NETWORK SHARE itself allows 100 connections, is it possible the underlying server it is running on doesn't have some sort of limitation?</p> <p>Have you checked event logs? </p> <p>This problem seems specific enough I would encourage you to post to the official Microsoft forums.</p>
Emulate hard disk in .NET <p>Is there a way to emulate a disk drive in .NET, intercepting read/write/lock operations?<br /> I would like to create something with a front-end similar to <a href="http://en.wikipedia.org/wiki/GMail_Drive" rel="nofollow">GMail Drive</a> in C#.</p> <p>Thanks, Tom</p>
<p>On Linux you can use the Mono.Fuse API (<a href="http://www.jprl.com/Projects/mono-fuse.html" rel="nofollow">http://www.jprl.com/Projects/mono-fuse.html</a>) to implement .NET-based file systems with user-land code.</p>
How can I read the RGB value of a given pixel in Python? <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p> <p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p> <p>It would be so much better if I didn't have to download any additional libraries.</p>
<p>It's probably best to use the <a href="http://www.pythonware.com/products/pil/">Python Image Library</a> to do this which I'm afraid is a separate download.</p> <p>The easiest way to do what you want is via the <a href="http://effbot.org/imagingbook/image.htm">load() method on the Image object</a> which returns a pixel access object which you can manipulate like an array:</p> <pre><code>from PIL import Image im = Image.open("dead_parrot.jpg") #Can be many different formats. pix = im.load() print im.size #Get the width and hight of the image for iterating over print pix[x,y] #Get the RGBA Value of the a pixel of an image pix[x,y] = value # Set the RGBA Value of the image (tuple) </code></pre> <p>Alternatively, look at <a href="http://effbot.org/imagingbook/imagedraw.htm">ImageDraw</a> which gives a much richer API for creating images.</p>
How can I improve CVS performance in a multi-site scenario? <p>I am currently working in a project with developers working on three sites. One of the sites is in Delhi, India while the other two are in Europe. The communication between the European offices and the office in Delhi has poor bandwidth and quite bad latency, and a CVS update from there often takes 5-10 minutes even though only a few files have changed.</p> <p>Is there any good CVS proxies out there, or any neat way of keeping separate CVS servers in sync? Do you have any other tips on how the performance can be improved in this scenario?</p> <p>Unfortunately, we will be stuck with CVS during the scope of this project, so switching to something completely different is not an option in the short-term.</p>
<p>Why isn't switching an option? </p> <p>I would highly recommend to switch to SVN or git instead. And that you do this conversion as soon as possible... like today :)</p> <p>There are even <a href="http://www.google.ca/search?rlz=1C1CHMG_enCA291&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=cvs+to+svn" rel="nofollow">svn tools/guides</a> and <a href="http://www.google.ca/search?hl=en&amp;rlz=1C1CHMG_enCA291&amp;q=cvs+to+git&amp;btnG=Search&amp;meta=" rel="nofollow">git tools/guides</a> out there that will do this CVS conversion for you.</p> <p>I personally use and love SVN for my work, but based on your above description, it sounds like git might be the better option for you.</p>
How to register file types/extensions with a WiX installer? <p>I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.</p> <p>For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.</p>
<p>Unfortunately there's no way to do a "safe" association with Windows Installer. </p> <p>We just write everything out to the registry and then have a separate component that takes over the system-wide default and is only installed if no other application has already registered itself as the default.</p> <p>With Vista there's the new "default programs" interface, again you write everything out to the registry. Here's a complete example that we're using in our installer. (WiX 3.0)</p> <p><strong>Update:</strong> 12 months have passed since my original answer and I have a better understanding of file associations. Rather than writing everything manually I'm now using proper <code>ProgId</code> definitions which improves handling for advertised packages. See the updated code <a href="http://stackoverflow.com/questions/2772452/how-to-register-application-for-existing-file-types-using-wix-installer">posted in response to this question</a>. </p> <pre><code>&lt;Component ....&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities" Name="ApplicationDescription" Value="ACME Foobar XYZ Editor" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities" Name="ApplicationIcon" Value="[APPLICATIONFOLDER]AcmeFoobar.exe,0" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities" Name="ApplicationName" Value="ACME Foobar" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities\DefaultIcon" Value="[APPLICATIONFOLDER]AcmeFoobar.exe,1" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities\FileAssociations" Name=".xyz" Value="AcmeFoobar.Document" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities\MIMEAssociations" Name="application/xyz" Value="AcmeFoobar.Document" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\AcmeFoobar\Capabilities\shell\Open\command" Value="&amp;quot;[APPLICATIONFOLDER]AcmeFoobar.exe&amp;quot; &amp;quot;%1&amp;quot;" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\RegisteredApplications" Name="Acme Foobar" Value="SOFTWARE\AcmeFoobar\Capabilities" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\.xyz" Name="Content Type" Value="application/xyz" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\.xyz\AcmeFoobar.Document\ShellNew" Value="" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\.xyz\OpenWithList\AcmeFoobar.exe" Value="" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\.xyz\OpenWithProgids" Name="AcmeFoobar.Document" Value="" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Applications\AcmeFoobar.exe\SupportedTypes" Name=".xyz" Value="" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\Applications\AcmeFoobar.exe\shell\open" Name="FriendlyAppName" Value="ACME Foobar" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcmeFoobar.exe" Value="[!AcmeFoobar.exe]" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcmeFoobar.exe" Name="Path" Value="[APPLICATIONFOLDER]" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\SystemFileAssociations\.xyz\shell\edit.AcmeFoobar.exe" Value="Edit with ACME Foobar" Type="string" /&gt; &lt;RegistryValue Root="HKLM" Key="SOFTWARE\Classes\SystemFileAssociations\.xyz\shell\edit.AcmeFoobar.exe\command" Value="&amp;quot;[APPLICATIONFOLDER]AcmeFoobar.exe&amp;quot; &amp;quot;%1&amp;quot;" Type="string" /&gt; &lt;/Component&gt; &lt;Component ....&gt; &lt;ProgId Id="AcmeFoobar.Document" Description="ACME XYZ Document"&gt; &lt;Extension Id="pdf" ContentType="application/xyz"&gt; &lt;Verb Id="open" Command="Open" TargetFile="[APPLICATIONFOLDER]AcmeFoobar.exe" Argument="%1" /&gt; &lt;/Extension&gt; &lt;/ProgId&gt; &lt;Condition&gt;&lt;![CDATA[DEFAULTVIEWER=1]]&gt;&lt;/Condition&gt; &lt;/Component&gt; </code></pre>
Compress Script Resources of ASP.Net <p>How do you compress Script Resources of ASP.Net? I saw a file there reached up to 255 KB! I tried finding solutions, but so far it only talks about scripting dynamic and static files. I checked the compression temp folder of IIS and found no compressed scripted resource there. That led me to the conclusion that these files are transferred over with high bandwidth.</p>
<p>If you're running IIS6 the guys at OrcsWeb have a nice wee article -</p> <blockquote> <p><a href="http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx" rel="nofollow">http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx</a></p> </blockquote> <p>We have customers running the port80 software because they get more control:</p> <blockquote> <p><a href="http://www.port80software.com/products/zipenable/" rel="nofollow">http://www.port80software.com/products/zipenable/</a> <a href="http://www.port80software.com/products/httpzip/" rel="nofollow">http://www.port80software.com/products/httpzip/</a></p> </blockquote>
Initializing a static std::map<int, int> in C++ <p>What is the right way of initializing a static map? Do we need a static function that will initialize it? </p>
<p>Using C++11:</p> <pre><code>#include &lt;map&gt; using namespace std; map&lt;int, char&gt; m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; </code></pre> <p>Using <a href="http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html">Boost.Assign</a>:</p> <pre><code>#include &lt;map&gt; #include "boost/assign.hpp" using namespace std; using namespace boost::assign; map&lt;int, char&gt; m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd'); </code></pre>
How unique is the php session id <p>How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?</p>
<p>It's not very unique as shipped. In the default configuration it's the result of a hash of various things including the result of gettimeofday (which isn't terribly unique), but if you're worried, you should configure it to draw some entropy from /dev/urandom, like so</p> <pre><code>ini_set("session.entropy_file", "/dev/urandom"); ini_set("session.entropy_length", "512"); </code></pre> <p>search for "php_session_create_id" in <a href="https://github.com/php/php-src/blob/34792280bcd2210784ba574d52fc3619cc06160d/ext/session/session.c#L279">the code</a> for the actual algorithm they're using.</p> <p>Edited to add: There's a DFA random-number generator seeded by the pid, mixed with the time in usecs. It's not a firm uniqueness condition <a href="http://seclists.org/vuln-dev/2001/Jul/33">especially from a security perspective</a>. Use the entropy config above.</p> <p><strong>Update:</strong> </p> <blockquote> <p>As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default. <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.entropy-file">PHP Manual</a></p> </blockquote>
Vim extension (via Python)? <p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p> <p>What I need ideally is custom command when in command mode. E.g.</p> <p>ESC</p> <p>:do_this</p> <p>:do_that</p>
<p>vim supports scripting in python (and in perl as well, I think).</p> <p>You just have to make sure that the vim distribution you are using has been compiled with python support.</p> <p>If you are using a Linux system, you can download the source and then compile it with</p> <pre><code>./configure --enable-pythoninterp make sudo make install </code></pre> <p>Inside vim, you can type</p> <pre><code>:version </code></pre> <p>to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise).</p> <p>Then, to check the usage of the python module, you can type</p> <pre><code>:help python </code></pre> <p>P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well.</p> <p>P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with </p> <pre><code>:Call MyFunction() </code></pre> <p>Check </p> <pre><code>:help user-functions </code></pre> <p>for details</p>
IE6 freezes due to *server* configuration <p>Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down?</p>
<p>You need to determine the difference between them, so I'd start out with the following:</p> <pre><code>curl -D first.headers -o first.body http://first.example.com curl -D second.headers -o second.body http://second.example.com diff -u first.headers second.headers diff -u first.body second.body </code></pre>
DIV with overflow:auto and a 100% wide table <p>I hope someone might be able to help me here. I've tried to simplify my example as best I can.</p> <p>I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display.</p> <p>Within the DIV I have a table to present some data, and it's width is 100%.</p> <p>When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div.</p> <p>This is IE specific - firefox works perfectly.</p> <p>Full source below. Any help greatly appreciated.</p> <p>Tony</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;Table sizing bug?&lt;/title&gt; &lt;style&gt; #maxsize { position: absolute; left: 5px; right: 5px; top: 5px; bottom: 5px; border: 5px solid silver; overflow: auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div id="maxsize"&gt; &lt;p&gt;This will be fine until such time as the vertical size forces a vertical scroll bar. At this point I'd expect the table to re-size to now take into account of the new vertical scroll bar. Instead, IE7 keeps the table the full size and introduces a horizontal scroll bar. &lt;/p&gt; &lt;table width="100%" cellspacing="0" cellpadding="0" border="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;A&lt;/td&gt; &lt;td&gt;B&lt;/td&gt; &lt;td&gt;C&lt;/td&gt; &lt;td&gt;D&lt;/td&gt; &lt;td&gt;E&lt;/td&gt; &lt;td&gt;F&lt;/td&gt; &lt;td&gt;G&lt;/td&gt; &lt;td&gt;H&lt;/td&gt; &lt;td&gt;I&lt;/td&gt; &lt;td&gt;J&lt;/td&gt; &lt;td&gt;K&lt;/td&gt; &lt;td&gt;L&lt;/td&gt; &lt;td&gt;M&lt;/td&gt; &lt;td&gt;N&lt;/td&gt; &lt;td&gt;O&lt;/td&gt; &lt;td&gt;P&lt;/td&gt; &lt;td&gt;Q&lt;/td&gt; &lt;td&gt;R&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Resize the browser window vertically so this content doesn't fit any more&lt;/p&gt; &lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt; &lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p><strong>added 03/16/10...</strong> thought it might be interesting to point out that GWT's source code points to this question in a comment... <a href="http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&amp;q=%22hack%20to%20account%20for%20the%22%20scrollpanel&amp;sa=N&amp;cd=1&amp;ct=rc&amp;l=48">http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&amp;q=%22hack%20to%20account%20for%20the%22%20scrollpanel&amp;sa=N&amp;cd=1&amp;ct=rc&amp;l=48</a></p>
<p>I had a problem with excessive horizonal bar in IE7. I've used D Carter's solution slighty changed</p> <pre><code>&lt;div style="zoom: 1; overflow: auto;"&gt; &lt;div id="myDiv" style="zoom: 1;"&gt; &lt;table style="width: 100%"... ... &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>To work in IE browser lesser than 7 you need add:</p> <pre><code>&lt;!--[if lt IE 7]&gt;&lt;style&gt; #myDiv { overflow: auto; } &lt;/style&gt;&lt;![endif]--&gt; </code></pre>
How to resolve a .lnk in c# <p>I need to find out the file/directory name that a .lnk is pointing to using c#.</p> <p>What is the simplest way to do this?</p> <p>Thanks.</p>
<p>I wrote this for video browser, it works really well </p> <pre><code>#region Signitures imported from http://pinvoke.net [DllImport("shfolder.dll", CharSet = CharSet.Auto)] internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath); [Flags()] enum SLGP_FLAGS { /// &lt;summary&gt;Retrieves the standard short (8.3 format) file name&lt;/summary&gt; SLGP_SHORTPATH = 0x1, /// &lt;summary&gt;Retrieves the Universal Naming Convention (UNC) path name of the file&lt;/summary&gt; SLGP_UNCPRIORITY = 0x2, /// &lt;summary&gt;Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded&lt;/summary&gt; SLGP_RAWPATH = 0x4 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct WIN32_FIND_DATAW { public uint dwFileAttributes; public long ftCreationTime; public long ftLastAccessTime; public long ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [Flags()] enum SLR_FLAGS { /// &lt;summary&gt; /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set, /// the high-order word of fFlags can be set to a time-out value that specifies the /// maximum amount of time to be spent resolving the link. The function returns if the /// link cannot be resolved within the time-out duration. If the high-order word is set /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out /// duration, in milliseconds. /// &lt;/summary&gt; SLR_NO_UI = 0x1, /// &lt;summary&gt;Obsolete and no longer used&lt;/summary&gt; SLR_ANY_MATCH = 0x2, /// &lt;summary&gt;If the link object has changed, update its path and list of identifiers. /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine /// whether or not the link object has changed.&lt;/summary&gt; SLR_UPDATE = 0x4, /// &lt;summary&gt;Do not update the link information&lt;/summary&gt; SLR_NOUPDATE = 0x8, /// &lt;summary&gt;Do not execute the search heuristics&lt;/summary&gt; SLR_NOSEARCH = 0x10, /// &lt;summary&gt;Do not use distributed link tracking&lt;/summary&gt; SLR_NOTRACK = 0x20, /// &lt;summary&gt;Disable distributed link tracking. By default, distributed link tracking tracks /// removable media across multiple devices based on the volume name. It also uses the /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.&lt;/summary&gt; SLR_NOLINKINFO = 0x40, /// &lt;summary&gt;Call the Microsoft Windows Installer&lt;/summary&gt; SLR_INVOKE_MSI = 0x80 } /// &lt;summary&gt;The IShellLink interface allows Shell links to be created, modified, and resolved&lt;/summary&gt; [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] interface IShellLinkW { /// &lt;summary&gt;Retrieves the path and file name of a Shell link object&lt;/summary&gt; void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags); /// &lt;summary&gt;Retrieves the list of item identifiers for a Shell link object&lt;/summary&gt; void GetIDList(out IntPtr ppidl); /// &lt;summary&gt;Sets the pointer to an item identifier list (PIDL) for a Shell link object.&lt;/summary&gt; void SetIDList(IntPtr pidl); /// &lt;summary&gt;Retrieves the description string for a Shell link object&lt;/summary&gt; void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); /// &lt;summary&gt;Sets the description for a Shell link object. The description can be any application-defined string&lt;/summary&gt; void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); /// &lt;summary&gt;Retrieves the name of the working directory for a Shell link object&lt;/summary&gt; void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); /// &lt;summary&gt;Sets the name of the working directory for a Shell link object&lt;/summary&gt; void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); /// &lt;summary&gt;Retrieves the command-line arguments associated with a Shell link object&lt;/summary&gt; void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); /// &lt;summary&gt;Sets the command-line arguments for a Shell link object&lt;/summary&gt; void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); /// &lt;summary&gt;Retrieves the hot key for a Shell link object&lt;/summary&gt; void GetHotkey(out short pwHotkey); /// &lt;summary&gt;Sets a hot key for a Shell link object&lt;/summary&gt; void SetHotkey(short wHotkey); /// &lt;summary&gt;Retrieves the show command for a Shell link object&lt;/summary&gt; void GetShowCmd(out int piShowCmd); /// &lt;summary&gt;Sets the show command for a Shell link object. The show command sets the initial show state of the window.&lt;/summary&gt; void SetShowCmd(int iShowCmd); /// &lt;summary&gt;Retrieves the location (path and index) of the icon for a Shell link object&lt;/summary&gt; void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); /// &lt;summary&gt;Sets the location (path and index) of the icon for a Shell link object&lt;/summary&gt; void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); /// &lt;summary&gt;Sets the relative path to the Shell link object&lt;/summary&gt; void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); /// &lt;summary&gt;Attempts to find the target of a Shell link, even if it has been moved or renamed&lt;/summary&gt; void Resolve(IntPtr hwnd, SLR_FLAGS fFlags); /// &lt;summary&gt;Sets the path and file name of a Shell link object&lt;/summary&gt; void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport, Guid("0000010c-0000-0000-c000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersist { [PreserveSig] void GetClassID(out Guid pClassID); } [ComImport, Guid("0000010b-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersistFile : IPersist { new void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); [PreserveSig] void Load([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, uint dwMode); [PreserveSig] void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember); [PreserveSig] void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName); [PreserveSig] void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName); } const uint STGM_READ = 0; const int MAX_PATH = 260; // CLSID_ShellLink from ShlGuid.h [ ComImport(), Guid("00021401-0000-0000-C000-000000000046") ] public class ShellLink { } #endregion public static string ResolveShortcut(string filename) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); } </code></pre>
GetExitCodeProcess() returns 128 <p>I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing:</p> <pre><code>STARTUPINFO si; ZeroMemory(&amp;si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; PROCESS_INFORMATION pi; ZeroMemory(&amp;pi, sizeof(pi)); if(!CreateProcess( NULL, // No module name (use command line). "&lt;my command line&gt;", NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. CREATE_SUSPENDED, // Create suspended. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &amp;si, // Pointer to STARTUPINFO structure. &amp;pi)) // Pointer to PROCESS_INFORMATION structure. { // Handle error. } else { // Do something. // Resume the external process thread. DWORD resumeThreadResult = ResumeThread(pi.hThread); // ResumeThread() returns 1 which is OK // (it means that the thread was suspended but then restarted) // Wait for the external process to finish. DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE); // WaitForSingleObject() returns 0 which is OK. // Get the exit code of the external process. DWORD exitCode; if(!GetExitCodeProcess(pi.hProcess, &amp;exitCode)) { // Handle error. } else { // There is no error but exitCode is 128, a value that // doesn't exist in the external process (and even if it // existed it doesn't matter as it isn't being invoked any more) // Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some // sense *if* GetExitCodeProcess() returned FALSE and then I were to // get ERROR_WAIT_NO_CHILDREN with GetLastError() } // PROCESS_INFORMATION handles for process and thread are closed. } </code></pre> <p>External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.)</p> <p>There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it?</p>
<p>Quoting from the MSDN article on <a href="http://msdn.microsoft.com/en-us/library/aa915088.aspx" rel="nofollow">GetExitCodeProcess</a>:</p> <p>The following termination statuses can be returned if the process has terminated:</p> <ul> <li>The exit value specified in the ExitProcess or TerminateProcess function </li> <li>The return value from the main or WinMain function of the process </li> <li>The exception value for an unhandled exception that caused the process to terminate</li> </ul> <p>Given the scenario you described, I think the most likely cause ist the third: An unhandled exception. Have a look at the source of the processes you create.</p>
Experiences with OpenLaszlo? <p>In a <a href="http://stackoverflow.com/questions/112351/recommendations-for-starting-web-programming">related question</a>, I asked about Web Development. I came across something called <a href="http://www.openlaszlo.org/">OpenLaszlo</a> yesterday and thought it looked interesting for doing some website development. The site has a bunch of good information on it and they've got some nice tutorials and such, but being a total novice (as far as web development goes), I'm wondering whether anyone here would recommend this. As I stated in my other question, this is a new world for me and there are a lot of directions I could go. Can you compare/contrast this and other web development you've done? Obviously, this is somewhat subjective, but I haven't heard much about it on SO and I'm hoping to get some opinions on this.</p>
<p>I worked on a website for about a year in which the entire UI was developed in Laszlo. I've also developed AJAX applications using JS frameworks such as JQuery, Prototype and Scriptaculous.</p> <p>In my experience, the total effort required is considerably less when using Laszlo, and the class-based object model helps to keep your code better organised than when using JS frameworks. My only complaints about Laszlo were that: </p> <ul> <li>It "breaks the browser" in terms of support for the back/forward/refresh buttons. This problem also exists with AJAX, but most JS libraries seem to have found a workaround.</li> <li>No support for internationalization, though none of the JS libraries are any better in my experience</li> <li>Relatively small user base/community compared to competitors such as GWT, JQuery, etc.</li> </ul> <p>All in all, I thought OpenLaszlo was a pretty good solution for creating rich web-based user interfaces, and has a number of very novel features, e.g. ability to deploy on multiple runtimes (Flash, DHTML, etc.) without requiring any code changes.</p> <p>Also, I should mention that I haven't used it for almost a year, so it's likely that some progress has been made in recent times on the issues I mentioned above.</p> <h2>Update</h2> <p>5 years since I posted this answer, things have changed considerably. In case anyone is in any doubt, don't use Laszlo, the project is completely moribund.</p>
listing all functions in a python module <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p> <p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p> <p>eg. something like:</p> <pre><code>from somemodule import foo print foo.methods # or whatever is the correct method to call </code></pre>
<p>You can use <code>dir(module)</code> to see all available methods/attributes. Also check out PyDocs.</p>
Writing XML files using XmlTextWriter with ISO-8859-1 encoding <p>I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). </p> <p>I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this:</p> <pre><code>MemoryStream stream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1")); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartDocument(); //Start doc </code></pre> <p>Then I add my Norwegian text like this:</p> <pre><code>xmlTextWriter.WriteCData(myNorwegianText); </code></pre> <p>Then I write the file to disk like this:</p> <pre><code>FileStream myFile = new FileStream(myPath, FileMode.Create); StreamWriter sw = new StreamWriter(myFile); stream.Position = 0; StreamReader sr = new StreamReader(stream); string content = sr.ReadToEnd(); sw.Write(content); sw.Flush(); myFile.Flush(); myFile.Close(); </code></pre> <p>Now the problem is that in the file on this, all the Norwegian characters look funny.</p> <p>I'm probably doing the above in some stupid way. Any suggestions on how to fix it?</p>
<p>Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. </p> <p>If you still want to do the double write, for whatever reason, do one of two things. Either</p> <ol> <li><p>Make sure that the StreamReader and StreamWriter objects you use <em>all</em> use the <em>same</em> encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or</p></li> <li><p>Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.</p></li> </ol>
Balanced Distribution Algorithm <p>I'm working on some code for a loosely coupled cluster. To achieve optimal performance during jobs, I have the cluster remap its data each time a child enters or exits. This will eventually be made optional, but for now it performs its data balancing by default. My balancing is basically just making sure that each child never has more than the average number of files per machine, plus one. The plus one is for the remainder if the division isn't clean. And since the remainder will <em>always</em> be less than the number of children [except 0 case, but we can exclude that], children after a balancing will have at most avg + 1.</p> <p>Everything seems fine, until I realized my algorithm is O(n!). Go down the list of children, find out the avg, remainder, who has too many and who has too few. For each child in the too many list, go through list, send to each child who has too few.</p> <p>Is there a better solution to this? I feel there must be.</p> <p>Edit: Here is some psuedocode to show how i derived O(n!):</p> <pre><code>foreach ( child in children ) { if ( child.dataLoad &gt; avg + 1 ) { foreach ( child2 in children ) { if ( child != child2 &amp;&amp; child2.dataLoad &lt; avg ) { sendLoad(child, child2) } } } } </code></pre> <p>Edit: O(n^2). Foreach n, n => n*n => n^2. I guess I didn't have enough coffee this morning! ;)</p> <p>In the future I'd like to move to a more flexible and resilient distribution method[weights and hueristics], but for now, a uniform distribution of data works.</p>
<p>@<a href="#139914" rel="nofollow">zvrba</a>: You do not even have to sort the list. When traversing the list the second time just move all items with less the average workload to the end of the list (you can keep a pointer to the last item at your first traversal). The order does not have to be perfect, it just changes when the iterators have to be augmented or decreased in your last step.</p> <p><a href="http://stackoverflow.com/questions/139580/balanced-distribution-algorithm#139656">See previous answer</a></p> <p>The last step would look something like:</p> <p>In the second step keep a pointer to the first item with less than average workload in child2 (to prevent the necessity to have a double link list).</p> <pre><code>for each child in list { if child2 == nil then assert("Error in logic"); while child.workload &gt; avg + 1 { sendwork(child, child2, min(avg + 1 - child2.workload, child.workload - (avg + 1))) if child2.workload == avg + 1 then child2 = child2.next; } } </code></pre>
What's the difference between TRUNCATE and DELETE in SQL <p>I wrote up an answer to this question by mistake in response to a question about the difference between DROP and TRUNCATE, but I thought that it's a shame not to share so I'll post my own answer to my own question ... is that even ethical? :)</p> <p>Edit: If your answer is platform specific can you please indicate that.</p>
<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.</p> <p><hr></p> <h1>General Overview</h1> <p>If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.</p> <p>Various system-specific issues have to be considered, as detailed below.</p> <p><hr></p> <h1>Statement type</h1> <p>Delete is DML, Truncate is DDL</p> <p><hr></p> <h1>Commit and Rollback</h1> <p>Variable by vendor</p> <p><strong>SQL*Server</strong></p> <p>Truncate can be rolled back.</p> <p><strong>PostgreSQL</strong></p> <p>Truncate can be rolled back.</p> <p><strong>Oracle</strong></p> <p>Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.</p> <p>However, see Flashback below.</p> <p><hr></p> <h1>Space reclamation</h1> <p>Delete does not recover space, Truncate recovers space</p> <p><strong>Oracle</strong></p> <p>If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.</p> <p><hr></p> <h1>Row scope</h1> <p>Delete can remove only some rows. Truncate removes all rows.</p> <p><strong>Oracle</strong></p> <p>When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.</p> <p><hr></p> <h1>Object types</h1> <p>Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)</p> <p><hr></p> <h1>Data Object Identity</h1> <p><strong>Oracle</strong></p> <p>Delete does not affect the data object id, but truncate assigns a new data object id <em>unless</em> there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.</p> <p><hr></p> <h1>Flashback (Oracle)</h1> <p>Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.</p> <p>However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition</p> <p><a href="http://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle">Use of FLASHBACK in Oracle</a> <a href="http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638">http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638</a></p> <p><hr></p> <h1>Privileges</h1> <p>Variable</p> <p><strong>Oracle</strong></p> <p>Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.</p> <p><hr></p> <h1>Redo/Undo</h1> <p>Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.</p> <p><hr></p> <h1>Indexes</h1> <p><strong>Oracle</strong></p> <p>A truncate operation renders unusable indexes usable again. Delete does not.</p> <p><hr></p> <h1>Foreign Keys</h1> <p>A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.</p> <p><hr></p> <h1>Table Locking</h1> <p><strong>Oracle</strong></p> <p>Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.</p> <p><hr></p> <h1>Triggers</h1> <p>DML triggers do not fire on a truncate.</p> <p><strong>Oracle</strong></p> <p>DDL triggers are available.</p> <p><hr></p> <h1>Remote Execution</h1> <p><strong>Oracle</strong></p> <p>Truncate cannot be issued over a database link.</p> <p><hr></p> <h1>Identity Columns</h1> <p><strong>SQL*Server</strong></p> <p>Truncate resets the sequence for IDENTITY column types, delete does not.</p>
When writing XML, is it better to hand write it, or to use a generator such as simpleXML in PHP? <p>I have normally hand written xml like this:</p> <pre><code>&lt;tag&gt;&lt;?= $value ?&gt;&lt;/tag&gt; </code></pre> <p>Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?</p>
<p>Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using.</p> <p>Good XML tools also save a bunch of repetitive typing of tags.</p>
Data in a table with carriage return? <p>In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.</p> <p>Eg:</p> <pre><code>insert into table values ('test1 test2 test3 test4'); </code></pre> <p>When I retrieve it, I get the message in a line </p> <p>test1 test2 test3 test4</p> <p>The carriage return is treated as a single character.</p> <p>Is there way to get the carriage returns or its just the way its going to be stored?</p> <p>Thanks for the help guys!!!</p> <p>Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.</p> <p>I return the data to the app development (C++) and may be some data or report viewer.</p> <p>I don't want to manipulate on the data.</p>
<p>You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns.</p> <p>Right click in the query window -> Results To -> Results To Text</p> <p>Run your query again.</p>
Does the latest release May 2008 of .NET enterprise library have the updater app block? <p>Does the latest version of the enterprise library (<a href="http://msdn.microsoft.com/en-us/library/cc512464.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc512464.aspx</a>) come with the updater application block?</p>
<p>Looks like it doesn't:</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc511823.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc511823.aspx</a></p> <p>It's now in the 'Archived Application Blocks' section of the MSDN docs.</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc485231.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc485231.aspx</a></p>
Are there alternatives to CGI (and do I really need one)? <p>I am designing an application that is going to consist of 3-4 services that run as separate processes and are linked by a suitable IPC. The system is going to have a web interface and I want to use whatever webserver is there.</p> <p>The web interface should be accessed under some URL that allows to have other URLs on the same webserver doing totally different things. I'm planning to use the path below that URL to specify what the web interface should do. It has facilities for use by other applications over the net and for humans to interact with in a browser.</p> <p>Off the cuff, I'd work as follows:</p> <ul> <li>make the webserver fire up a CGI process for every request it receives (like SetHandler in Apache)</li> <li>let the CGI connect to the IPC</li> <li>let it get whatever it needs from the backend services</li> <li>let the CGI return HTML / XML and whatever HTTP Status based on the services' answers</li> </ul> <p>Now, what I really want is to avoid the first two steps, or if I can't, avoid the second one, because I'm afraid that I'm wasting performance on unneccesary overhead (the requests coming from other applications might be frequent).</p> <p>PHP, for example, can open persistent connections to a MySQL database that survive the script's runtime and don't need to be recreated next time, though I don't know how they actually do it. Also, as I understand it, the Apache modules are loaded once when the server starts, so that might remove the first step but would tie me to Apache.</p> <p>So, what are good ways to hook a handler for specific URLs into different webservers? I don't want to handle the HTTP, otherwise I might just use a proxy setup to a second server, but it just seems to be so reinventing-the-wheel. If you think, CGI is fine and have examples where it handles large numbers of request of a similar structure, please let me know.</p>
<p>OK, I overlooked this previously. Explaining my question here brought me onto it:</p> <blockquote> <p>Instead of creating a new process for every request, FastCGI can use a single persistent process which handles many requests over its lifetime. -- <a href="http://en.wikipedia.org/wiki/FastCGI" rel="nofollow">Wikipedia: FastCGI</a></p> </blockquote>
How do I change the Status labels in Bugzilla <p>I don't want to change how the Status field works I just want to change the labels to the states that the old system uses. (the old systems consists of spreadsheets and paper :P <br> We are using 3.0</p> <pre> * UNCONFIRMED --> PRELIMARY * NEW --> DESIGN REVIEW * ASSIGNED --> STR1 * RESOLVED --> STR2 * REOPEN * VERIIFED --> BMR * CLOSED --> TCG </pre>
<p>If you log into the bugzilla system as an administrator you'll see on the bottom a link that says "Field Values", click that, on the next page you'll see "Resolution", go there then click on the resolution you'd like to change,</p>
Possible causes of Java VM EXCEPTION_ACCESS_VIOLATION? <p>When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts?</p> <p>Edit: there is a native component, this is an SWT application on win32.</p>
<p>Most of the times this is a bug in the VM. But it can be caused by any native code (e.g. JNI calls).</p> <p>The hs_err_pidXXX.log file should contain some information about where the problem happened.</p> <p>You can also check the "Heap" section inside the file. Many of the VM bugs are caused by the garbage collection (expecially in older VMs). This section should show you if the garbage was running at the time of the crash. Also this section shows, if some sections of the heap are filled (the percentage numbers). </p> <p>The VM is also much more likely to crash in a low memory situation than otherwise.</p>
Where should a Subversion repository be? <p>Should it be on the development servers or a Subversion server?</p> <p>I suppose this could be expanded to any client-server version control system.</p>
<p>The physical repository should be on a stable system that gets regular backups. </p> <p>Generally, a development server does not fit this description... it may be acceptable to put the apache server on the dev server and host the files remotely on a stable, backed-up file server (though there are a number of pitfalls with this approach) if you are unable to get additional server resources. Hosting it on the dev server may be fine if you have an aggressive backup system to protect your code...</p> <p>Just keep in mind that dev servers are prone to configuration changes, being blown-away, or otherwise mucked with that could take down your repo at a critical moment.</p>
Client/JS Framework for "Unsaved Data" Protection? <p>We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).</p> <p>I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?</p>
<p>One piece of the puzzle:</p> <pre><code>/** * Determines if a form is dirty by comparing the current value of each element * with its default value. * * @param {Form} form the form to be checked. * @return {Boolean} &lt;code&gt;true&lt;/code&gt; if the form is dirty, &lt;code&gt;false&lt;/code&gt; * otherwise. */ function formIsDirty(form) { for (var i = 0; i &lt; form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j &lt; element.options.length; j++) { if (element.options[j].selected != element.options[j].defaultSelected) { return true; } } } } return false; } </code></pre> <p><a href="http://developer.mozilla.org/en/DOM/window.onbeforeunload">And another</a>:</p> <pre><code>window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someFormOfInterest"])) { // For IE and Firefox if (e) { e.returnValue = "You have unsaved changes."; } // For Safari return "You have unsaved changes."; } }; </code></pre> <p>Wrap it all up, and what do you get?</p> <pre><code>var confirmExitIfModified = (function() { function formIsDirty(form) { // ...as above } return function(form, message) { window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms[form])) { // For IE and Firefox if (e) { e.returnValue = message; } // For Safari return message; } }; }; })(); confirmExitIfModified("someForm", "You have unsaved changes."); </code></pre> <p>You'll probably also want to change the registration of the <code>beforeunload</code> event handler to use <code>LIBRARY_OF_CHOICE</code>'s event registration.</p>
Base constructor in C# - Which gets called first? <p>Which gets called first - the base constructor or "other stuff here"?</p> <pre><code>public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } </code></pre>
<p>Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code:</p> <pre><code>public class BaseClass { private string sentenceOne = null; // A public BaseClass() { sentenceOne = "The quick brown fox"; // B } } public class SubClass : BaseClass { private string sentenceTwo = null; // C public SubClass() { sentenceTwo = "jumps over the lazy dog"; // D } } </code></pre> <p>Order of execution is: C, A, B, D.</p> <p>Check out these 2 msdn articles:</p> <ul> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx">Why do initializers run in the opposite order as constructors? Part One</a></li> <li><a href="http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx">Why do initializers run in the opposite order as constructors? Part Two</a></li> </ul>
Workaround for J2ME Hessian limitations? <p>The official J2ME implementation of Hessian seems to have serious limitations : complex objects are not supported.<br> This limitation is not mentioned anywhere on the online documentation, but if you google "hessian j2me" you will find posts about this problem. No solutions found with google though. Does anyone have a solution for this problem ? Is there an alternate implementation of Hessian for J2ME ? <br> I would like to avoid getting strings from Hessian and then do some JSON/XML parsing to get objects...</p>
<p>This is somewhat confusing as a Hessian is a matrix of mixed second partial derivatives, and a library that couldn't handle complex numbers would indeed be a problem.</p> <p>Why'd they have to reuse a well-established name with other meanings?</p>
What is the best way to store a large amount of text in a SQL server table? <p>What is the best way to store a large amount of text in a table in SQL server?</p> <p>Is varchar(max) reliable?</p>
<p>In SQL 2005 and higher, VARCHAR(MAX) is indeed the preferred method. The TEXT type is still available, but primarily for backward compatibility with SQL 2000 and lower.</p>
NSIS get path of current installer file that is running <p>Is there an NSIS var to get the path of the currently running installer?</p>
<p>Found it: $EXEPATH</p>
Firebug - how can I run multiline scripts or create a new JavaScript file? <p>Is there a way in Firebug to start a new script file to apply to page? Basically I want to do work like I'd normally do on the Firebug console but be able to to paste in multi-line functions, etc. It doesn't seem like the console is amenable to that.</p>
<p>Down in the lower-right corner of the FireBug UI you should see a red square icon with an up arrow. Use that and stretch it to a size you like.</p> <p><hr /></p> <p><img src="http://i160.photobucket.com/albums/t162/JasonBunting/FireBug1.gif"> <br /><br /> <img src="http://i160.photobucket.com/albums/t162/JasonBunting/FireBug2.gif"></p>
Is it possible to compile .NET IL code to machine code? <p>I would like to distribute my .NET programs without the .NET framework. Is it possible to compile a .NET program to machine code?</p>
<p>Remotesoft has one: <a href="http://www.remotesoft.com/linker/">Salamander .NET Linker</a></p> <p>I don't have any experience with it though.</p>
How do I test if another installation is already in progress? <p>Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?</p> <p>[Update 2]</p> <p>Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:</p> <pre><code>using System.Threading; [...] /// &lt;summary&gt; /// Wait (up to a timeout) for the MSI installer service to become free. /// &lt;/summary&gt; /// &lt;returns&gt; /// Returns true for a successful wait, when the installer service has become free. /// Returns false when waiting for the installer service has exceeded the timeout. /// &lt;/returns&gt; public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime) { // The _MSIExecute mutex is used by the MSI installer service to serialize installations // and prevent multiple MSI based installations happening at the same time. // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx const string installerServiceMutexName = "Global\\_MSIExecute"; try { Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName, System.Security.AccessControl.MutexRights.Synchronize); bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false); MSIExecuteMutex.ReleaseMutex(); return waitSuccess; } catch (WaitHandleCannotBeOpenedException) { // Mutex doesn't exist, do nothing } catch (ObjectDisposedException) { // Mutex was disposed between opening it and attempting to wait on it, do nothing } return true; } </code></pre>
<p>See the description of the <a href="http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx">_MSIExecute Mutex</a> on MSDN.</p>
How to avoid SSIS FTP task from failing when there are no files to download? <p>I'm using SQL Server 2005, and creating ftp tasks within SSIS. </p> <p>Sometimes there will be files to ftp over, sometimes not. If there are no files, I don't want the task nor the package to fail. I've changed the arrow going from the ftp task to the next to "completion", so the package runs through. I've changed the allowed number of errors to 4 (because there are 4 ftp tasks, and any of the 4 directories may or may not have files). </p> <p>But, when I run the package from a job in agent, it marks the job as failing. Since this will be running every 15 minutes, I don't want a bunch of red x's in my job history, which will cause us to not see a problem when it really does occur. </p> <p>How do I set the properties in the ftp task so that not finding files to ftp is not a failure? The operation I am using is "Send files".</p> <p>Here is some more information: the files are on a server that I don't have any access through except ftp. And, I don't know the filenames ahead of time. The user can call them whatever they want. So I can't check for specific files, nor, I think, can I check at all. Except through using the ftp connection and tasks based upon that connection. The files are on a remote server, and I want to copy them over to my server, to get them from that remote server.</p> <p>I can shell a command level ftp in a script task. Perhaps that is what I need to use instead of a ftp task. (I have changed to use the ftp command line, with a parameter file, called from a script task. It gives no errors when there are no files to get. I think this solution is going to work for me. I'm creating the parameter file dynamically, which means I don't need to have connection information in the plain text file, but rather can be stored in my configuration file, which is in a more secure location.)</p>
<p>I understand that you have found an answer to your question. This is for other users who might stumble upon this question. Here is one possible way of achieving this. <code>Script Task</code> can be used to find the list of files present in an FTP folder path for a given pattern (say <code>*.txt</code>). Below example shows how this can be done.</p> <p><strong>Step-by-step process:</strong></p> <ol> <li><p>On the SSIS package, create an <code>FTP Connection</code> named <strong>FTP</strong> and also create <strong>5</strong> variables as shown in screenshot #<strong>1</strong>. Variable <code>RemotePath</code> contains the FTP folder path; <code>LocalPath</code> contains the folder where the files will be downloaed to; <code>FilePattern</code> contains the file pattern to find the list of files to download from FTP server; <code>FileName</code> will be populated by the <code>Foreach loop container</code> but to avoid FTP task design time error, it can be populated with <strong>/</strong> or the <code>DelayValidation</code> property on the FTP Task can be set to <strong>True</strong>.</p></li> <li><p>On the SSIS package, place a <code>Script Task</code>, <code>Foreach Loop container</code> and <code>FTP Task</code> within the <code>Foreach Loop container</code> as shown in screenshots #<strong>2</strong>.</p></li> <li><p>Replace the <code>Main()</code> method within the <code>Script Task</code> with the code under the <strong>Script Task Code</strong> section. Script Task will populate the variable <strong>ListOfFiles</strong> with the collection of files matching a given pattern. This example will first use the pattern *.txt, which yields no results and then later the pattern *.xls that will match few files on the FTP server.</p></li> <li><p>Configure the <code>Foreach Loop container</code> as shown in screenshots #<strong>3</strong> and #<strong>4</strong>. This task will loop through the variable *<em>ListOfFiles</em>. If there are no files, the FTP task inside the loop container will not execute. If there are files, the FTP task inside the loop container will execute for the task for the number of files found on the FTP server.</p></li> <li><p>Configure the <code>FTP Task</code> as shown in screenshots #<strong>5</strong> and #<strong>6</strong>.</p></li> <li><p>Screenshot #<strong>7</strong> shows sample package execution when <strong>no</strong> matching files are found for the pattern <code>*.txt</code>.</p></li> <li><p>Screenshot #<strong>8</strong> shows the contents of the folder <code>C:\temp\</code> <strong>before</strong> execution of the package.</p></li> <li><p>Screenshot #<strong>9</strong> shows sample package execution when matching files are found for the pattern <code>*.xls</code>.</p></li> <li><p>Screenshot #<strong>10</strong> shows the contents of the FTP remote path <code>/Practice/Directory_New</code>.</p></li> <li><p>Screenshot #<strong>11</strong> shows the contents of the folder <code>C:\temp\</code> <strong>after</strong> execution of the package.</p></li> <li><p>Screenshot #<strong>12</strong> shows the package failure when provided with incorrect <strong>Remote path</strong>.</p></li> <li><p>Screenshot #<strong>13</strong> shows the error message related to the package failure.</p></li> </ol> <p>Hope that helps.</p> <p><strong>Script Task Code:</strong></p> <p><strong>C#</strong> code that can be used in <strong><code>SSIS 2008 and above</code></strong>. </p> <p>Include the <code>using</code> statement <strong>using System.Text.RegularExpressions;</strong></p> <pre><code>public void Main() { Variables varCollection = null; ConnectionManager ftpManager = null; FtpClientConnection ftpConnection = null; string[] fileNames = null; string[] folderNames = null; System.Collections.ArrayList listOfFiles = null; string remotePath = string.Empty; string filePattern = string.Empty; Regex regexp; int counter; Dts.VariableDispenser.LockForWrite("User::RemotePath"); Dts.VariableDispenser.LockForWrite("User::FilePattern"); Dts.VariableDispenser.LockForWrite("User::ListOfFiles"); Dts.VariableDispenser.GetVariables(ref varCollection); try { remotePath = varCollection["User::RemotePath"].Value.ToString(); filePattern = varCollection["User::FilePattern"].Value.ToString(); ftpManager = Dts.Connections["FTP"]; ftpConnection = new FtpClientConnection(ftpManager.AcquireConnection(null)); ftpConnection.Connect(); ftpConnection.SetWorkingDirectory(remotePath); ftpConnection.GetListing(out folderNames, out fileNames); ftpConnection.Close(); listOfFiles = new System.Collections.ArrayList(); if (fileNames != null) { regexp = new Regex("^" + filePattern + "$"); for (counter = 0; counter &lt;= fileNames.GetUpperBound(0); counter++) { if (regexp.IsMatch(fileNames[counter])) { listOfFiles.Add(remotePath + fileNames[counter]); } } } varCollection["User::ListOfFiles"].Value = listOfFiles; } catch (Exception ex) { Dts.Events.FireError(-1, string.Empty, ex.ToString(), string.Empty, 0); Dts.TaskResult = (int) ScriptResults.Failure; } finally { varCollection.Unlock(); ftpConnection = null; ftpManager = null; } Dts.TaskResult = (int)ScriptResults.Success; } </code></pre> <p><strong>VB</strong> code that can be used in <strong><code>SSIS 2005 and above</code></strong>. </p> <p>Include the <code>Imports</code> statement <strong>Imports System.Text.RegularExpressions</strong></p> <pre><code>Public Sub Main() Dim varCollection As Variables = Nothing Dim ftpManager As ConnectionManager = Nothing Dim ftpConnection As FtpClientConnection = Nothing Dim fileNames() As String = Nothing Dim folderNames() As String = Nothing Dim listOfFiles As Collections.ArrayList Dim remotePath As String = String.Empty Dim filePattern As String = String.Empty Dim regexp As Regex Dim counter As Integer Dts.VariableDispenser.LockForRead("User::RemotePath") Dts.VariableDispenser.LockForRead("User::FilePattern") Dts.VariableDispenser.LockForWrite("User::ListOfFiles") Dts.VariableDispenser.GetVariables(varCollection) Try remotePath = varCollection("User::RemotePath").Value.ToString() filePattern = varCollection("User::FilePattern").Value.ToString() ftpManager = Dts.Connections("FTP") ftpConnection = New FtpClientConnection(ftpManager.AcquireConnection(Nothing)) ftpConnection.Connect() ftpConnection.SetWorkingDirectory(remotePath) ftpConnection.GetListing(folderNames, fileNames) ftpConnection.Close() listOfFiles = New Collections.ArrayList() If fileNames IsNot Nothing Then regexp = New Regex("^" &amp; filePattern &amp; "$") For counter = 0 To fileNames.GetUpperBound(0) If regexp.IsMatch(fileNames(counter)) Then listOfFiles.Add(remotePath &amp; fileNames(counter)) End If Next counter End If varCollection("User::ListOfFiles").Value = listOfFiles Dts.TaskResult = ScriptResults.Success Catch ex As Exception Dts.Events.FireError(-1, String.Empty, ex.ToString(), String.Empty, 0) Dts.TaskResult = ScriptResults.Failure Finally varCollection.Unlock() ftpConnection = Nothing ftpManager = Nothing End Try Dts.TaskResult = ScriptResults.Success End Sub </code></pre> <p><strong>Screenshot #1:</strong></p> <p><img src="http://i.stack.imgur.com/Lv78g.png" alt="1"></p> <p><strong>Screenshot #2:</strong></p> <p><img src="http://i.stack.imgur.com/Ibx38.png" alt="2"></p> <p><strong>Screenshot #3:</strong></p> <p><img src="http://i.stack.imgur.com/QR09z.png" alt="3"></p> <p><strong>Screenshot #4:</strong></p> <p><img src="http://i.stack.imgur.com/OsAHp.png" alt="4"></p> <p><strong>Screenshot #5:</strong></p> <p><img src="http://i.stack.imgur.com/D4LGu.png" alt="5"></p> <p><strong>Screenshot #6:</strong></p> <p><img src="http://i.stack.imgur.com/2veal.png" alt="6"></p> <p><strong>Screenshot #7:</strong></p> <p><img src="http://i.stack.imgur.com/GxIGn.png" alt="7"></p> <p><strong>Screenshot #8:</strong></p> <p><img src="http://i.stack.imgur.com/wh0dO.png" alt="8"></p> <p><strong>Screenshot #9:</strong></p> <p><img src="http://i.stack.imgur.com/8T8JL.png" alt="9"></p> <p><strong>Screenshot #10:</strong></p> <p><img src="http://i.stack.imgur.com/dy3tV.png" alt="10"></p> <p><strong>Screenshot #11:</strong></p> <p><img src="http://i.stack.imgur.com/2rjo2.png" alt="11"></p> <p><strong>Screenshot #12:</strong></p> <p><img src="http://i.stack.imgur.com/7aabW.png" alt="12"></p> <p><strong>Screenshot #13:</strong></p> <p><img src="http://i.stack.imgur.com/jPmGy.png" alt="13"></p>
Are "dirty reads" safe to use in Terracotta? <p>"Dirty reads", meaning reading an object's value even though it is write-locked by another thread, are <a href="http://www.terracotta.org/confluence/display/howto/Recipe?recipe=dirty-read" rel="nofollow">described</a> on Terracotta's website, yet I've heard that they shouldn't be used, even if you don't care about the possibility that you might get old data when you dirty-read the locked object.</p> <p>Does anyone have any experience of using dirty reads in Terracotta, and are they safe to use if you don't care about the possibility of reading an old value?</p>
<p>A dirty read is a dirty read. Terracotta, being distributed/clustered, only adds the possibility to read even older values of the shared mutable state that you are accessing without proper synchronization.</p> <p>You should note that, under the memory model in Java 5, you are not guaranteed to <em>ever</em> read an updated value if you don't use proper synchronization. Terracotta may decide to take advantage of this possibility. In fact, any JVM may, at their leisure, take advantage of it. Even if it might work on your machine, it may break on other machines. It may break on minor updates of the JVM, and it may break for the same version of the same JVM on a different CPU.</p> <p>With that in mind, you can say that dirty reads isn't safe in any JVM... Unless you don't mind the possibility that you won't ever be able to read the updates that other threads make - an unlikely situation but it could happen.</p> <p>Also, when you actually follow your link to Terracottas wiki, it says that the article has been removed and that the pattern is discouraged.</p>
Why does Java not have block-scoped variable declarations? <p>The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:</p> <pre><code>void methodName() { int i = 7; for (int j = 0; j &lt; 10; j++) { int i = j * 2; } } </code></pre> <p>Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!</p> <p>What's the rationale for this design decision for Java?</p> <p>Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)</p>
<p>Well, strictly speaking, Java <em>does</em> have block-scoped variable declarations; so this is an error:</p> <pre><code>void methodName() { for (int j = 0; j &lt; 10; j++) { int i = j * 2; } System.out.println(i); // error } </code></pre> <p>Because 'i' doesn't exist outside the for block.</p> <p>The problem is that Java doesn't allow you to create a variable with the same name of another variable that was declared in an outer block of the same method. As other people have said, supposedly this was done to prevent bugs that are hard to identify.</p>
What's the best way to count keywords in JavaScript? <p>What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. </p> <p>Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.</p>
<p>Once you have that array of words cleaned up, and let's say you call it <code>wordArray</code>:</p> <pre><code>var keywordRegistry = {}; for(var i = 0; i &lt; wordArray.length; i++) { if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) { keywordRegistry[wordArray[i]] = 0; } keywordRegistry[wordArray[i]] = keywordRegistry[wordArray[i]] + 1; } // now keywordRegistry will have, as properties, all of the // words in your word array with their respective counts // this will alert (choose something better than alert) all words and their counts for(var keyword in keywordRegistry) { alert("The keyword '" + keyword + "' occurred " + keywordRegistry[keyword] + " times"); } </code></pre> <p>That should give you the basics of doing this part of the work.</p>
Flex Post Event Screen Updates <p>I came across this topic today while investigating something very strange. Doing certain things in our Flex app can cause the number of frames rendered to rocket, from 12fps to ~30fps: loaded animations start playing at high speed and the GUI starts to lock up.</p> <p>Since everything I've read on Flex/Flash hammers home the point "the frame rate is capped at the fps set in the top level app", it seems the only way these extra renders can be happening is due to some events causing them (no programmatic changes to the stage's framerate are done anywhere). Since it only happens when I put my update logic in the ENTER_FRAME handler, I'm trying to figure out what might be happening which to apparently causing Flex to go render-crazy.</p> <p>Hypothesis: something in my update function is triggering an immediate screen update, this raises another ENTER_FRAME immediately, which means my update loop gets called, which triggers another immediate screen update, ...</p> <p>We have Flex components used in our GUI, if this is a factor. I don't really know where to go next on this.</p> <p><strong>Clarifications</strong>:</p> <ul> <li>When I say things speed up, there are two ways this manifests.</li> <li>Firstly, my ENTER_FRAME handler gets called far more often.</li> <li>Secondly, a loaded Flash SWF with a looping animation built in suddenly speeds up to te point it looks silly.</li> <li>I am not using updateAfterEvent, I only found this existed when researching this problem. Apparently, some events on Sprite subclasses automatically call this and I wonder if that's the root cause.</li> <li>I am not doing any direct messsing about with rendering at all. Background animations play automatically as they have timelines built-in from CS3 authoring, all our update function does is change the position of DisPlayObjects or add/remove them etc</li> </ul> <p><strong>Update:</strong> I added a label to my app to print out stage.frameRate, and discovered at certain times, it suddenly changes from 12 to 1000 (the maximum allowed value). While it was trivial to add a line to my ENTER_FRAME handler to reset it that's hardly a big help. Also, even doing this, the rendering is all messed up. Certain actions (like raising an Alert popup) make it all spring back into life. Unfortunately, I am not able to view the source of the Stage class to set a breakpoint on the setter property.</p> <p>That's very interesting about the Flex loading 'set to 1000fps' thing. What we have are several Flex applications which all provide a common interface. A master app is in charge of loading these modules as required through the SWFLoader class. However, the loading process already takes into account the delayed loading... when the SWF loads we then wait for the APPLICATION_COMPLETE from the SystemManager. Once this is received, shouldn't the applications completion have occurred?</p>
<p>Flex sets the frame rate to 1000 during "phased instantiation" of Flex components, which occurs only during initial load of a flex swf. This allows it to build all components very quickly.</p> <p>Are you waiting for the Flex app to be fully loaded and constructed? You should be waiting for FlexEvent.CREATION_COMPLETE before working with your Flex content.</p> <p>If you would like a reference to where this occcurs, look in the Flex LayoutManager class, line 326 (using Flex SDK 3.0.194161), in the setter for the property usePhasedInstantiation.</p> <p><b>Update:</b></p> <p>APPLICATION_COMPLETE should have you covered for the initial load.</p> <p>This actually happens any time components are created directly from MXML. So there are a few other cases to look for. Are you using any Repeaters? Do you use any navigation containers that are building their children on demand?</p>
INotifyPropertyChanged property name - hardcode vs reflection? <p>What is the best way to specify a property name when using INotifyPropertyChanged? </p> <p>Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.</p>
<p>Don't forget one thing : <code>PropertyChanged</code> event is mainly consumed by components that will <strong>use reflection</strong> to get the value of the named property.</p> <p>The most obvious example is databinding.</p> <p>When you fire <code>PropertyChanged</code> event, passing the name of the property as a parameter, you should know that <em>the subscriber of this event is likely to use reflection</em> by calling, for instance, <code>GetProperty</code> (at least the first time if it uses a cache of <code>PropertyInfo</code>), then <code>GetValue</code>. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the <code>GetProperty</code> which only queries meta data. (Note that data binding relies on the whole <a href="http://msdn.microsoft.com/en-us/library/ms171819.aspx">TypeDescriptor</a> thing -- but the default implementation uses reflection.)</p> <p>So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism.</p> <p>Here is what I use sometimes in C# 3.0, when performances would not be a concern :</p> <pre><code>public class Person : INotifyPropertyChanged { private string name; public string Name { get { return this.name; } set { this.name = value; FirePropertyChanged(p =&gt; p.Name); } } private void FirePropertyChanged&lt;TValue&gt;(Expression&lt;Func&lt;Person, TValue&gt;&gt; propertySelector) { if (PropertyChanged == null) return; var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression == null) return; PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an <code>Expression</code> :</p> <pre><code>FirePropertyChanged(p =&gt; p.Name); </code></pre>
Javascript to detect whether the dropdown of a select element is visible <p>I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:</p> <ul> <li>Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.</li> <li>Change events, but these only are triggered when the select box's value changes.</li> </ul> <p>Ideas?</p>
<p>here is how I would preferred to do it. focus and blur is where it is at.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;SandBox&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;select id="ddlBox"&gt; &lt;option&gt;Option 1&lt;/option&gt; &lt;option&gt;Option 2&lt;/option&gt; &lt;option&gt;Option 3&lt;/option&gt; &lt;/select&gt; &lt;div id="divMsg"&gt;some text or whatever goes here.&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;script type="text/javascript"&gt; window.onload = function() { var ddlBox = document.getElementById("ddlBox"); var divMsg = document.getElementById("divMsg"); if (ddlBox &amp;&amp; divMsg) { ddlBox.onfocus = function() { divMsg.style.display = "none"; } ddlBox.onblur = function() { divMsg.style.display = ""; } divMsg.style.display = ""; } } &lt;/script&gt; </code></pre>
Visual Studio 2008 source control for small teams <p>I work on a small web team where I am the only .NET developer currently using Visual Studio 2008 Professional to build and maintain a few web applications. I am about to start training another member of our team so we purchased him a copy of Visual Studio 2008 Professional. I've looked into Visual Source Safe, but I'm dubious. I don't like that is file system based. Ideally, the system would work with SQL Server 2005 and plug into Visual Studio. Windows based solutions are the best because of the IT environment of the organization I work for.</p> <p>What are my options for a source control system?</p> <p>(Forgive me if the answer exists in another thread.)</p>
<p><a href="http://subversion.tigris.org/">Subversion</a> has good integration with Visual Studio 2008 through <a href="http://www.visualsvn.com/">VisualSVN</a> and <a href="http://ankhsvn.open.collab.net/">Ankh</a>. </p> <p>SourceSafe is dangerous. You're right that a filesharing-based SCM is a bad idea, and Microsoft themselves have downplayed it and replaced it with a new SCM that comes with the Team edition of Visual Studio.</p>
Should try...catch go inside or outside a loop? <p>I have a loop that looks something like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } </code></pre> <p>This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return <code>null</code> if there is an error, so I put the loop inside a <code>try...catch</code> block, like this:</p> <pre><code>try { for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } </code></pre> <p>But then I also thought of putting the <code>try...catch</code> block inside the loop, like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } </code></pre> <p>Is there any reason, performance or otherwise, to prefer one over the other?</p> <hr> <p><strong>Edit:</strong> The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?</p>
<p>PERFORMANCE:</p> <p>There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.</p> <p>Here's a reference: <a href="http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html">http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html</a></p> <p>The table is described about half-way down.</p>
RoR: Accessing models from with application.rb <p>i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.</p> <p>i have this code in the application.rb:</p> <p>def check_role @user = session[:user]</p> <p>if @user.role.can_access_admin.nil? || !@user.role.can_access_admin render :text => "your current role does not allow access to the administration area." return end end</p> <p>and then i have this code inside one of the admin controllers:</p> <p>class Admin::BlogsController &lt; ApplicationController before_filter :check_role</p> <p>def list @blogList = Blog.find(:all) end end</p> <p>and when i try to view the list action i get this error:</p> <p>undefined method 'role' for user...</p> <p>anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)</p>
<p>just a guess but it seems that your session[:user] is just storing the id, you need to do:</p> <pre><code>@user = User.find(session[:user]) </code></pre> <p>or something along those lines to fetch the user from the database (along with its associations). </p> <p>It's good to do the above in a before filter too.</p>