input
stringlengths
51
42.3k
output
stringlengths
18
55k
What's the best way to implement a SQL script that will grant permissions to a database role on all the user tables in a database? <p>What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?</p> <p>Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.</p>
<p>I'm sure there is an easier way, but you could loop through the sysobjects table in the database and grant permissions to any user table objects that exist. You could then run that multiple times whenever new tables are added.</p>
Learning CIL <p>Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.</p>
<p>The only CIL book on my shelf is <a href="http://rads.stackoverflow.com/amzn/click/1590596463" rel="nofollow">Expert .NET 2.0 IL Assembler</a> by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a>.</p> <p><strong>Edit:</strong> CIL (and indeed the CLR in general) has not changed at all between .NET 2.0 and .NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements. So there's nothing newer available on a CIL level than what would be in a book on 2.0</p>
How can I programmatically determine if my workstation is locked? <p>I'm writing up some productivity/metrics tools for myself to help monitor my focus throughout the day. Recently, I've noticed that I tend to get off track more than usual and feel the need to get up and go for walks/drinks/etc and I'm concerned that I'm "wasting" too much time.</p> <p>Since I always lock my computer when I go anywhere, and I unlock it as soon as I return (even if I'm just reading at my desk, etc), I was wondering how I can determine, in code, how long the machine is locked.</p> <p>I'm writing this in C# if that helps, but I'm open to other ideas.</p> <p><hr /></p> <p>I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.</p> <p>I'll write it up anyway and see if it works. Thanks everyone!</p>
<p>I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:</p> <pre><code> Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { //I left my desk } else if (e.Reason == SessionSwitchReason.SessionUnlock) { //I returned to my desk } } </code></pre>
How to parse a string into a nullable int <p>I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.</p> <p>I was kind of hoping that this would work</p> <pre><code>int? val = stringVal as int?; </code></pre> <p>But that won't work, so the way I'm doing it now is I've written this extension method</p> <pre><code>public static int? ParseNullableInt(this string value) { if (value == null || value.Trim() == string.Empty) { return null; } else { try { return int.Parse(value); } catch { return null; } } } </code></pre> <p>Is there a better way of doing this?</p> <p><strong>EDIT:</strong> Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>
<p><code>int.TryParse</code> is probably a tad easier:</p> <pre><code>public static int? ToNullableInt(this string s) { int i; if (int.TryParse(s, out i)) return i; return null; } </code></pre> <p><strong>Edit</strong> @Glenn <code>int.TryParse</code> is "built into the framework". It and <code>int.Parse</code> are <em>the</em> way to parse strings to ints.</p>
Problems with disabling IIS shutdown of idle worker process? <p>I ran into an issue with an IIS web app shutting down an idle worker process. The next request would then have to re-initialize the application, leading to delays. I disabled the IIS shutdown of idle worker processes on the application pool to resolve this. Are there any issues associated with turning this off? If the process is leaking memory, I imagine it is nice to recycle the process every now and then. Are there any other benefits to having this process shutdown?</p>
<p>I'm assuming that you're referring to IIS 6.</p> <p>Instead of disabling shutdown altogether, maybe you can just increase the amount of time it waits before killing the process. The server is essentially conserving resources - if your server can stand the resource allocation for a process that mostly sits around doing nothing, then there isn't any harm in letting it be.</p> <p>As you mentioned, setting the auto-recycling of the process on a memory limit would be a good idea, if the possibility of a memory leak is there.</p>
Is it possible to forward ssh requests that come in over a certain port to another machine? <p>I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?</p> <p>Oh and all of these machines are running either Ubuntu or OS X. </p>
<p>Another way to go would be to use ssh tunneling (which happens on the client side).</p> <p>You'd do an ssh command like this:</p> <pre><code>ssh -L 8022:myinsideserver:22 paul@myoutsideserver </code></pre> <p>That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside.</p> <p>Then you'd do another ssh command like this (leaving the first one still connected):</p> <pre><code>ssh -p 8022 paul@localhost </code></pre> <p>That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver. </p> <p>There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now.</p> <p><strong>Edit</strong></p> <p>Hmmm. The ssh manpage says this: **Only the superuser can forward privileged ports. **</p> <p><strike>That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that.</strike></p> <p>It looks like superuser privileges aren't required as long as the forwarded port <strong><em>(in this case, 8022)</em></strong> isn't a privileged port (like 22). Thanks for the clarification <a href="http://stackoverflow.com/questions/45230/is-it-possible-to-forward-ssh-requests-that-come-in-over-a-certain-port-to-anot#45254" rel="nofollow">Mike Stone</a>.</p>
Friendly URLs for ASP.NET <p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/">http://somewhere.overtherainbow.com/userid/123424/</a></p> <p>I want you to notice the ending path <strong>/userid/123424/</strong></p> <p>How do you do this in ASP.NET?</p>
<p>This example uses ASP.NET Routing to implement friendly URLs. </p> <p>Examples of the mappings that the application handles are: </p> <p><a href="http://samplesite/userid/1234">http://samplesite/userid/1234</a> - <a href="http://samplesite/users.aspx?userid=1234">http://samplesite/users.aspx?userid=1234</a><br /> <a href="http://samplesite/userid/1235">http://samplesite/userid/1235</a> - <a href="http://samplesite/users.aspx?userid=1235">http://samplesite/users.aspx?userid=1235</a> </p> <p>This example uses querystrings and avoids any requirement to modify the code on the aspx page. </p> <h1>Step 1 - add the necessary entries to web.config</h1> <pre><code>&lt;system.web&gt; &lt;compilation debug="true"&gt; &lt;assemblies&gt; … &lt;add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; … &lt;httpModules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;/httpModules&gt; &lt;/system.web&gt; &lt;system.webServer&gt; … &lt;modules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/modules&gt; &lt;handlers … &lt;add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; </code></pre> <h1>Step 2 - add a routing table in global.asax</h1> <p>Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. </p> <pre><code>void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("UseridRoute", new Route ( "userid/{userid}", new CustomRouteHandler("~/users.aspx") )); } </code></pre> <h1>Step 3 - implement the route handler</h1> <p>Add the querystring to the current context before the routing takes place. </p> <pre><code>using System.Web.Compilation; using System.Web.UI; using System.Web; using System.Web.Routing; public class CustomRouteHandler : IRouteHandler { public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { // Add the querystring to the URL in the current context string queryString = "?userid=" + requestContext.RouteData.Values["userid"]; HttpContext.Current.RewritePath( string.Concat( VirtualPath, queryString)); var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; } } </code></pre> <h1>Code from users.aspx</h1> <p>The code on the aspx page for reference. </p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string id = Page.Request.QueryString["userid"]; switch (id) { case "1234": lblUserId.Text = id; lblUserName.Text = "Bill"; break; case "1235": lblUserId.Text = id; lblUserName.Text = "Claire"; break; case "1236": lblUserId.Text = id; lblUserName.Text = "David"; break; default: lblUserId.Text = "0000"; lblUserName.Text = "Unknown"; break; } </code></pre>
Source control system for single developer <p>What's the recommended source control system for a very small team (one developer)?<BR><BR> Price does not matter. Customer would pay :-)<BR> I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. <BR><BR>Any opinions?</p>
<p>I would use Subversion (in fact I use it) [<strong>update</strong>: Jul 2014 -- I use Git -- see end of the answer]. SVN is:</p> <ul> <li>free, </li> <li>good enough (see disadvantages below), </li> <li>simple, </li> <li>works fine on Windows (and Linux too), </li> <li>a lot of people use it so it's easy to get help, </li> <li>can integrate with most of IDEs i.e. <strong>Visual Studio</strong> (i.e. <a href="http://ankhsvn.open.collab.net/" rel="nofollow">ankhsvn</a> or <a href="http://www.visualsvn.com/" rel="nofollow">VisualSVN</a> -- <a href="http://stackoverflow.com/questions/453481/subversion-plugin-to-visual-studio">more info</a>) or <strong>Eclipse</strong> (i.e. <a href="http://sourceforge.net/projects/subclipse/" rel="nofollow">Subclipse</a> -- <a href="http://stackoverflow.com/questions/185486/which-eclipse-subversion-plugin-should-i-use">here</a> someone asked about that).</li> </ul> <p>I would <strong>strongly</strong> recommended separate machine to source control server. At best somewhere <em>on the cloud</em>. Advantages:</p> <ul> <li>You don't lost your source control repositories if your development box dies.</li> <li>You don't have to worry about maintenance of one more box.</li> </ul> <p>There are companies which <a href="http://www.svnhostingcomparison.com/" rel="nofollow">host SVN repositories</a>.</p> <p><a href="http://subversion.apache.org/packages.html" rel="nofollow">Here</a> are links to SVN (client and server) packages for various operating systems.</p> <h1>Disadvantages of SVN</h1> <p>I am using SVN on Windows machine for about 5 years and found that SVN has a few disadvantages :).</p> <h2>It is slow on large repositories</h2> <p>SVN (or its client -- TortoiseSVN) has one <strong>big</strong> disadvantage -- it terrible slow (while updating or committing) on large (thousands of files) repositories unless you have <a href="http://en.wikipedia.org/wiki/Solid-state_drive" rel="nofollow">SSD</a> drive.</p> <h2>Merging can be difficult</h2> <p>Many people complain about how hard merging is with SVN.</p> <p>I do merging for about 4 years (including about 2 years in CVS -- that was terrible, but doable) and about 2 years with SVN.</p> <p>And personally I don't find it hard -- on the other hand -- any merge is easy after merging branches in CVS :).</p> <p>I do merge of large repository (two repositories in fact) once a week and rarely I have conflicts which are hard to solve (most of conflicts are solved automatically with <em>diff</em> software which I use).</p> <p>However in case of project of a few developers merging should not be problem at all if you keep a few simple rules:</p> <ul> <li>merge changes often,</li> <li>avoid active development in various branches simultaneously.</li> </ul> <h2>Added in July 2011</h2> <p>Many devs recommended <a href="http://en.wikipedia.org/wiki/Distributed_revision_control_system" rel="nofollow">Distributed Version Control</a> like <a href="http://git-scm.com/" rel="nofollow">Git</a> or <a href="http://mercurial.selenic.com/" rel="nofollow">Mercurial</a>.</p> <p>From <strong>single developer</strong> perspective there are only a few important advantages of DVCS over SVN:</p> <ul> <li>DVCS can be faster.</li> <li>You can commit to local repository without access to central one.</li> <li>DVCS is hot thing and fancy to use/learn (if someone pay for your learning).</li> </ul> <p>And I don't think merging is a problem in case of single developer.</p> <p>Joel Spolsky wrote <a href="http://hginit.com/" rel="nofollow">tutorial about Mercurial</a> which is definitively worth to read.</p> <p>So, despite of many advantages of DVCS I would stay with SVN if merging or speed is not a problem.</p> <p>Or try Mercurial, which according to <a href="http://stackoverflow.com/questions/995636/popularity-of-git-mercurial-bazaar-vs-which-to-recommend">this</a> and <a href="http://stackoverflow.com/questions/2550091/best-support-now-on-windows-mercurial-or-git">this</a> SO questions, is better supported (in July 2011) on Windows.</p> <h2>Added in July 2014</h2> <p>For about a year I use Git (Git Bash mainly) for my pet-projects (i.e. solving Euler problems) and local branches for each Euler problem are really nice feature -- exactly as it is described as advantage of DVCS. </p> <p>Today Git tooling on Windows is much, much better then 2 or more years ago. You can use remote repo (like GitHub or ProjectLocker and many others) to keep copy of your project away from your workstation with no extra effort/money.</p> <p>However I use GUI client only to looks at diffs (and sometimes to choose files to commit), so it's better to not afraid of command line -- it's really nice.</p> <p>So as of today I would go with Git.</p>
Suggest some good MVC framework in perl <p>Can you suggest some good MVC framework for perl -- one I am aware of is <a href="http://www.catalystframework.org/" rel="nofollow">catalyst</a></p> <p>The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.</p>
<p>I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework. </p> <p>In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives.</p> <p>If Catalyst doesn't seem right to you, then you could build upon the lightweight framework <a href="http://cgi-app.org/">CGI::Application</a> to suit your needs or take a look at some of the lesser known MVC frameworks like <a href="http://pagekit.org/">PageKit</a> and <a href="http://maypole.perl.org/">Maypole</a>.</p>
Wacom tablet Python interface <p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
<p>You could perhaps take a look at the <a href="http://www.alexmac.cc/tablet-apps/tablet-apps-0.3.1.tar.bz2" rel="nofollow">software</a> described <a href="http://www.alexmac.cc/tablet-apps/" rel="nofollow">here</a>. It is a gnome applet, written in Python.</p> <p>From the web site:</p> <p>"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."</p> <p><a href="http://www.google.com/search?q=wacom+tablet+python" rel="nofollow">Google is your friend</a></p>
How can I call a .NET DLL from an Inno Setup script? <p>I want to call a function from a .NET DLL (coded in C#) from an Inno Setup script.</p> <p>I have:</p> <ol> <li>marked the <em>Register for COM interop</em> option in the project properties,</li> <li>changed the <em>ComVisible</em> setting in the <em>AssemblyInfo.cs</em> file,</li> <li>added these lines to the ISS script:</li> </ol> <blockquote> <p>[Files]</p> <p>Source: c:\temp\1\MyDLL.dll; Flags: dontcopy</p> <p>[Code]</p> <p>function MyFunction(): string;</p> <p>external 'MyFunction@files:MyDLL.dll stdcall setuponly';</p> </blockquote> <p>but I still get the following error:</p> <blockquote> <p>Runtime Error (at -1:0):</p> <p>Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll.</p> </blockquote> <p>What am I doing wrong?</p>
<p>Intenta de esta manera (Try this way):</p> <pre><code>Var obj: Variant va: MyVariableType; Begin //Starting ExtractTemporaryFile('MyDll.dll'); RegisterServer(False, ExpandConstant('{tmp}\MyDll.dll'), False); obj := CreateOleObject('MyDll.MyClass'); //Using va := obj.MyFunction(); //Finishing UnregisterServer(False, ExpandConstant('{tmp}\MyDll.dll'), False); DeleteFile('{tmp}\MyDll.dll'); End; </code></pre> <p>Suerte (good luck)</p>
How to know whether a window with a given title is already open in Tk? <p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p> <pre><code>from Tkinter import * import tkMessageBox root = Tk() root.withdraw() # TODO not if a window with this title exists tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre> <p>Any idea how to check that?</p>
<p>I believe you want:</p> <pre><code>if 'normal' != root.state(): tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre>
A issue with the jquery dialog when using the themeroller css <p>The <a href="http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog" rel="nofollow">demos</a> for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. </p> <p>Here is the js file:</p> <pre><code>topMenu = { init: function(){ $("#my_button").bind("click", function(){ $("#SERVICE03_DLG").dialog("open"); $("#something").focus(); }); $("#SERVICE03_DLG").dialog({ autoOpen: false, modal: true, resizable: false, title: "my title", overlay: { opacity: 0.5, background: "black" }, buttons: { "OK": function() { alert("hi!"); }, "cancel": function() { $(this).dialog("close"); } }, close: function(){ $("#something").val(""); } }); } } $(document).ready(topMenu.init); </code></pre> <p>Here is the html that uses the flora theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="flora/flora.all.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="flora"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the html that uses the downloaded themeroller theme:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"&gt; &lt;title&gt;sample&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css"&gt; &lt;script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"&gt;&lt;/script&gt; &lt;script src="TopMenu.js" language="JavaScript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me!" id="my_button"&gt; &lt;div id="SERVICE03_DLG" class="ui-dialog"&gt;please enter something&lt;br&gt;&lt;br&gt; &lt;label for="something"&gt;somthing:&lt;/label&gt;&amp;nbsp;&lt;input name="something" id="something" type="text" maxlength="20" size="24"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As you can see, only the referenced css file and class names are different. Anybody have a clue as to what could be wrong?</p> <p>@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:</p> <pre class="lang-none prettyprint-override"><code>style="z-index:5000" </code></pre> <p>and I've also tried it referencing an external css file:</p> <pre class="lang-none prettyprint-override"><code>#SERVICE03_DLG{z-index:5000;} </code></pre> <p>But neither of these work. Am I missing something in what you suggested?</p> <p><strong>Edit:</strong><br> Solve by brostbeef!<br> Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.</p>
<p>I think it is because you have the classes different.<br/> <code>&lt;div id="SERVICE03_DLG" class="flora"&gt;</code> (flora)<br/> <code>&lt;div id="SERVICE03_DLG" class="ui-dialog"&gt;</code> (custom)</p> <p>Even with the flora theme, you would still use the ui-dialog class to define it as a dialog.</p> <p>I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you.</p> <p>Try getting rid of the class attribute or using the "ui-dialog" class.</p>
Common Files in Visual Studio Solution <p>Many times I have seen Visual Studio solutions which have multiple projects that share source files. These common source files are usually out in a common directory and in the solution explorer their icon shows up with a link arrow in the bottom left.</p> <p>However, any time I try to add a source file to the project that is outside of that project's main directory, it just automatically copies it into the directory so that I no longer have a shared copy.</p> <p>I found that I can get around this by manually opening the project file in a text editor and modifying the path to something like "../../../Common/Source.cs" but this is more of a hack then I would like.</p> <p>Is there a setting or something I can change that will allow me to do this from within the IDE?</p>
<p>Right click on a project, select <strong>Add->Existing Item->Add as link</strong> (press on small arrow on Add button)</p>
XML Editor for OS X <p><a href="http://stackoverflow.com/questions/12073/what-is-the-best-xml-editor" rel="nofollow">http://stackoverflow.com/questions/12073/what-is-the-best-xml-editor</a> was a great question regarding XML editors on Windows. What about on OS X?</p> <p>Oxygen is feature complete, but, it's a Java app and a bit clunky on OSX. It's also extremely expensive.</p> <p>Anything Mac native and comparable in features for less than $300 ?</p> <p>Thanks</p> <p>Andrew</p>
<p>If you use TextMate, there are plugins available such as <a href="http://ditchnet.org/xmlmate/" rel="nofollow">http://ditchnet.org/xmlmate/</a></p>
C# Force Form Focus <p>So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.</p> <pre><code>CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } </code></pre> <p>As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? </p> <hr> <p>@Joel, thanks for the info. Here is what I tried based on your suggestion:</p> <pre><code>msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); </code></pre> <p>The form still comes up <em>under</em> the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.</p> <p>Thnks for all the ideas so far folks.</p> <hr> <p>Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.</p>
<p>I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem.</p> <p>Basically, call ShowWindow() then SetForegroundWindow().</p> <pre><code>using System.Diagnostics; using System.Runtime.InteropServices; // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or minimize a window [DllImportAttribute("User32.DLL")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_RESTORE = 9; private void ActivateApplication(string briefAppName) { Process[] procList = Process.GetProcessesByName(briefAppName); if (procList.Length &gt; 0) { ShowWindow(procList[0].MainWindowHandle, SW_RESTORE); SetForegroundWindow(procList[0].MainWindowHandle); } } </code></pre>
How do you move a file in SVN? <p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p> <p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p>
<p>Check out section <b><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html#tsvn-dug-rename-move">5.14.2. Moving files and folders</a></b> (or check out "move" in the Index of the help) of the TortoiseSVN help. You do a move via right-dragging. It also mentions that you need to commit from the parent folder to make it "one" revision. This works for doing the change in a working copy.</p> <p>(Note that the SVN items in the following image will only show up if the destination folder has already been added to the repository.)</p> <p><img src="http://i.stack.imgur.com/3YzW2.png" alt="tortoise move menu"></p> <p>You can also do the move via the Repo Browser (section <b><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-repobrowser.html">5.23. The Repository Browser</a> </b> of the help).</p>
How do I group in memory lists? <p>I have a list of <code>Foo</code>. Foo has properties <code>Bar</code> and <code>Lum</code>. Some <code>Foo</code>s have identical values for <code>Bar</code>. How can I use lambda/linq to group my <code>Foo</code>s by <code>Bar</code> so I can iterate over each grouping's <code>Lum</code>s?</p>
<pre><code>var q = from x in list group x by x.Bar into g select g; foreach (var group in q) { Console.WriteLine("Group " + group.Key); foreach (var item in group) { Console.WriteLine(item.Bar); } } </code></pre>
Getting an int representation of a String <p>I am looking for a way to create an int\long representation of an arbitrary alpha-numeric String. Hash codes won't do it, because I can't afford hash collisions i.e. the representation must be unique and repeatable. </p> <p>The numeric representation will be used to perform efficient (hopefully) compares. The creation of the numeric key will take some time, but it only has to happen once, whereas I need to perform vast numbers of comparisons with it - which will hopefully be much faster than comparing the raw Strings.</p> <p>Any other idea's on faster String comparison will be most appreciated too...</p>
<p>Unless your string is limited in length, you can't avoid collisions. </p> <p>There are 4294967296 possible values for an integer (2^32). If you have a string of more than 4 ASCII characters, or more than two unicode characters, then there are more possible string values than possible integer values. You can't have a unique integer value for every possible 5 character string. Long values have more possible values, but they would only provide a unique value for every possible string of 8 ASCII characters.</p> <p>Hash codes are useful as a two step process: first see if the hash code matches, then check the whole string. For most strings that don't match, you only need to do the first step, and it's really fast.</p>
iPhone app crashing with NSUnknownKeyException setValue:forUndefinedKey: <p>I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging. Essentially my app displays an image and when touched plays a short sound. When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.</p> <p>I get the following error:</p> <pre><code>Application Specific Information: iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331) *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;UIView 0x34efd0&gt; setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.' </code></pre> <p>kramerImage here is the image I'm using for the background.</p> <p>I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.</p>
<p>(This isn't really iPhone specific - the same thing will happen in regular Cocoa).</p> <p>NSUnknownKeyException is a common error when using <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html" rel="nofollow">Key-Value Coding</a> to access a key that the object doesn't have.</p> <p>The properties of most Cocoa objects can be accessing directly:</p> <pre><code>[@"hello world" length] // Objective-C 1.0 @"hello world".length // Objective-C 2.0 </code></pre> <p>Or via Key-Value Coding:</p> <pre><code>[@"hello world" valueForKey:@"length"] </code></pre> <p>I would get an NSUnknownKeyException if I used the following line:</p> <pre><code>[@"hello world" valueForKey:@"purpleMonkeyDishwasher"] </code></pre> <p>because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.</p> <p>Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib.</p> <p>Find where 'kramerImage' is being used, and try to track it down from there.</p>
web site structure/architecture <p>What web site structure(s)/architecture(s) would the community swear by, with a narrowing down in the direction towards more of a small facebook style project?</p> <p>I understand the question to be rather broad/subjective; but being relatively new to the area of web development, I find just looking at and learning from examples of working projects most times extremely helpful, and that at other times just blows my mind and changes how I construct future assignments.</p> <p>With the latter paragraph in mind, does the community have any suggestions on places to look/articles to read?</p>
<p>I guess it depends on the technology you select. For web projects in general I've always employed (Web-)MVC for the past two years or so. The advantage being a clear seperation of frontend and backend in order to create a managable code base.</p> <p>But that's as vague as a recommendation could be. :)</p> <p>Aside from using a framework to build your site from scratch, you might also want to look into using what's already out there (in terms of open source). I'd recommend any kind of "community software" that's semi-established, well documented, not too often in the news because of security issues and offers API to extend its base. That could indeed jump start you on your facebook-esque site. ;)</p>
Center a block of content when you don't know its width in advance <p>After lots of attempts and search I have never found a satisfactory way to do it with CSS2.</p> <p>A simple way to accomplish it is to wrap it into a handy <code>&lt;table&gt;</code> as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; table { margin:0px auto 0 auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;test&lt;br/&gt;test&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;html&gt; </code></pre> <hr> <p>What I want to know is how to do it without a fixed width and also being a block.</p>
<p>@Jason, yep, <code>&lt;center&gt;</code> works. Good times. I'll propose the following, though:</p> <pre><code> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; body { text-align: center; } div.my-centered-content { margin: 0 auto; /* Centering */ display: inline; } &lt;/style&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="my-centered-content"&gt; &lt;p&gt;test&lt;/p&gt; &lt;p&gt;test&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>EDIT</strong> @Santi, a block-level element will fill the width of the parent container, so it will effectively be <code>width:100%</code> and the text will flow on the left, leaving you with useless markup and an uncentered element. You might want to try <code>display: inline-block;</code>. Firefox might complain, but <a href="http://www.w3.org/TR/CSS21/visuren.html#display-prop" rel="nofollow">it's right</a>. Also, try adding a <code>border: solid red 1px;</code> to the CSS of the <code>.my-centered-content</code> DIV to see what's happening as you try these things out.</p>
Why doesn't Oracle tell you WHICH table or view does not exist? <p>If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object? </p> <p>Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I'm a developer working with a complex join through several layers of application code, it's often very difficult to tell.</p> <p>My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.)</p> <p>Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table?</p> <p><hr /></p> <p>Although I've accepted an answer which is relevant to the topic, it doesn't really answer my question: <em>Why isn't the name part of the error message?</em> If anyone can come up with the real answer, I'll be happy to change my vote.</p>
<p>SQL*Plus does tell you the table that doesn't exist. For example:</p> <pre><code>SQL&gt; select 2 * 3 from 4 user_tables a, 5 non_existent_table b 6 where 7 a.table_name = b.table_name; non_existent_table b * ERROR at line 5: ORA-00942: table or view does not exist </code></pre> <p>Here it shows that the name of the missing table and the line number in the SQL statement where the error occurs.</p> <p>Similarly, in a one-line SQL statement you can see the asterisk highlighting the name of the unknown table:</p> <pre><code>SQL&gt; select * from user_tables a, non_existent_table b where a.table_name = b.table_name; select * from user_tables a, non_existent_table b where a.table_name = b.table_name * ERROR at line 1: ORA-00942: table or view does not exist </code></pre> <p>In terms of your question, I guess the reason the error message doesn't include the name of the table is that the error message itself needs to be static text. The line number and location in the line of the error is clearly passed back to SQL*Plus (somehow).</p>
Showing a hint for a C# winforms edit control <p>I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?</p>
<p>You will need to use some P/Inovke interop code to do this. Look for the Win32 API <code>SendMessage</code> function and the <code>EM_SETCUEBANNER</code> message.</p>
Reference material for LabVIEW <p>I'm supposed to learn how to use <a href="http://www.ni.com/labview/">LabVIEW</a> for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites.</p> <p>I'm a senior developer with lots of Java/C#/C++ experience.</p> <p>I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.</p>
<p><strong>It will take some <em>training</em> and some <em>time</em> to learn the style needed to develop maintainable code</strong>.</p> <p>Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls.</p> <p>For the basics, National Instruments offers <a href="http://www.ni.com/training/" rel="nofollow">training courses</a>. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification.</p> <p>Get an <a href="http://www.ni.com/labview/try/daq.htm" rel="nofollow">evaluation copy</a> of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly.</p> <p>LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function. </p> <p>The official NI support forums and knowledgebase are probably the best resources out there at the moment.</p> <p>Unofficial sites like <a href="http://www.cipce.rpi.edu/programs/remote_experiment/labview/" rel="nofollow">Tutorials in G</a> have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck.</p> <p><strong>Edit:</strong> <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/2241" rel="nofollow">Basics I/II</a> are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/12769" rel="nofollow">Intermediate I/II</a>. NI has the course outlines available on their website as well, so you know what you're going to cover in each.</p>
Is there a good Fogbugz client for Mac OS X? <p>And/or: do I need one?</p> <p>I've recently started using FogBugz for my hobby projects, and I'm very happy with things so far. Having read more about it, especially the evidence-based scheduling, I'd like to start using it for my PhD as well. (Heh; something tells me my supervisors won't be opening tickets for me, though.)</p> <p>Last night I stumbled onto <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=9016">TimePost</a>, which looks like a tidy app that doesn't do much but could be a real bonus to logging my time in FogBugz effectively. I tried looking around for similar apps but came up a little empty-handed. Are there any other FogBugz clients that you've used and recommend for Mac OS X? Or are you happy with the web interface?</p>
<p>The official answer is no, there is not a dedicated Mac client, other than Safari :)</p> <p>There's a <a href="http://support.fogcreek.com/default.asp?W840" rel="nofollow">command line version</a> that runs on Linux, Windows, and Mac.</p> <p>There are also plans for an iPhone version although I'm not technically supposed to announce features before they are done or even spec'd so pretend I didn't say that.</p>
Versioning library like SQLite database library? <p>I like how SQLite library can be included into an application and the application has a full-fledged database to use.</p> <p>Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?</p>
<p>SVN doesn't require any prerequisites on end user machine. You can embed SVN right into you app. To learn more on subversion integration, visit "<a href="http://www.svnforum.org/2017/viewforum.php?f=17&amp;sid=643adb11d5f8edd09544aa435b6f5732" rel="nofollow">Application Integration/Embedding</a>" thread on SVN forum.</p>
Best way to test a MS Access application? <p>With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).</p> <p>One of the main issues with testing forms is that only a few controls have a <code>hwnd</code> handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.</p> <p>Any experience to share?</p>
<p>I appreciated knox's and david's answers. My answer will be somewhere between theirs: just make <strong><em>forms that do not need to be debugged</em></strong>!</p> <p>I think that forms should be exclusively used as what they are basically, meaning graphic interface <strong><em>only</em></strong>, meaning here that they do not have to be debugged! The debugging job is then limited to your VBA modules and objects, which is a lot easier to handle. </p> <p>There is of course a natural tendency to add VBA code to forms and/or controls, specially when Access offers you these great "after Update" and "on change" events, but I definitely advise you <strong>not</strong> to put any form or control specific code in the form's module. This makes further maintenance and upgrade very costy, where your code is split between VBA modules and forms/controls modules.</p> <p>This does not mean you cannot use anymore this <code>AfterUpdate</code> event! Just put standard code in the event, like this:</p> <pre><code>Private Sub myControl_AfterUpdate() CTLAfterUpdate myControl On Error Resume Next Eval ("CTLAfterUpdate_MyForm()") On Error GoTo 0 End sub </code></pre> <p>Where:</p> <ul> <li><p><code>CTLAfterUpdate</code> is a standard procedure run each time a control is updated in a form</p></li> <li><p><code>CTLAfterUpdateMyForm</code> is a specific procedure run each time a control is updated on MyForm</p></li> </ul> <p>I have then 2 modules. The first one is </p> <ul> <li><code>utilityFormEvents</code><br> where I will have my CTLAfterUpdate generic event</li> </ul> <p>The second one is </p> <ul> <li><code>MyAppFormEvents</code><br> containing the specific code of all specific forms of the MyApp application and including the CTLAfterUpdateMyForm procedure. Of course, CTLAfterUpdateMyForm might not exist if there are no specific code to run. This is why we turn the "On error" to "resume next" ...</li> </ul> <p>Choosing such a generic solution means a lot. It means you are reaching a high level of code normalization (meaning painless maintenance of code). And when you say that you do not have any form-specific code, it also means that form modules are fully standardized, and their production can be <strong><em>automated</em></strong>: just say which events you want to manage at the form/control level, and define your generic/specific procedures terminology.<br> Write your automation code, once for all.<br> It takes a few days of work but it give exciting results. I have been using this solution for the last 2 years and it is clearly the right one: my forms are fully and automatically created from scratch with a "Forms Table", linked to a "Controls Table".<br> I can then spend my time working on the specific procedures of the form, if any.</p> <p>Code normalization, even with MS Access, is a long process. But it is really worth the pain!</p>
How can I break on exception using ddbg <p>I'm using the d programing language to write a program, and I'm trying to use ddbg to debug it. When there is an exception, I want to have the program break whenever there is an exception thrown so that I can inspect the stack.</p> <p>Alternatively, is there another debugger that works with d? Is there another way to get a stack trace when there is an exception?</p>
<p>You want to break when there's any exception thrown or just uncaught exceptions? Because I think the latter is already the default behavior.</p> <p>You probably know this, but you get the stack trace by typing 'us' (unwind stack) at the prompt. Just trying to eliminate the obvious.</p> <p>Anyway, I've never had to use onex. Never even heard of it. Another thing you could try is forcing execution to stop by putting in asserts.</p>
Is there a way to parse a dependency tree from a build script output? <p>I have an inherited project that uses a build script (not make) to build and link the project with various libraries.</p> <p>When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.</p> <p>The script is compiling and linking with GNU tools.</p>
<p>You might try using the <code>nm</code> tool. Given the right options, it will look at a binary (archive or linked image) and tell you what objects were linked into it.</p> <p>Actually, here's a one-liner I use at work:</p> <pre><code>#!/bin/sh nm -Ag $* | sed 's/^.*\/\(.*\.a\):/\1/' | sort -k 3 | grep -v ' U ' </code></pre> <p>to find the culprits for undefined symbols. Just chop off the last grep expression and it should pretty much give you what you want.</p>
What are the most useful (custom) code snippets for C#? <p>What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#?</p> <p>Anyone want to post a good custom one you created yourself?</p> <p><a href="http://en.wikipedia.org/wiki/Ferris_Bueller" rel="nofollow">Anyone?... Bueller?</a></p>
<p>There's plenty of code snippets within Visual Studio for basic programming structure but I wouldn't necessarily rate one higher than another. </p> <p>I would definitely say the best ones are the custom snippets you define yourself to accomplish more specific tasks that you may find yourself using on a regular basis. Definitely a big time saver. </p> <p>A fairly basic intro to creating custom snippets can be found at <a href="http://www.15seconds.com/issue/080724.htm">http://www.15seconds.com/issue/080724.htm</a> to help with this.</p>
Deciphering C++ template error messages <p>I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype.</p> <p>Are there any tricks to deciphering these errors?</p> <p>EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.</p>
<p>You can try the following tool to make things more sane:</p> <p><a href="http://www.bdsoft.com/tools/stlfilt.html">http://www.bdsoft.com/tools/stlfilt.html</a></p>
Moving ViewState out of the page? <p>We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it.</p> <p>I'd love to hear some techniques other people have used to move ViewState to a custom provider.</p> <p>That said, a few caveats:</p> <ul> <li>We serve on average 2 Million unique visitors per hour.</li> <li>Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database.</li> <li>We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback.</li> </ul> <p>Ideas?</p>
<p>How do you handle Session State? There is a built-in "store the viewstate in the session state" provider. If you are storing the session state in some fast, out of proc system, that might be the best option for the viewstate.</p> <p>edit: to do this add the following code to the your Page classes / global page base class</p> <pre><code> protected override PageStatePersister PageStatePersister { get { return new SessionPageStatePersister(this); } } </code></pre> <p>Also... this is by no means a perfect (or even good) solution to a large viewstate. As always, minimize the size of the viewstate as much as possible. However, the SessionPageStatePersister is relatively intelligent and avoids storing an unbounded number of viewstates per session as well as avoids storing only a single viewstate per session.</p>
Free text search integrated with code coverage <p>Is there any tool which will allow me to perform a free text search over a system's code, but only over the code which was actually executed during a particular invocation?</p> <p>To give a bit of background, when learning my way around a new system, I frequently find myself wanting to discover where some particular value came from, but searching the entire code base turns up far more matches than I can reasonably assess individually.</p> <p>For what it's worth, I've wanted this in Perl and Java at one time or another, but I'd love to know if any languages have a system supporting this feature.</p>
<p>You can generally twist a code coverage tool's arm and get a report that shows the paths that have been executed during a given run. This report should show the code itself, with the first few columns marked up according to the coverage tool's particular notation on whether a given path was executed.</p> <p>You might be able to use this straight up, or you might have to preprocess it and either remove the code that was not executed, or add a new notation on each line that tells whether it was executed (most tools will only show path information at control points):</p> <p>So from a coverage tool you might get a report like this:</p> <pre><code>T- if(sometest) { x somecode; } else { - someother_code; } </code></pre> <p>The notation T- indicates that the if statement only ever evaluated to true, and so only the first part of the code executed. The later notation 'x' indicates that this line was executed.</p> <p>You should be able to form a regex that matches only when the first column contains a T, F, or x so you can capture all the control statements executed and lines executed.</p> <p>Sometimes you'll only get coverage information at each control point, which then requires you to parse the C file and mark the execute lines yourself. Not as easy, but not impossible either.</p> <p>Still, this sounds like an interesting question where the solution is probably more work than it's worth...</p>
How can I upsert a bunch of ActiveRecord objects and relationships in Rails? <p>I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop.</p> <p>I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data.</p> <p>I believe that the way I'm doing it now is very inefficient:</p> <pre><code># routes is an array of [number, destination] that I build while iterating over the data routes.uniq.each do |route| number = route[0] destination = route[1] r = Route.find_by_number_and_destination(number, destination) if !r r = Route.new :number =&gt; number, :destination =&gt; destination r.save end # I have to check if it already exists because I can't find a way # to create a uniqueness constraint on the join table with 2 foreign keys r.stops &lt;&lt; stop unless r.stops.include? stop end </code></pre> <p>Basically, I have to do 2 things for every route I find: 1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist.</p> <p>Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?</p>
<p>If I get it right, you (should) have 2 models. A Route model, and a Stop model.</p> <p>Here's how I would define these models:</p> <pre><code>class Route &lt; ActiveRecord::Base has_and_belongs_to_many :stops belongs_to :stop, :foreign_key =&gt; 'destination_id' end class Stop &lt; ActiveRecorde::Base has_and_belongs_to_many :routes end </code></pre> <p>And here's how I would set up my tables:</p> <pre><code>create_table :routes do |t| t.integer :destination_id # Any other information you want to store about routes end create_table :stops do |t| # Any other information you want to store about stops end create_table :routes_stops, :primary_key =&gt; [:route_id, :stop_id] do |t| t.integer :route_id t.integer :stop_id end </code></pre> <p>Finally, here's the code I'd use:</p> <pre><code># First, find all the relevant routes, just for caching. Route.find(numbers) r = Route.find(number) r.destination_id = destination r.stops &lt;&lt; stop </code></pre> <p>This should use only a few SQL queries.</p>
Free JSP plugin for eclipse? <p>I was looking out for a free plugin for developing/debugging JSP pages in eclipse.<br /> Any suggestions? </p>
<p>The <a href="http://wiki.eclipse.org/Category:Eclipse_Web_Tools_Platform_Project" rel="nofollow">Eclipse Web Tools Platform Project</a> includes a JSP debugger. I have only ever needed to use it with Tomcat so I cannot say how well it works with other servlet containers.</p>
Best Ruby on Rails social networking framework <p>I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. </p> <p>Searching the web I found three such frameworks. Which of these three would you recommend using and why?</p> <p><a href="http://portal.insoshi.com/">http://portal.insoshi.com/</a></p> <p><a href="http://www.communityengine.org/">http://www.communityengine.org/</a></p> <p><a href="http://lovdbyless.com/">http://lovdbyless.com/</a></p>
<p>It depends what your priorities are.</p> <p>If you really want to learn RoR, <strong>do it all from scratch</strong>. Seriously. Roll your own. It's the best way to learn, far better than hacking through someone else's code. If you do that, sometimes you'll be learning Rails, but sometimes you'll just be learning that specific social network framework. And <strong>you won't know which is which...</strong></p> <p>The type of site you're suggesting sounds perfect for a Rails project. If you get stuck, <strong>then</strong> go browse the repositories of these frameworks. Who cares if you're reinventing the wheel? It's your site, your vision, your rules.</p> <p>If you just want a site up and running, then I would pick Insoshi or LovdbyLess simply because they're out of the box apps so you'll have to do less to do get running. I suggest trying to install them both, and introducing yourself in the Google Groups. That'll give you a good indication of wether you're going to get along.</p>
Cannot handle FaultException <p>i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract. </p> <p>here is the code below;</p> <pre><code>public void Foo() { try { DoSomething(); // throws FaultException&lt;FooFault&gt; } catch (FaultException) { throw; } catch (Exception ex) { myProject.Exception.Throw&lt;FooFault&gt;(ex); } } </code></pre> <p>in service contract;</p> <pre><code>[FaultException(typeof(FooFault))] void Foo(); </code></pre> <p>when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?</p>
<p>Are you consuming the WCF service from Silverlight? If so, a special configuration is needed to make the service return a HTTP 200 code instead of 500 in case of error. The details are here: <a href="http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx</a></p>
Eclipse spelling engine does not exist <p>I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows.</p> <p>When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary.</p> <p>If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text Editors/Spelling" preference pane. This preference pane however states that <strong>"The selected spelling engine does not exist"</strong>, but has no control to add or install an engine.</p> <p>How can I put a spelling engine in existence?</p> <p>Update: What solved my problem was to install also the JDT. This solution was brought up on 2008-09-07 and was accepted, but is now missing.</p>
<p>The CDT version of Ganymede apparently shipped improperly configured. After playing around for a while, I have come up with the following steps that fix the problem.</p> <ol> <li>Export your Eclipse preferences (File > Export > General > Preferences).</li> <li>Open the exported file in a text editor.</li> <li><p>Find the line that says</p> <pre>/instance/org.eclipse.ui.editors/spellingEngine=org.eclipse.jdt.internal.ui.text.spelling.DefaultSpellingEngine</pre></li> <li><p>Change it to</p> <pre>/instance/org.eclipse.ui.editors/spellingEngine=org.eclipse.cdt.internal.ui.text.spelling.CSpellingEngine</pre></li> <li><p>Save the preferences file.</p></li> <li>Import the preferences back into Eclipse (File > Import > General > Preferences).</li> </ol> <p>You should now be able to access the Spelling configuration page as seen above.</p> <p>Note: if you want to add a custom dictionary, Eclipse must be able to access and open the file (i.e. it must exist - an empty file will work)</p>
How to disable Visual Studio macro "tip" balloon? <p>Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says:</p> <blockquote> <p>Visual Studio .NET macros</p> <p>To stop the macro from running, double-click the spinning cassette.<br /> Click here to not show this balloon again.</p> </blockquote> <p>I have trouble clicking the balloon because my macro runs so quickly.</p> <p>Is this controllable by some dialog box option?</p> <p>(I found someone else asking this question on <a href="http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.ide/2005-11/msg00267.html">some other site</a> but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)</p>
<p>This will disable the pop up:</p> <p>For Visual Studio 2008:</p> <pre>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0<br> DWORD DontShowMacrosBalloon=6</pre> <p>For Visual Studio 2010 (the DWORD won't be there by default, use <code>New | DWORD value</code> to create it):</p> <pre>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0<br> DWORD DontShowMacrosBalloon=6</pre> <p>Delete the same key to re-enable it.</p>
How do I publish a Asp.NET web application using MSBuild? <p>I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;</p> <pre><code>&lt;target name="publish-artifacts-to-build"&gt; &lt;msbuild project="my-solution.sln" target="Publish"&gt; &lt;property name="Configuration" value="debug" /&gt; &lt;property name="OutDir" value="builds\" /&gt; &lt;arg line="/m:2 /tv:3.5" /&gt; &lt;/msbuild&gt; &lt;/target&gt; </code></pre> <p>and all I get is this as a response;</p> <pre><code>[msbuild] Skipping unpublishable project. </code></pre> <p>Is it possible to publish web applications via the command line in this way?</p>
<p>The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. You would want to use the AspNetCompiler task, rather than the MSBuild task. See <a href="http://msdn2.microsoft.com/en-us/library/ms164291.aspx">http://msdn2.microsoft.com/en-us/library/ms164291.aspx</a> for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task. </p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1032073&amp;SiteID=1">Source</a></p>
Something like a callback delegate function in php <p>I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically some resource-intensive calls that get queued, cached, and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.</p> <p>I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? </p>
<p>(Apart from the observer pattern) you can also use <a href="http://php.net/manual/function.call-user-func.php" rel="nofollow"><code>call_user_func()</code></a> or <a href="http://nl2.php.net/manual/function.call-user-func-array.php" rel="nofollow"><code>call_user_func_array()</code></a>.</p> <p>If you pass an <code>array(obj, methodname)</code> as first parameter it will invoked as <code>$obj-&gt;methodname()</code>.</p> <pre> &lt;?php class Foo { public function bar($x) { echo $x; } } function xyz($cb) { $value = rand(1,100); call_user_func($cb, $value); } $foo = new Foo; xyz( array($foo, 'bar') ); </pre>
Winforms c# - Set focus to first child control of TabPage <p>Say I have a <code>Textbox</code> nested within a <code>TabControl</code>. </p> <p>When the form loads, I would like to focus on that <code>Textbox</code> (by default the focus is set to the <code>TabControl</code>).</p> <p>Simply calling <code>textbox1.focus()</code> in the <code>Load</code> event of the form does not appear to work. </p> <p>I have been able to focus it by doing the following:</p> <pre><code> private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } </code></pre> <p><strong>My question is:</strong></p> <p>Is there a more elegant way to do this?</p>
<p>The following is the solution:</p> <pre><code>private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } </code></pre> <p>The better question would however be why... I'm not entirely sure what the answer to that one is.</p> <p>Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.</p>
What are the best Visual Studio addins? <p>I currently use Resharper and have for a few years now. I know there are a ton of other useful addins out there but i never seem to have the time to sort through them to see which is worthy of using. So i was hoping some of you would be able to help me do some sorting.</p>
<p><a href="http://stackoverflow.com/questions/2767/do-you-have-any-recommended-add-onsplugins-for-microsoft-visual-studio" rel="nofollow">Third post</a> under <a href="http://stackoverflow.com/questions/tagged/visualstudio" rel="nofollow">visualstudio</a> tag</p>
How do I write a for loop in bash <p>I'm looking for the basic loop like:</p> <pre><code>for(int i = 0; i &lt; MAX; i++) { doSomething(i); } </code></pre> <p>but for bash. </p>
<p>See: <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html">this site</a></p> <pre><code> for i in $(seq 1 10); do echo $i done </code></pre>
How can I map a list of strings to my entity using NHibernate? <p>I've got two tables in my database: Articles and Tags</p> <p>The Tags tables consist of ArticleID (foreign key) and a Tag (varchar).</p> <p>Now I need to map an articles tags into a readonly collection on Article entity, either using IList Tags or ReadOnlyCollection Tags.</p> <p>I've consulted the NHibernate reference material, but I can't seem to figure when to use Set, Bag and the other Nhibernate collections. I've seen examples using the ISet collection, but I really don't like to tie my entity classes to a NHibernate type.</p> <p>How can I do the mapping in NHibernate?</p> <p>Thank you in advance.</p> <p>edit: I ended up using a <code>&lt;bag&gt;</code> instead, as it doesn't require an index:</p> <pre><code>&lt;bag name="Tags" table="Tag" access="nosetter.camelcase" lazy="false"&gt; &lt;key column="ArticleId" /&gt; &lt;element column="Tag" type="System.String" /&gt; &lt;/bag&gt; </code></pre>
<p>The type of collection to use in your mapping depends on how you want to represent the collection in code. The settings map like so:</p> <ul> <li>The <code>&lt;list&gt;</code> maps directly to an IList.</li> <li>The <code>&lt;map&gt;</code> maps directly to an IDictionary.</li> <li>The <code>&lt;bag&gt;</code> maps to an IList. A does not completely comply with the IList interface because the Add() method is not guaranteed to return the correct index. An object can be added to a <code>&lt;bag&gt;</code> without initializing the IList. Make sure to either hide the IList from the consumers of your API or make it well documented.</li> <li>The <code>&lt;set&gt;</code> maps to an Iesi.Collections.ISet. That interface is part of the Iesi.Collections assembly distributed with NHibernate.</li> </ul> <p>so if you want an IList to be returned, then you would use the <code>&lt;list&gt;</code> mapping. In your case, I'd probably map using the <code>&lt;list&gt;</code> mapping.</p>
Deploying a project using LINQ to SQL <p>I am working on a winforms application using LINQ to SQL - and am building the app using a SQL Express instance on my workstation. The final installation of the project will be on a proper SQL Server 2005. </p> <p>The database has the same name, and all tables are identical but the hostname is different. </p> <p>The only way I have found to make my app work from one machine to the next is to re-open the code in Visual Studio, delete all of the objects referring to the SQL express instance from my .mdbl, save the project, connect to the other server, drag all of the references back on, and rebuild the application for release once more.</p> <p>an answer here suggested that one can simply modify the app.config/web.config file - whih would work for asp.net, but this is a winforms application. What's the correct way of making LINQ to SQL apps use a new database without having to re-open the app in visual studio?</p>
<p>If I understand your problem correctly, you simply change the database's connection string in your app.config / web.config.</p> <p><strong>Edit</strong>, post clarification: You have the connection strings stored somewhere. They might be in the app.config of your server. Still, you get them from somewhere and that somewhere may be in an app.config. Use that then :)</p>
VS 2005 & 2008 library linking <p>Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator.</p> <p>This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number.</p> <p>There are no such problems when the program is compiled with VS 2005.</p> <p>What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur.</p>
<p>VS2005 and VS2008 use different STL implementations. When the VS2005 code returns a vector, the object has memory layout different from what VS2008 expects. That should be the reason for the broken values you see in the returned date.</p> <p>As a rule of thumb, you should always compile all C++ modules of a project with the same compiler and all settings/#defines equal.</p> <p>One particular #define that causes similar behaviour is the SECURE_SCL #define of VS2008. Two modules compiled with different settings will create exactly your problems, because #defining SECURE_SCL introduces more member variables to various C++ library classes.</p>
Practical solution to center vertically and horizontally in HTML that works in FF, IE6 and IE7 <p>What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?</p> <p>Some details:</p> <ul> <li><p>I am looking for solution for the entire page.</p></li> <li><p>You need to specify only width of the element to be centered. Height of the element is not known in design time.</p></li> <li><p>When minimizing window, scrolling should appear only when all white space is gone. In other words, width of screen should be represented as: </p></li> </ul> <p>"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+<br /> "centeredElement width=widthOfCenteredElement"+<br /> "rightSpace width=(screenWidth-widthOfCenteredElement)/2" </p> <p>And the same for the height:</p> <p>"topSpace height=(screenHeight-heightOfCenteredElement)/2"+<br /> "centeredElement height=heightOfCenteredElement"+<br /> "bottomSpace height=(screenWidth-heightOfCenteredElement)/2"</p> <ul> <li>By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility.</li> </ul>
<p>From <a href="http://www.webmonkey.com/codelibrary/Center_a_DIV" rel="nofollow">http://www.webmonkey.com/codelibrary/Center_a_DIV</a></p> <pre><code>#horizon { text-align: center; position: absolute; top: 50%; left: 0px; width: 100%; height: 1px; overflow: visible; display: block } #content { width: 250px; height: 70px; margin-left: -125px; position: absolute; top: -35px; left: 50%; visibility: visible } &lt;div id="horizon"&gt; &lt;div id="content"&gt; &lt;p&gt;This text is&lt;br&gt;&lt;emphasis&gt;DEAD CENTRE&lt;/emphasis &gt;&lt;br&gt;and stays there!&lt;/p&gt; &lt;/div&gt;&lt;!-- closes content--&gt; &lt;/div&gt;&lt;!-- closes horizon--&gt; </code></pre>
Animation Extender Problems <p>I have just started working with the <code>AnimationExtender</code>. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel.</p> <p>Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the <code>ScriptManager</code> to detect when the postback is complete and have made some progress. I have added two javascript methods to the page.</p> <pre><code>function linkPostback() { var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) } function playAnimation() { var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); } </code></pre> <p>And I’ve changed the <code>btnOpenList.OnClientClick=”linkPostback();”</code></p> <p>This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the <code>onclkBehavior.pause()</code> has no effect. I can get around this by setting the <code>AnimationExtender.Enabled = false</code> and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the <code>AnimationExtender</code> via javascript but this has no effect.</p> <p>Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the buttons click event so I can control when the animation is fired.</p> <p>Hope that makes sense.</p> <p>Thanks</p> <p>DG</p>
<p>The flow you are seeing is something like this:</p> <ol> <li>Click on button</li> <li>AnimationExtender catches action and call clickOn callback</li> <li>linkPostback starts asynchronous request for page and then returns flow to AnimationExtender</li> <li>Animation begins</li> <li>pageRequest returns and calls playAnimation, which starts the animation again</li> </ol> <p>I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click.</p> <p>Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to "display: none;" and having your own button call linkPostback().</p> <p>Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is:</p> <pre><code>function linkPostback() { var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) } function playAnimation() { AnimationExtender.Enabled = true; var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); AnimationExtender.Enabled = false; } </code></pre> <p>As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some "Loading..." thing, make it about the right size, and then populate the actual contents when it arrives.</p>
How do I export (and then import) a Subversion repository? <p>I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account.</p> <p>How would I go about doing this?</p>
<p>If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder.</p> <p>If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using <code>svnadmin dump</code> will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use <code>svnadmin load</code>, which will essentially replay all the commits along with its metadata (author, timestamp, etc).</p> <p>You can read more about the dump/load process here:</p> <p><a href="http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate">http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate</a></p> <p>Also, if you do <code>svnadmin load</code>, make sure you use the <code>--force-uuid</code> option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository.</p> <p>If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case.</p>
Apache rewrite based on subdomain <p>Im trying to redirect requests for a wildcard domain to a sub-directory.<br /> ie. <code>something.blah.domain.com</code> --> <code>blah.domain.com/something</code></p> <p>I dont know how to get the subdomain name to use in the rewrite rule.</p> <p><strong>Final Solution:</strong></p> <pre><code>RewriteCond %{HTTP_HOST} !^blah\.domain\.com RewriteCond %{HTTP_HOST} ^([^.]+) RewriteRule ^(.*) /%1/$1 [L] </code></pre> <p>Or as pointed out by pilif</p> <pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\.media\.xnet\.tk$ </code></pre>
<p>You should have a look at the <a href="http://httpd.apache.org/docs/2.2/rewrite/" rel="nofollow" title="URL Rewriting Guide">URL Rewriting Guide</a> from the apache documentation.</p> <p>The following is untested, but it should to the trick:</p> <pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$ RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R] </code></pre> <p>This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.</p>
How do you set your Cocoa application as the default web browser? <p>How do you set your Cocoa application as the default web browser?</p> <p>I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).</p>
<p>There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.</p> <p><strong>1) Add the URL schemes your app can handle to your application's info.plist file</strong></p> <p>To add support for <code>http://</code> and <code>https://</code> you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.</p> <pre class="lang-xml prettyprint-override"><code>&lt;key&gt;CFBundleURLTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;CFBundleURLName&lt;/key&gt; &lt;string&gt;http URL&lt;/string&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;http&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;dict&gt; &lt;key&gt;CFBundleURLName&lt;/key&gt; &lt;string&gt;Secure http URL&lt;/string&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;https&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre> <p><strong>2) Write an URL handler method</strong></p> <p>This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:</p> <pre><code>- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { // Get the URL NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; //TODO: Your custom URL handling code here } </code></pre> <p><strong>3) Register the URL handler method</strong></p> <p>Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed <code>self</code> as the event handler, assuming that we're calling <code>setEventHandler</code> from the same object that defines the <code>getUrl:withReplyEvent:</code> method.</p> <p>You should add this code somewhere in your application's initialisation code.</p> <pre><code>NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager]; [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; </code></pre> <p>Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:</p> <pre><code>[em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:'WWW!' andEventID:'OURL']; </code></pre> <p><strong>4) Set your app as the default browser</strong></p> <p>Everything we've done so far as told the OS that your application is <em>a browser</em>, now we need to make it <em>the default browser</em>.</p> <p>We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:</p> <pre><code>CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier]; OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID); OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID); //TODO: Check httpResult and httpsResult for errors </code></pre> <p>(It's probably best to ask the user's permission before changing their default browser.)</p> <p><strong>Custom URL schemes</strong></p> <p>It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is <code>com.example.MyApp</code> you should consider using <code>x-com-example-myapp://</code> URLs.</p>
64 bit tools like BoundsChecker & Purify <p>For many years I have used two great tools <a href="http://www.compuware.com/products/devpartner/visualc.htm">BoundsChecker</a> &amp; <a href="http://www-01.ibm.com/software/awdtools/purify/win/">Purify</a>, but the developers of these applications have let me down, they no longer put effort into maintaining them or developing them. We have corporate accounts with both companies, and they both tell me that they have no intention of producing versions to support 64 bit applications.</p> <p>Can anyone recommend either open source or commercial alternatives that support 64 bit native C++/MFC applications?</p>
<p>Viva64 (<a href="http://www.viva64.com/viva64-tool/" rel="nofollow">http://www.viva64.com/viva64-tool/</a>) tool provides detection of errors typical of 64-bit Windows applications. Viva64 is a lint-like static analyzer of C/C++ code. Viva64 integrates into Visual Studio 2005/2008 environment and provides user-friendly interface to test your software projects.</p>
Problems with mouseout event <p>I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.</p> <p>The html looks like this:</p> <pre><code>&lt;div onmouseover="jsHoverIn('1')" onmouseout="jsHoverOut('1')"&gt; &lt;div style="" id="image1" /&gt; &lt;div id="text1" style="display: none;"&gt; &lt;p&gt;some content&lt;/p&gt; &lt;p&gt;some more content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And the javascript (It uses scriptaculous):</p> <pre><code>function jsHoverIn (id) { if ( !visible[id] ) { new Effect.Fade ("image"+id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text"+id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get( id ); scope.each( function( effect ){ effect.cancel() } ); new Effect.Fade ("text"+id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image"+id, {queue: { position: 'end', scope: id } }); visible[id] = false; } </code></pre> <p>This seems really simple, but i just cant wrap my head around it.</p>
<p>I'd give the container div:</p> <pre><code>position: relative; </code></pre> <p>and add a third div in the container (should be the last child of the container) with:</p> <pre><code>position: absolute; top: 0; bottom: 0; left: 0; right: 0; </code></pre> <p>and catch the mouseover and mouseout events on this div instead.</p> <p>Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it.</p> <p><em>Edit:</em></p> <p>What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event.</p>
In HTML, what should happen to a selected, disabled option element? <p>In my specific example, I'm dealing with a drop-down, e.g.:</p> <pre><code>&lt;select name="foo" id="bar"&gt; &lt;option disabled="disabled" selected="selected"&gt;Select an item:&lt;/option&gt; &lt;option&gt;an item&lt;/option&gt; &lt;option&gt;another item&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.</p> <p><strong>Update:</strong> To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs onchange(). This is <em>fairly</em> well 'progressively enhanced', in that a submit button is present, and only removed via javascript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out 'onchange' drop downs altogether, or should the "select..." option be selectable, just with no effect?</p>
<p>The HTML specs are a bit vague (ie. completely lacking) with regard to this odd combination. They do say that a form element with the disabled attribute set should not be successful, so it really <em>can't</em> be selected.</p> <p>The browser may well render it so that it looks selected, but it shouldn't show up in the POSTed data. Looks like Opera's got it right to me.</p>
I understand threading in theory but not in practice in .net <p>I have a basic cs-major understanding of multi-threading but have never had to do anything beyond simple timers in an application. Does anyone know of a good resource that will give me a tour how to work with multi-threaded applications, explaining the basics and maybe posing some of the more difficult stuff?</p>
<p>This is a great free resource by Joseph Albahari. <a href="http://www.albahari.com/threading/">Threading in C#</a></p>
Mediawiki custom tag Stops page parsing <p>I created a few mediawiki custom tags, using the guide found here</p> <p><a href="http://www.mediawiki.org/wiki/Manual:Tag_extensions" rel="nofollow">http://www.mediawiki.org/wiki/Manual:Tag_extensions</a></p> <p>I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.</p> <p>Any Ideas?</p> <pre><code>if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) { $wgHooks['ParserFirstCallInit'][] = 'tagregister'; } else { // Otherwise do things the old fashioned way $wgExtensionFunctions[] = 'tagregister'; } function tagregister(){ global $wgParser; $wgParser->setHook('tag1','tag1func'); $wgParser->setHook('tag2','tag2func'); return true; } function tag1func($input,$params) { return "It called me"; } function tag2func($input,$params) { return "It called me -- 2"; }</code></pre> <p>Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signalling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behaviour.</p>
<p>Never used Mediawiki but that sort of problem in my experience is indicative of a php error that occurred but was suppressed either with the @ operator or because php error output to screen is turned off.</p> <p>I hate to resort to this debugging method but when absolutely and utterly frustrated in php I will just start putting echo statements every few lines (always with a marker so I remember to remove them later), to figure out exactly where the error is coming from. Eventually you'll get to the bottom of the rabbit hole and figure out exactly what the problematic line of code is.</p>
Is there a way to generalize an Apache ANT target? <p>We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.</p> <p>The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.</p>
<p>I would suggest to work with <a href="http://ant.apache.org/manual/Tasks/macrodef.html" rel="nofollow">macros</a> over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).</p> <p>You simply refactor your Ant script starting with your target:</p> <pre><code>&lt;target name="vss.check"&gt; &lt;vssadd localpath="D:\build\build.00012.zip" comment="Added by automatic build"/&gt; &lt;/target&gt; </code></pre> <p>creating a macro (notice the copy/paste and replacement with the @{file}):</p> <pre><code>&lt;macrodef name="private-vssadd"&gt; &lt;attribute name="file"/&gt; &lt;sequential&gt; &lt;vssadd localpath="@{file}" comment="Added by automatic build"/&gt; &lt;/sequential&gt; &lt;/macrodef&gt; </code></pre> <p>and invoke the macros with your files:</p> <pre><code>&lt;target name="vss.check"&gt; &lt;private-vssadd file="D:\build\File1.zip"/&gt; &lt;private-vssadd file="D:\build\File2.zip"/&gt; &lt;/target&gt; </code></pre> <p>Refactoring, "the Ant way"</p>
Garbage Collection: Is it necessary to set large objects to null in a Dispose method? <p>Is it necessary to set large objects to <code>null</code> when implementing a <code>Dispose()</code> method?</p>
<p>If a class has a Dispose method the best practice is to call it. the reason behind that is that Dispose runs when called, whereas setting the object to null simply adds a entry to the Finalize queue in GC, and we cannot determine when GC will run.</p> <p>There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector. Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed to the .NET Framework. Managed objects that use native resources (such as the FileStream class) implement the IDisposable interface.</p> <p>An elegant means of inoking Dispose that have adopted is using the "using" construct. For those of you who may not be familiar with the construct, it provide a means to implicity invoke Dispose() on an instance that implements IDisposable even if an exception is thrown durring the operation. The following is an example of the using construct: </p> <pre><code>using(DisposableClass dc = new DisposableClass()) { dc.PerformActionOnUmanagedResources(); dc.PerformAnotherActionOnUmanagedResources(); } </code></pre> <p>In the previous example, if an exception was thrown in the PerformActionOnUmanagedResources() method, although the PerformAnotherActionOnUmanagedResources() method would not be processed, the using block will still implicity invoke the Dispose method on dc ensuring the realese of any unmanaged resources.</p>
Database abstraction layers for (Visual) C++ <p>What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons?</p>
<ol> <li><a href="http://msdn.microsoft.com/en-us/library/ms710252.aspx" rel="nofollow">Microsoft ODBC</a>.</li> <li>The MFC ODBC classes such as <a href="http://msdn.microsoft.com/en-us/library/2dhc1abk.aspx" rel="nofollow">CDatabase</a>.</li> <li><a href="http://msdn.microsoft.com/en-us/library/ms722784.aspx" rel="nofollow">OleDB</a> (via COM).</li> <li>And you can always go through the per-RDBMS native libraries (for example, the <a href="http://msdn.microsoft.com/en-us/library/ms722784.aspx" rel="nofollow">SQL Server native library</a>)</li> <li><a href="http://msdn.microsoft.com/en-us/library/aa163992.aspx" rel="nofollow">DAO</a> (don't).</li> <li>3rd party ORM providers.</li> </ol> <p>I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.</p>
Replace huge Case statement in Classic ASP <p>I have a 200+ case statement in Classic ASP which is getting out of control. It sets 5 variables, based on which case is selected. Address, Phone, Name etc. Just sets the variables and nothing else in each case.</p> <p>Databases or files are not an option for this application.</p> <p>Coming from the Perl world I would use a hash to store this info. </p>
<p>Getting out of control? I think it's already out of control!</p> <p>Can you not categorise the cases into 'x' general areas and split down into helper routines?</p>
Does "display: marker" work in any current browsers, and if so, how? <p>I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.</p> <p>My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS. So the HTML is like this:</p> <pre><code>&lt;ol&gt; &lt;li&gt;The&lt;li&gt; &lt;li&gt;quick&lt;/li&gt; &lt;li&gt;brown&lt;/li&gt; &lt;/ol&gt; &lt;ol&gt; &lt;li&gt;fox&lt;/li&gt; &lt;li&gt;jumped&lt;/li&gt; &lt;li&gt;over&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>and the CSS, which I <em>think</em> is correct according to <a href="http://www.w3.org/TR/CSS2/generate.html#markers" rel="nofollow">the spec</a>, is like this:</p> <pre><code>html { counter-reset: myCounter; } li { counter-increment: myCounter; } li:before { content: counter(myCounter)". "; display: marker; width: 5em; text-align: right; marker-offset: 1em; } </code></pre> <p>But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).</p> <p>So, does anyone know if markers are <em>supposed</em> to work? Quirksmode.org isn't being its usual helpful self in this regard :(.</p>
<p>Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support. I suppose that didn’t help its popularity …</p> <p>Source: <a href="http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display" rel="nofollow">http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display</a> (German)</p>
Floats messing up in Safari browsers <p>I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to <code>padding</code> and <code>position:relative</code>, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.</p> <p>The main section of css that seems to be causing the problem is:</p> <pre class="lang-css prettyprint-override"><code>#settings{ float:left; } #right_content{ margin-top:20px; margin-left:440px; width:400px; } </code></pre> <p>This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.</p> <p>The site is available at: <a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow">http://frickinsweet.com/tools/Theme.mvc.aspx</a> to see the source code.</p>
<p>Have you tried floating the #right_content div to the right?</p> <pre class="lang-css prettyprint-override"><code>#right_content{ float: right; margin-top: 20px; width: 400px; } </code></pre>
Why the option to use attributes in new ATL projects was removed from Visual Studio 2008? <p>This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects."</p> <p>But WHY?!! </p>
<p>In ATL these attributes were a compiler trick. They were not a core part of the platform like attributes in C#. They were also more confusing to debug than macros's and the method of dumping generated attribute code was a hassle.</p> <p>I suspect another issue is likely to have been C++ compiler compatibility and standards-adherence. Attributes didn't make for more beautiful C++ code, and perhaps this syntax may be used in a future version of a real C++ standard.</p>
Override ScriptControl or BaseValidator for an async ASP.NET validator control? <p>I'm planning to develop an ASP.NET server control to provide asynchronous username availability validation for new user registrations. The control will allow a developer to point it at a "username" TextBox and it will provide an indication of whether or not the username is available. Like <a href="http://encosia.com/2007/07/02/aspnet-username-availability-checking-via-ajax/" rel="nofollow">this example</a>, but without the clunky UpdatePanel.</p> <p>One design decision that's giving me headaches is whether to inherit from <strong>ScriptControl</strong> or <strong>BaseValidator</strong>.</p> <p>By implementing it as a <strong>ScriptControl</strong>, I can make the client side portion easier to deal with and easily localize it with a resx.</p> <p>However, I want to make sure that the validator functions properly with respect to Page.IsValid. The only way I know to do this is to override <strong>BaseValidator</strong> and implement <code>EvaluateIsValid()</code>.</p> <p>So, my question is, how would you suggest structuring this control? Is inheriting from BaseValidator the best (only) way to get the validator part right, or can I do that in some other way?</p>
<p>You should be able to do both if you implement the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.iscriptcontrol.aspx" rel="nofollow">IScriptControl</a> interface while also deriving from BaseValidator:</p> <pre><code>public class YourControl : IScriptControl, BaseValidator </code></pre> <p>To implement the IScriptControl interface means your control will also have to have the GetScriptReferences and GetScriptDescriptors methods.</p>
CSS - Placement of a div in the lower left-hand corner <p>I wish I were a CSS smarty .... </p> <p>How can you place a div container in the lower left-hand corner of the web page; taking into account the users scroll-position?</p>
<p>The attributes...</p> <pre><code>position: fixed; left: 0; bottom: 0; </code></pre> <p>...should do the job in every browser except IE. If supporting IE users is important for your site, you need to add some ugly Javascript.</p>
How to iterate a jagged array? <p>This has been driving me crazy for a few days. Why doesn't the following work?</p> <blockquote> <pre><code> Dim arr(3, 3) As Integer For y As Integer = 0 To arr.GetLength(0) - 1 For x As Integer = 0 To arr.GetLength(y) - 1 arr(y, x) = y + x Next Next </code></pre> </blockquote> <p>Also, what if the array looked like this instead?</p> <pre><code>{ {1, 2, 3}, {4, 5, 6, 7, 8, 9, 9, 9}, {5, 4, 3, 2} } </code></pre>
<p>Because there is no '2' or '3' dimension. Should be .GetLength(1) instead of .GetLength(y)</p> <p>Also: in VB.Net array declarations work a little differently. The subscript you specify in the declaration is the last index, not the number of items created like with C# or C++. But the array is still 0-indexed like C# or C++, instead of 1-indexed like VB6. That means that if you move to VB.Net from a different language your array instincts are probably wrong, no matter which language it is. In VB.Net, <em>Dim arr(3,3) As Integer</em> actually creates a <strong>4x4</strong> array. </p>
Can I prevent user pasting Javascript into Design Mode IFrame? <p>I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums.</p> <p>I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript:</p> <pre><code>&lt;script type="text/javascript"&gt; // Do some nasty stuff &lt;/script&gt; </code></pre> <p>Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.</p> <p>Am I worrying over nothing?</p> <p>Any advice would be great, couldn't find much searching Google.</p> <p>Anthony</p>
<blockquote> <p>...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. </p> <p>Am I worrying over nothing?</p> </blockquote> <p>Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript.</p> <p>AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users.</p>
How to convince a project sponsor that all functions in your code should have unit tests <p>Non technical people in most cases do not see any value in writing unit tests. They just want to have basic code completed and do not spend money and time on such things like unit tests. Later, every day they just to ask to fix a one bug more. Projects are missing deadlines and they still don't see value in good automated tests.</p>
<p>The best way is to not get so technical with "non techical" people. Just build it into the delivery time without going into details. </p> <p>On the flipside, it sounds like the project deadlines were not realistic to actually build it.</p>
Average User Download Speeds <p>Any ideas what the average user's download speed is? I'm working on a site that streams video and am trying to figure out what an average download speed as to determine quality.</p> <p>I know i might be comparing apples with oranges but I'm just looking for something to get a basis for where to start.</p>
<p><a href="http://speedtest.net/global.php">Speedtest.net</a> has a lot of stats broken down by country, region, city and ISP. Not sure about accuracy, since it's only based on the people using their "bandwidth measurement" service.</p>
Best way to detect a release build from a debug build? .net <p>So I have about 10 short css files that I use with mvc app. There are like error.css login.css etc... Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this</p> <pre><code>if(Debug.Mode){ &lt;link rel="stylesheet" type="text/css" href="error.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="login.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="menu.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="page.css" /&gt; } else { &lt;link rel="stylesheet" type="text/css" href="site.css" /&gt; } </code></pre> <p>I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.</p>
<p>Specifically, like this in C#:</p> <pre><code>#if (DEBUG) Debug Stuff #endif </code></pre> <p>C# has the following preprocessor directives:</p> <pre><code>#if #else #elif // Else If #endif #define #undef // Undefine #warning // Causes the preprocessor to fire warning #error // Causes the preprocessor to fire a fatal error #line // Lets the preprocessor know where this source line came from #region // Codefolding #endregion </code></pre>
What is the simplest way to find the difference between 2 times in python? <p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
<p>Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using <code>datetime.datetime.combine</code>, then subtracting:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; t1 = datetime.time(2,3,4) &gt;&gt;&gt; t2 = datetime.time(18,20,59) &gt;&gt;&gt; dummydate = datetime.date(2000,1,1) &gt;&gt;&gt; datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675) </code></pre>
What are some good usability guidelines an average developer should follow? <p>I'm not a usability specialist, and I really don't care to be one.</p> <p>I just want a small set of rules of thumb that I can follow while coding my User Interfaces so that my product has decent usability.</p> <p>At first I thought that this question would be easy to answer "Use your common sense", but if it's so common among us developers we wouldn't, as a group, have a reputation for our horrible interfaces.</p> <p>Any Suggestions?</p>
<p><img src="http://i.stack.imgur.com/G5Xcl.png" alt="simplicity"/></p> <p>Source: <a href="http://stuffthathappens.com/blog/wp-content/uploads/2008/03/simplicity.png" rel="nofollow">http://stuffthathappens.com/blog/wp-content/uploads/2008/03/simplicity.png</a></p>
Get MIME type of a local file in PHP5 without a PECL extension? <p><code>mime_content_type()</code> is deprecated.</p> <p>How can I find the <code>MIME type of a local file</code> using <code>PHP5</code> but without using this deprecated method or the <code>PECL fileinfo extension?</code></p> <p>Edit: That's what I was afraid of. It's unfortunate that they deprecated a built-in function in favour of one that requires an extension that isn't always available.</p>
<p>If you can't use the fileinfo extension, and you don't want to use mime_content_type, your options are limited.</p> <p>Most likely you'll need to do a lookup based on the file extension. mime_content_type did something a bit more intelligent and actually looked for special data in the file to determine the mime type.</p>
How many real world developers are involved with the Demoscene? <p>I grew up learning to code based on what I've experienced with the <a href="http://en.wikipedia.org/wiki/Demoscene">demoscene</a>. It seems to be a pretty sparse subculture in the US. How many developers watch or participate in the scene?</p> <p>Teaser: If you haven't checked out the scene before, take a look at one of my favorites: <a href="http://www.pouet.net/prod.php?which=30244">Debris</a> by Farbrausch. Watch on <a href="http://demoscene.tv/page.php?id=172&amp;lang=uk&amp;vsmaction=view_prod&amp;id_prod=12909">demoscene.tv</a> or download the <a href="http://www.scene.org/file.php?file=/parties/2007/breakpoint07/demo/fr-041_debris.zip&amp;fileinfo">app</a> (179k) and run it yourself. No video, all realtime rendering and audio. Think, a small group of guys wrote this for a competition on their free time.</p>
<p>I think nowadays developers are kind of "dropping out of the demo scene". In the good old days demos were all about "what could you technically squeeze out of the machine". You needed to be a good developer/coder/hacker to achieve the best. Today the development seems to be more like basic technical stuff. Most effects are already provided by the graphics adapter. It's not so much about the code, so as a coder "you can't show off". It's more about design, graphics, more design, music and even more design. That's in most cases not the developers' domain :)</p> <p>However my guess would be that most good and experienced developers today have an history in demo scene, even if it's just a small one (just being interested and astonished).</p> <p>Wow... PC-GPE still exists? :D</p>
Why does clicking a child window not always bring the application to the foreground? <p>When an application is behind another applications and I click on my application's taskbar icon, I expect the entire application to come to the top of the z-order, even if an app-modal, WS_POPUP dialog box is open.</p> <p>However, some of the time, for some of my (and others') dialog boxes, only the dialog box comes to the front; the rest of the application stays behind.</p> <p>I've looked at Spy++ and for the ones that work correctly, I can see WM_WINDOWPOSCHANGING being sent to the dialog's parent. For the ones that leave the rest of the application behind, WM_WINDOWPOSCHANGING is not being sent to the dialog's parent.</p> <p>I have an example where one dialog usually brings the whole app with it and the other does not. Both the working dialog box and the non-working dialog box have the same window style, substyle, parent, owner, ontogeny.</p> <p>In short, both are WS_POPUPWINDOW windows created with DialogBoxParam(), having passed in identical HWNDs as the third argument.</p> <p>Has anyone else noticed this behavioral oddity in Windows programs? What messages does the TaskBar send to the application when I click its button? Who's responsibility is it to ensure that <em>all</em> of the application's windows come to the foreground?</p> <p>In my case the base parentage is an MDI frame...does that factor in somehow?</p>
<p>I know this is very old now, but I just stumbled across it, and I know the answer.</p> <p>In the applications you've seen (and written) where bringing the dialog box to the foreground did <strong>not</strong> bring the main window up along with it, the developer has simply neglected to specify the owner of the dialog box.</p> <p>This applies to both modal windows, like dialog boxes and message boxes, as well as to modeless windows. Setting the owner of a modeless popup also keeps the popup above its owner at all times.</p> <p>In the Win32 API, the functions to bring up a dialog box or a message box take the owner window as a parameter:</p> <pre><code>INT_PTR DialogBox( HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent, /* this is the owner */ DLGPROC lpDialogFunc ); int MessageBox( HWND hWnd, /* this is the owner */ LPCTSTR lpText, LPCTSTR lpCaption, UINT uType ); </code></pre> <p>Similary, in .NET WinForms, the owner can be specified:</p> <pre><code>public DialogResult ShowDialog( IWin32Window owner ) public static DialogResult Show( IWin32Window owner, string text ) /* ...and other overloads that include this first parameter */ </code></pre> <p>Additionally, in WinForms, it's easy to set the owner of a modeless window:</p> <pre><code>public void Show( IWin32Window owner, ) </code></pre> <p>or, equivalently:</p> <pre><code>form.Owner = this; form.Show(); </code></pre> <p>In straight WinAPI code, the owner of a modeless window can be set when the window is created:</p> <pre><code>HWND CreateWindow( LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, /* this is the owner if dwStyle does not contain WS_CHILD */ HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam ); </code></pre> <p>or afterwards:</p> <pre><code>SetWindowLong(hWndPopup, GWL_HWNDPARENT, (LONG)hWndOwner); </code></pre> <p>or (64-bit compatible)</p> <pre><code>SetWindowLongPtr(hWndPopup, GWLP_HWNDPARENT, (LONG_PTR)hWndOwner); </code></pre> <p>Note that MSDN has the following to say about <a href="http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx" rel="nofollow">SetWindowLong[Ptr]</a>:</p> <blockquote> <p>Do not call <strong>SetWindowLongPtr</strong> with the GWLP_HWNDPARENT index to change the parent of a child window. Instead, use the <a href="http://msdn.microsoft.com/en-us/library/ms633541%28VS.85%29.aspx" rel="nofollow">SetParent</a> function. </p> </blockquote> <p>This is somewhat misleading, as it seems to imply that the last two snippets above are wrong. This isn't so. Calling <code>SetParent</code> will turn the intended popup into a <em>child</em> of the parent window (setting its <code>WS_CHILD</code> bit), rather than making it an owned window. The code above is the correct way to make an existing popup an owned window.</p>
How do I stop Visual Studio from automatically inserting asterisk during a block comment? <p>I'm tearing my hair out with this one. If I start a block comment <code>/*</code> in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk <code>*</code>. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?</p>
<p><a href="http://forums.msdn.microsoft.com/en-US/csharpide/thread/a41e3652-efe2-4f81-ad3e-94994974fcb2/">This post</a> addresses your question. The gist of it is:</p> <pre><code>Text Editor &gt; C# &gt; Advanced &gt; Generate XML documentation comments for /// </code></pre>
Best way to deal with RoutingError in Rails 2.1.x? <p>I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.</p> <p>This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.</p> <p>Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.</p> <p>In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist?</p> <p>EDIT:</p> <p>So the code here is: </p> <pre><code># File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141 def rescue_action_without_handler(exception) log_error(exception) if logger erase_results if performed? # Let the exception alter the response if it wants. # For example, MethodNotAllowed sets the Allow header. if exception.respond_to?(:handle_response!) exception.handle_response!(response) end if consider_all_requests_local || local_request? rescue_action_locally(exception) else rescue_action_in_public(exception) end end </code></pre> <p>So our best option is to override log_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController</p> <pre><code>def log_error(exception) message = '...' if should_log_exception_as_debug?(exception) logger.debug(message) else logger.error(message) end end def should_log_exception_as_debug?(exception) return (ActionController::RoutingError === exception) end </code></pre> <p>Salt for additional logic where we want different controller logic, routes, etc.</p>
<p>Nooooo!!! Don't implement method_missing on your controller! And please try to avoid action_missing as well.</p> <p>The frequently touted pattern is to add a route:</p> <pre><code>map.connect '*', :controller =&gt; 'error', :action =&gt; 'not_found' </code></pre> <p>Where you can show an appropriate error.</p> <p>Rails also has a mechanism called rescue_action_in_public where you can write your own error handling logic -- we really should clean it up and encourage people to use it. PDI! :-)</p>
Find all drive letters in Java <p>For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.</p> <p>I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).</p> <p>Any help?</p> <p><strong>EDIT:</strong> I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.</p>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()">http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()</a></p> <pre><code>File[] roots = File.listRoots(); for(int i = 0; i &lt; roots.length ; i++) System.out.println("Root["+i+"]:" + roots[i]); </code></pre> <p>google: list drives java, first hit:-)</p>
When can DataInputStream.skipBytes(n) not skip n bytes? <p>The <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInput.html#skipBytes%28int%29" rel="nofollow">Sun Documentation for DataInput.skipBytes</a> states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility."</p> <ol> <li><p>Other than reaching end of file, why might <code>skipBytes()</code> not skip the right number of bytes? (The <code>DataInputStream</code> I am using will either be wrapping a <code>FileInputStream</code> or a <code>PipedInputStream</code>.)</p></li> <li><p>If I definitely want to skip n bytes and throw an <code>EOFException</code> if this causes me to go to the end of the file, should I use <code>readFully()</code> and ignore the resulting byte array? Or is there a better way?</p></li> </ol>
<p>1) There might not be that much data available to read (the other end of the pipe might not have sent that much data yet), and the implementing class might be non-blocking (i.e. it will just return what it can, rather than waiting for enough data to fulfil the request).</p> <p>I don't know if any implementations actually behave in this way, however, but the interface is designed to permit it.</p> <p>Another option is simply that the file gets closed part-way through the read.</p> <p>2) Either readFully() (which will always wait for enough input or else fail) or call skipBytes() in a loop. I think the former is probably better, unless the array is truly vast.</p>
Where did all the java applets go? <p>When java was young, people were excited about writing applets. They were cool and popular, for a little while. Now, I never see them anymore. Instead we have flash, javascript, and a plethora of other web app-building technologies.</p> <p>Why don't sites use java applets anymore?</p> <p>I'm also curious: historically, why do you think this occurred? What could have been done differently to keep Java applets alive?</p>
<p>I think Java applets were overshadowed by Flash and ActionScript (pun unintended), being much easier to use for what Java Applets were being used at the time (animations + stateful applications). </p> <p>Flash's success in this respect in turn owes to its much smaller file sizes, as well as benefiting from the Sun vs. Microsoft suit that resulted in Microsoft removing the MSJVM from Internet Explorer, at a time of Netscape's demise and IE's heavy dominance.</p>
How to get the base 10 logarithm of a Fixnum in Ruby? <p>I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.</p> <p>What is the easiest way to get the base 10 logarithm of a Fixnum?</p>
<p>There is </p> <pre><code>Math::log10 (n) </code></pre> <p>And there is also a property of logarithms that logx(y) = log(y)/log(x) </p>
How do I reset a sequence in Oracle? <p>In <a href="http://en.wikipedia.org/wiki/PostgreSQL">PostgreSQL</a>, I can do something like this:</p> <pre><code>ALTER SEQUENCE serial RESTART WITH 0; </code></pre> <p>Is there an Oracle equivalent?</p>
<p>Here is a good procedure for resetting any sequence to 0 from Oracle guru <a href="http://asktom.oracle.com">Tom Kyte</a>. Great discussion on the pros and cons in the links below too.</p> <pre><code>[email protected]&gt; create or replace procedure reset_seq( p_seq_name in varchar2 ) is l_val number; begin execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0'; end; / </code></pre> <p>From this page: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592">Dynamic SQL to reset sequence value</a><br /> Another good discussion is also here: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597">How to reset sequences?</a></p>
Bad Smells When Reviewing Code Affects Approach? <p>G'day,</p> <p>I was thinking about a comment from <a href="http://stackoverflow.com/users/1175/kristopher-johnson" rel="nofollow">Kristopher Johnson</a> about my answer to this <a href="http://stackoverflow.com/questions/50612/software-development-quality" rel="nofollow">question</a> regarding Software Development Quality.</p> <p>I'd posted a list of software quality metrics that I could think of off the top of my head that included:</p> <ol> <li>McCabe Cyclometric Complexity - basically a measure of the number of linear paths through code.</li> <li>Levels of indentation - a measure of complexity when looking at nested decision statements.</li> <li>Distance from declaration to first use - how many statements exist between where a variable is declared and where it is first used.</li> <li>Comment percentage - how many lines of code are comments compared to source code.</li> <li>Percent test coverage - as a percentage of lines of code, how many are exercised by your suite of tests.</li> <li>Path test coverage - how many paths of execution are exercised by your tests.</li> <li>Unit coverage - how many individual units, classes, packages, etc., are exercised by your unit tests.</li> </ol> <p>Kris's comment was:</p> <blockquote> <p>Only the test-coverage metrics listed here could be considered a measure of "quality." The others are measurements of complexity and readability, which really has nothing to do with quality.</p> </blockquote> <p>Apart from the fact that I don't agree with this statement at all, it got me thinking.</p> <p>When I have to review code that has hardly any associated tests, whether unit, system or integration, I tend to approach the code much, much more warily than if I see a good suite of tests that have been successfully passed.</p> <p>Same thing when performing security audits on code. If I see unused variables, huge functions, bizarre mixtures of configs, per server, per dir, etc. being used in Apache modules it also predisposes me to approach the code very warily.</p> <p>Does anyone else use this initial "gut feeling" approach and does it affect the outcome?</p> <p>BTW I don't agree with Kris's comment because all the other metrics are definitely valid measures that will help highlight badly designed, poorly executed code. As Damian Conway says:</p> <blockquote> <p>Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.</p> </blockquote>
<p>Developed "gut feeling" is what distinguish beginners from professionals. After you gain some experience "gut feeling" becomes one of the main contributors to final decision. It doesn't matter whether you're reviewing somebody's code or creating system architecture, gut feeling guides you. However pragmatic developer must not be too self-assured. There is always a place for check-lists and other means.</p> <p>As for metrics, I totally agree with you. Metrics is meaningless if it doesn't contribute to code quality.</p>
How to get an absolute file path in Python <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p> <pre><code>"C:/example/cwd/mydir/myfile.txt" </code></pre>
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("mydir/myfile.txt") </code></pre>
How do you treat legacy code (and data)? <p>I am currently in the process of restructuring my local Subversion repository by adding some new projects and merging legacy code and data from a couple of older repositories into it. </p> <p>When I have done this in the past I have usually put the legacy code in a dedicated "legacy" folder, as not to "disturb" the new and "well-structured" code tree. However, in the spirit of refactoring I feel this is somewhat wrong. In theory, the legacy code will be refactored over time and moved to its new location, but in practice this rarely happens.</p> <p>How do you treat your legacy code? As much as I feel tempted to tuck away old sins in the "legacy" folder, never to look at it again, on some level I hope that by forcing it to live among the more "healthy" inhabitants in the repository, maybe the legacy code will have a better chance of getting well some day?</p> <p>(Yeah, we all know <a href="http://www.joelonsoftware.com/articles/fog0000000069.html" rel="nofollow">we shouldn't rewrite stuff</a>, but this is my "fun" repository, not my business projects...)</p> <p><strong>Update</strong></p> <p>I am not worried about the technical aspects of keeping track of various versions. I know how to use tags and branches for that. This is more of a psychological aspect, as I prefer to have a "neat" structure in the repository, which makes navigating it much easier&mdash;for humans.</p>
<p>All code becomes 'legacy' one day, why seperate it at all? Source control is by project/branch or project/platform/branch and that type of hierarchy. Who cares how long in the tooth it is?</p>
Determine how much memory a class uses? <p>I am trying to find a way to determine at run-time how much memory a given class is using in .NET. Using Marshal.SizeOf() is out, as it only works on value types. Is there a way to check exactly how much memory a class uses?</p>
<p>I've only recently started looking into this type of thing, but i have found that memory profilers can give quite detailed information regarding instances of objects within your application.</p> <p>Here are a couple that are worth trying:</p> <ul> <li><a href="http://www.red-gate.com/Products/ants_profiler/index.htm" rel="nofollow">ANTS Profiler</a></li> <li><a href="http://memprofiler.com/" rel="nofollow">.NET Memory Profiler</a></li> </ul>
Metamodelling tools <p>What tools are available for metamodelling? </p> <p>Especially for developing diagram editors, at the moment trying out <a href="http://www.eclipse.org/modeling/gmf/" rel="nofollow">Eclipse GMF</a></p> <p>Wondering what other options are out there? Any comparison available?</p>
<p>Your question is simply too broad for a single answer - due to many aspects.</p> <p>First, meta-modelling is not a set term, but rather a very fuzzy thing, including modelling models of models and reaching out to terms like MDA.</p> <p>Second, there are numerous options to developing diagram editors - going the Eclipse way is surely a nice option.</p> <p>To get you at least started in the Eclipse department:</p> <ul> <li>have a look at MOF, that is architecture for "meta-modelling" from the OMG (the guys, that maintain UML)</li> <li>from there approach EMOF, a sub set which is supported by the Eclipse Modelling Framework in the incarnation of Ecore.</li> <li>building something on top of GMF might be indeed a good idea, because that's the way existing diagram editors for the Eclipse platform take (e.g. Omondo's EclipseUML)</li> <li>there are a lot of tools existing in the Eclipse environment, that can utilize Ecore - I simply hope, that GMF builts on top of Ecore itself.</li> </ul>
Graph (Chart) Algorithm <p>Does anyone have a decent algorithm for calculating axis minima and maxima? </p> <p>When creating a chart for a given set of data items, I'd like to be able to give the algorithm: </p> <ul> <li>the maximum (y) value in the set </li> <li>the minimum (y) value in the set </li> <li>the number of tick marks to appear on the axis </li> <li>an optional value that <strong>must</strong> appear as a tick (e.g. zero when showing +ve and -ve values)</li> </ul> <p>The algorithm should return</p> <ul> <li>the largest axis value </li> <li>the smallest axis value (although that could be inferred from the largest, the interval size and the number of ticks)</li> <li>the interval size </li> </ul> <p>The ticks should be at a regular interval should be of a "reasonable" size (e.g. 1, 3, 5, possibly even 2.5, but not any more sig figs). </p> <p>The presence of the optional value will skew this, but without that value the largest item should appear between the top two tick marks, the lowest value between the bottom two. </p> <p>This is a language-agnostic question, but if there's a C#/.NET library around, that would be smashing ;) </p>
<p>OK, here's what I came up with for one of our applications. Note that it doesn't deal with the "optional value" scenario you mention, since our optional value is always 0, but it shouldn't be hard for you to modify.</p> <p>Data is continually added to the series so we just keep the range of y values up to date by inspecting each data point as its added; this is very inexpensive and easy to keep track of. Equal minimum and maximum values are special cased: a spacing of 0 indicates that no markers should be drawn.</p> <p>This solution isn't dissimilar to Andrew's suggestion above, except that it deals, in a slightly kludgy way with some arbitrary fractions of the exponent multiplier.</p> <p>Lastly, this sample is in C#. Hope it helps.</p> <pre><code> private float GetYMarkerSpacing() { YValueRange range = m_ScrollableCanvas. TimelineCanvas.DataModel.CurrentYRange; if ( range.RealMinimum == range.RealMaximum ) { return 0; } float absolute = Math.Max( Math.Abs( range.RealMinimum ), Math.Abs( range.RealMaximum ) ), spacing = 0; for ( int power = 0; power &lt; 39; ++power ) { float temp = ( float ) Math.Pow( 10, power ); if ( temp &lt;= absolute ) { spacing = temp; } else if ( temp / 2 &lt;= absolute ) { spacing = temp / 2; break; } else if ( temp / 2.5 &lt;= absolute ) { spacing = temp / 2.5F; break; } else if ( temp / 4 &lt;= absolute ) { spacing = temp / 4; break; } else if ( temp / 5 &lt;= absolute ) { spacing = temp / 5; break; } else { break; } } return spacing; } </code></pre>
Vista BEX error <p>Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error:</p> <pre><code>Problem signature: Problem Event Name: BEX Application Name: iexplore.exe Application Version: 7.0.6001.18000 Application Timestamp: 47918f11 Fault Module Name: ntdll.dll Fault Module Version: 6.0.6001.18000 Fault Module Timestamp: 4791a7a6 Exception Offset: 00087ba6 Exception Code: c000000d Exception Data: 00000000 OS Version: 6.0.6001.2.1.0.768.3 Locale ID: 1037 Additional Information 1: fd00 Additional Information 2: ea6f5fe8924aaa756324d57f87834160 Additional Information 3: fd00 Additional Information 4: ea6f5fe8924aaa756324d57f87834160 </code></pre> <p>Googling revealed this sort of problems <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1194672&amp;SiteID=1">is</a> <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=eu&amp;comments_parentId=101420&amp;forumId=1">common</a> <a href="http://www.eggheadcafe.com/software/aspnet/29930817/bex-problem.aspx">for</a> <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.vc.mfc&amp;tid=d511c635-3c99-431d-8118-526d3e3fff00&amp;cat=&amp;lang=&amp;cr=&amp;sloc=&amp;p=1">Vista</a> and relates to <a href="http://www.gomanuals.com/java_not_working_on_windows_vista.shtml">Java</a> (although SUN <a href="http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html">negates</a>). Also I think it has something to do with DEP. I failed to find official Microsoft Kb.</p> <p>So, the questions are:</p> <ul> <li>What BEX stands for?</li> <li>What is it about?</li> <li>How to deal with such kind of errors?</li> </ul>
<p>BEX=Buffer overflow exception. See <a href="http://technet.microsoft.com/en-us/library/cc738483.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/cc738483.aspx</a> for details. However, c000000d is STATUS_INVALID_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP)</p>
Property default values using Properties.Settings.Default <p>I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:</p> <pre><code>ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; </code></pre> <p>But it seems to return a string instead of ValuationInput and it throws an exception. </p> <p>I made a quick hack, which works fine:</p> <pre><code>string valuationInputStr = (string) Settings.Default.Properties["ValuationInput"].DefaultValue; XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput)); ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr)); </code></pre> <p>But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: ValuationInput valuationInput = Settings.Default.ValuationInput;</p>
<p>At some point, something, somewhere is going to have to use Xml Deserialization, whether it is you or a wrapper inside the settings class. You could always abstract it away in a method to remove the "ugly" code from your business logic.</p> <pre><code>public static T FromXml&lt;T&gt;(string xml) { XmlSerializer xmlser = new XmlSerializer(typeof(T)); using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { return (T)xmlser.Deserialize(sr); } } </code></pre> <p><a href="http://www.vonsharp.net/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx" rel="nofollow">http://www.vonsharp.net/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx</a></p>
How to force my ASP.net 2.0 app to recompile <p>I have a ASP.net 2.0 app and I have made some changes the the source file ( cs files ). I uploaded the changes with the belief that it would auto-recompile. I also have the compiled dll in MY_APP/bin. I checked it and noticed that it did not recompile. Please understand I am new to this.</p>
<p>my #1 way to do this, add white space to the top of the web config file, after the xml declaration tag.</p> <p>It forces the node to re-cache and recompile. We even have a page deep in the admin called Flush.aspx that does it for us.</p>
How do I allow assembly (unit testing one) to access internal properties of another assembly? <p>I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.80).aspx">InternalsVisibleTo</a> attribute to the rescue!</p> <p>Just add: </p> <pre><code>[assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")] </code></pre> <p>to your Core classes AssemblyInfo.cs file</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/0tke9fxk(VS.80).aspx">Friend Assemblies (C# Programming Guide)</a> for best practices.</p>
How do I build a loop in JavaScript? <p>How can I build a loop in JavaScript?</p>
<p><strong>For loops</strong></p> <pre><code>for (i = startValue; i &lt;= endValue; i++) { // Before the loop: i is set to startValue // After each iteration of the loop: i++ is executed // The loop continues as long as i &lt;= endValue is true } </code></pre> <p><strong>For...in loops</strong></p> <pre><code>for (i in things) { // If things is an array, i will usually contain the array keys *not advised* // If things is an object, i will contain the member names // Either way, access values using: things[i] } </code></pre> <p>It is bad practice to use <code>for...in</code> loops to itterate over arrays. It goes against the <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow">ECMA 262</a> standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by <a href="http://www.prototypejs.org/api/array" rel="nofollow">Prototype</a>. <em>(Thanks to <a href="http://stackoverflow.com/users/7679/chase-seibert">Chase Seibert</a> for pointing this out in the comments)</em></p> <p><strong>While loops</strong></p> <pre><code>while (myCondition) { // The loop will continue until myCondition is false } </code></pre>
What are the (technical) pros and cons of Flash vs AJAX/JS? <p>We provide a web application with a frontend completely developed in Adobe Flash. When we chose Flash 6 years ago, we did so for its large number of features for user interaction, like dragging stuff, opening and closing menus, tree navigation elements, popup dialogs etc.</p> <p>Today it's obvious that AJAX/JS offers roughly the same possibilities and because of the number of frameworks that are readily available, it's very feasible to implement them.</p> <p>Is there a technical reason one should choose either technology over the other? By "technical", I mean performance, security, portability/compatibility and the like. I don't mean aspects such as the very non-programmer way development is done in Flash or whether it makes sense to switch an app from one to the other.</p> <p>As I just explained <a href="http://stackoverflow.com/questions/52094/which-ria-technology-has-the-biggest-market-share" rel="nofollow">in another question</a>, it seems to me that JS is way ahead in terms of market share and I'm wondering whether we are missing some important point if we stick to Flash.</p>
<p>In addition to what others have said, Flash is constrained in the "rectangle" and cannot be added to a normal html page in an un-obtrusive manner.</p> <p>@Gulzar I think when more browsers will support the video tag like mozilla 3.1 does we'll see even more adoption of ajax/js over flash.</p>
VB6 Runtime Type Retrival <p>How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?</p> <p>i.e. something like:</p> <pre><code>If Typeof(foobar) = "CommandButton" Then ... </code></pre> <p><strong>/EDIT:</strong> to clarify, I need to check on Dynamically Typed objects. An example:</p> <pre><code>Dim y As Object Set y = CreateObject("SomeType") Debug.Print( &lt;The type name of&gt; y) </code></pre> <p>Where the output would be "CommandButton"</p>
<p>I think what you are looking for is TypeName rather than TypeOf.</p> <pre><code>If TypeName(foobar) = "CommandButton" Then DoSomething End If </code></pre> <p>Edit: What do you mean Dynamic Objects? Do you mean objects created with CreateObject(""), cause that should still work.</p> <p>Edit: </p> <pre><code>Private Sub Command1_Click() Dim oObject As Object Set oObject = CreateObject("Scripting.FileSystemObject") Debug.Print "Object Type: " &amp; TypeName(oObject) End Sub </code></pre> <p>Outputs</p> <p><code>Object Type: FileSystemObject</code></p>
Templates of Technical and Functional Specs <p>So basically I am looking for good templates for writing both technical and functional specs on a project or work request.</p> <p>What do you use? How deep do you get while writing the specs? Any additional general tips you could provide would be appreciated.</p> <p>My company needs these badly. I work for a contractor and right now we do not use these documents at all. </p> <p><strong>EDIT:</strong> I have read Joel's take about <a href="http://www.joelonsoftware.com/articles/fog0000000036.html">Painless Specification</a>, I really liked it, but are there any other opinions :) </p>
<p>On general tips;</p> <p>We are implementing a process of </p> <p>1) Business Requirements Statement (BRS)</p> <p>2) Functional Specification</p> <p>3) Technical specification</p> <p>The BRS covers what the business problems are, and what the requirements are around solutions, testing, security, reliability and delivery. This defines what would make a successful solution.</p> <p>The functional spec details what is needed, how it should look, how long fields should be, etc.</p> <p>The technical spec details where the data comes from, any tricky code that may need to be considered.</p> <p>The customer owns the requirements. The developers own the tech specs, and the functional spec is a middle ground. Testing is done against the tech specs (usually unit testing) then against the functional specs (usually system testing) and then against the requirements (UAT).</p> <p>The important part of this (and we are struggling with) is that the developers still need to deliver to the functional spec, and the original business requirements. In reality the functional and tech specs are just there for clarity.</p> <p>In short, my main tip is to first work out the process you wish to implement. Then seek agreement from all parties involved in your proposed process, then work on the templates to fit. The templates themselves are only are a small part of the change you want to make.</p>
How can you determine what version(s) of .NET are running on a system? <p>What are the different ways (programmatically and otherwise) to determine what versions of .NET are running on a system?</p>
<p>Directly from the source:</p> <p><em><a href="http://support.microsoft.com/kb/318785" rel="nofollow">How to determine which versions and service pack levels of the Microsoft .NET Framework are installed</a></em></p>
Patterns for the overlap of two objects <p>I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q &amp; A's to be useful.</p> <p>I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. </p> <p>Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. </p>
<p>Table driven designs can be effective. Steve Maguire had few nice examples in <em>Writing</em> <em>Solid</em> <em>Code</em> .</p> <p>They are also a great way to capture tests, see <a href="http://fit.c2.com/" rel="nofollow">fit</a> .</p> <p>In your case something like:</p> <pre><code>Field1ReadonlyRules = { 'user class 1' : True, 'user class 2' : False } field1.readOnly = Field1ReadonlyRules[ someUser.userClass ] </code></pre> <p>As an aside you probably want to model <em>both</em> users and user classes/roles/groups instead of combining them. A user typically captures <em>who</em> (authentication) while groups/roles capture <em>what</em> (permissions, capabilities)</p>