input
stringlengths
51
42.3k
output
stringlengths
18
55k
How do I get the mac address or IPAddress from a cisco callmanager? <p>Is there any way to retrieve either the mac address or the IP address of phones on a Cisco server using Callmanager version 6 via the axl with VB.net?</p> <p>The server can retrieve the IP address itself to use the phone and it's not in the database information retrieved from the server.</p>
<p>You can download the WSDL file from your CallManager server. Then with the included methods, you can make a call to getPhone and it's pretty simple from there. If you want to do it in a more manual way, you can use the method from this blog post:</p> <p><a href="http://blog.crowe.co.nz/Archive/2008/October" rel="nofollow">http://blog.crowe.co.nz/Archive/2008/October</a></p> <p>(See the section "Getting the IP Addresses of Phones from a Cisco Call Manager v6.x using C#")</p>
MySQL Training videos <p>Hi were can I find training videos for MySQL ? </p>
<p>In youtube you find somethings like mysql install: <a href="http://www.youtube.com/watch?v=KQcFP3GcQ0s" rel="nofollow">http://www.youtube.com/watch?v=KQcFP3GcQ0s</a></p> <p>mysql trainning: <a href="http://www.youtube.com/watch?v=BHq-bORKncA" rel="nofollow">http://www.youtube.com/watch?v=BHq-bORKncA</a></p> <p>Google presentation about mysql tunning (hot) <a href="http://www.youtube.com/watch?v=u70mkgDnDdU" rel="nofollow">http://www.youtube.com/watch?v=u70mkgDnDdU</a></p> <p>You have anothers google presentations about mysql, just search in youtube and googlevideos :-)</p>
How do I retrieve the selected rows of a woodstock table <p>I have a JSF woodstock table with checkboxes. When a row is selected I want to do some processing with those items. I managed to get a selection of RowKey objects but can't find out how to get the original objects I put in back. The table is populated by an ObjectListDataProvider.</p>
<p>Always nice to be able to answer you own questions. I managed to solve it by casting the table's data provider to ObjectListDataProvider and use the method 'getObject' to get my original object back.</p>
Help needed for extending Asp.Net <p>As most of you would know, if I drop a file named app_offline.htm in the root of an asp.net application, it takes the application offline <a href="http://asp-net-whidbey.blogspot.com/2006/04/aspnet-20-features-appofflinehtm.html" rel="nofollow">as detailed here</a>.</p> <p>You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319986" rel="nofollow">as mentioned here</a>.</p> <p>Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.</p> <p>HELP!</p>
<p>The handling of app_offline.htm is hardcoded in the ASP.NET pipeline, and can't be modified: see <code>CheckApplicationEnabled()</code> in <code>HttpRuntime.cs</code>, where it throws a very non-configurable 404 error if the application is deemed to be offline.</p> <p>However, <a href="http://support.microsoft.com/kb/307996" rel="nofollow">creating your own HTTP module</a> to do something similar is of course trivial -- the OnBeginRequest handler could look as follows in this case (implementation for a HttpHandler shown, but in a HttpModule the idea is exactly the same):</p> <pre><code>Public Sub ProcessRequest(ByVal ctx As System.Web.HttpContext) Implements IHttpHandler.ProcessRequest If IO.File.Exists(ctx.Server.MapPath("/app_unavailable.htm")) Then ctx.Response.Status = "503 Unavailable (in Maintenance Mode)" ctx.Response.Write(String.Format("&lt;html&gt;&lt;h1&gt;{0}&lt;/h1&gt;&lt;/html&gt;", ctx.Response.Status)) ctx.Response.End() End If End Sub </code></pre> <p>This is just a starting point, of course: by making the returned HTML a bit friendlier, you can display a nice "we'll be right back" page to your users as well.</p>
AMD 64 bit Dual Core Optimization <p>We have a graphics intensive application that seems to be experiencing problems on AMD 64 bit Dual Core platforms that are not apparent on Intel platforms.</p> <p>Running the application causes the CPU to run at 100%, in particular when using code for shadows and lighting (Open GL).</p> <p>Does anyone know of specific issues with AMD processors that could cause this or know where to track down the problem, and/or ways to optimize the code base to avoid these issues?</p> <p><em>note, the application generally works well on mid range hardware, my dev machine has an nvidia gtx260 card in, so lack of power should not be an issue</em></p>
<p>Note that AMD64 is a <a href="http://en.wikipedia.org/wiki/Non-Uniform_Memory_Access" rel="nofollow">NUMA</a> architecture - if you are using a multi-processor box you may be running lots of memory accesses across the hypertransport bus which will be slower than the local memory and may explain the behaviour.</p> <p>This will not be the case between cores on a single socket so feel free to ignore this if you are not using a multiple-socket machine.</p> <p>Linux is NUMA aware (i.e. it has system services to allocate memory by local bank and bind processes to specific CPU's). I believe that Win 2k3 server, 2k8 and Vista are NUMA aware but XP is not. Most of the proprietary unix variants such as Solaris have NUMA support as well.</p>
spring & web service client - Fault Detail <p>How could I get the Fault Detail sent by a SoapFaultClientException ? I use a WebServiceTemplate as shown below :</p> <pre><code>WebServiceTemplate ws = new WebServiceTemplate(); ws.setMarshaller(client.getMarshaller()); ws.setUnmarshaller(client.getUnMarshaller()); try { MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req); } catch (SoapFaultClientException e) { SoapFault fault = e.getSoapFault(); SoapFaultDetail details = e.getSoapFault().getFaultDetail(); //details always NULL ? Bug? } </code></pre> <p>The Web Service Fault sent seems correct :</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;soapenv:Fault&gt; &lt;faultcode&gt;soapenv:Client&lt;/faultcode&gt; &lt;faultstring&gt;Validation error&lt;/faultstring&gt; &lt;faultactor/&gt; &lt;detail&gt; &lt;ws:ValidationError xmlns:ws="http://ws.x.y.com"&gt;ERR_UNKNOWN&lt;/ws:ValidationError&gt; &lt;/detail&gt; &lt;/soapenv:Fault&gt; &lt;/soapenv:Body&gt; </code></pre> <p></p> <p>Thanks</p> <p>Willome</p>
<p>I also had the problem that getFaultDetail() returned null (for a SharePoint web service). I could get the detail element out by using a method similar to this:</p> <pre><code>private Element getDetail(SoapFaultClientException e) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMResult result = new DOMResult(); transformer.transform(e.getSoapFault().getSource(), result); NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail"); return (Element)nl.item(0); } </code></pre> <p>After that, you can call getTextContent() on the returned Element or whatever you want.</p>
What is an ideal variable naming convention for loop variables? <p>If you are writing a <em>simple</em> little loop, what <em>should</em> you name the counter?</p> <p><em>Provide example loops!</em></p>
<p>1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, either you should consider refactoring the code.</p> <p>Java Example:</p> <pre class="lang-java prettyprint-override"><code>for(int i = 0; i &lt; ElementsList.size(); i++) { Element element = ElementsList.get(i); someProcessing(element); .... } </code></pre> <p>2) For the new style java loops like <code>for(Element element: ElementsList)</code> it is better to use normal meanigful name</p> <p>Java Example:</p> <pre class="lang-java prettyprint-override"><code>for(Element element: ElementsList) { someProcessing(element); .... } </code></pre> <p>3) If it is possible with the language you use, convert the loop to use iterator</p> <p>Java Iterator Example: <a href="http://www.javadeveloper.co.in/java-example/java-iterator-example.html">click here</a></p>
CSV API for Java <p>Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it.</p> <p>A quick google has found <a href="http://flatpack.sourceforge.net/">http://flatpack.sourceforge.net/</a> which looks promising.</p> <p>I just wanted to check what others are using before I couple myself to this API.</p>
<p>I've used <a href="http://opencsv.sourceforge.net/">OpenCSV</a> in the past. </p> <pre><code>import au.com.bytecode.opencsv.CSVReader;</code></pre> <p><pre>String fileName = "data.csv"; CSVReader reader = new CSVReader(new FileReader(fileName ));</p> <p>// if the first line is the header String[] header = reader.readNext();<br /> // iterate over reader.readNext until it returns null String[] line = reader.readNext(); </pre></p> <p>There were some other choices in the answers to <a href="http://stackoverflow.com/questions/123/csv-file-to-xml#53547">another question</a>. </p>
What would you use to write end user documentation for a WPF application <p>We're working on a WPF-based application and we would like to have user documentation included in the application.</p> <p>Our requirements:</p> <ul> <li>Must support multiple output formats (CHM,HTML,PDF)</li> <li>Be able to load the text into a WPF application</li> <li>Be familiar for a windows user</li> <li>Preferrable possible to give us context sensitive help within the application</li> <li>Nice predefined template so we only need to adjust to our colours</li> </ul> <p>I've been considering basing this on <a href="http://en.wikipedia.org/wiki/Microsoft_Assistance_Markup_Language" rel="nofollow">MAML</a> which is Vista's documentation format, but I am a bit unsure about the tooling support and the <a href="http://en.wikipedia.org/wiki/Online_help" rel="nofollow">lack of commitment for a public API</a> by Microsoft. Does anyone have any experience with MAML?</p>
<p>We're using <a href="http://www.codeplex.com/Sandcastle" rel="nofollow">SandCastle</a> with <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=SHFB" rel="nofollow">Sandcastle Help File Builder</a> as a configuration tool. It can create CHM, help2 &amp; website (asp or html). It is very easy to use and free - the only downside is that additional context need to be created using MAML - an XML flavor MS uses.</p>
Which is the best .Net XML-RPC library? <p>I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries?</p> <p>EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so:</p> <pre><code>object1.object2.someMethod(string1) </code></pre> <p>This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy.</p> <p>So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode):</p> <pre><code>x = new xmlrpc(host, port) x.makeCall("methodName", "arg1"); </code></pre> <p>I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire.</p> <p>Unless someone has a better idea looks like I am going to have to start an open source project myself!</p>
<p>If the method name is all that is changing (i.e., the method signature is static) XML-RPC.NET can handle this for you. This is addressed <a href="http://xml-rpc.net/faq/xmlrpcnetfaq.html#2.23" rel="nofollow">in the FAQ</a>, noting "However, there are some XML-RPC APIs which require the method name to be generated dynamically at runtime..." From the FAQ:</p> <pre><code>ISumAndDiff proxy = (ISumAndDiff)XmlRpcProxyGen.Create(typeof(ISumAndDiff)); proxy.XmlRpcMethod = "Id1234_SumAndDifference" proxy.SumAndDifference(3, 4); </code></pre> <p>This generates an XmlRpcProxy which implementes the specified interface. Setting the XmlRpcMethod attribute causes methodCalls to use the new method name.</p>
Vim errorformat for Visual Studio <p>I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild.</p> <p>I've created a batch file called build.bat which executes the devenv build like this:</p> <pre><code>devenv MySln.sln /Build Debug </code></pre> <p>In vim I've pointed the :make command to that batch file:</p> <pre><code>:set makeprg=build.bat </code></pre> <p>When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors.</p> <p>I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried:</p> <pre><code>set errorformat=%*\\d&gt;%f(%l)\ :\ %t%[A-z]%#\ %m set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m set errorformat=%f(%l,%c):\ error\ %n:\ %f </code></pre> <p>And of course I've tried Vim's default.</p> <p>Here's some example output from the build.bat:</p> <pre><code>C:\TFS\KwB Projects\Thingy&gt;devenv Thingy.sln /Build Debug Microsoft (R) Visual Studio Version 9.0.30729.1. Copyright (C) Microsoft Corp. All rights reserved. ------ Build started: Project: Thingy, Configuration: Debug Any CPU ------ c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs" C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) Compile complete -- 1 errors, 0 warnings ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ========== </code></pre> <p><strong>UPDATE:</strong> It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment).</p> <p>Using msbuild the makeprg would be:</p> <pre><code>:set makeprg=msbuild\ /nologo\ /v:q </code></pre> <p>Sample output whould be:</p> <pre><code>Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) </code></pre> <p>It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file.</p> <p><strong>ANSWER:</strong> I figured it out...</p> <pre><code>set errorformat=\ %#%f(%l\\\,%c):\ %m </code></pre> <p>This will capture the output for both devenv /Build and msbuild. However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup:</p> <pre><code>&lt;GenerateFullPaths&gt;True&lt;/GenerateFullPaths&gt; </code></pre>
<p>I have a blog post which walks through all the details of getting C# projects building in Vim, including the error format. You can find it here: <a href="http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html">http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html</a></p> <p>In short you need the following:</p> <pre><code>:set errorformat=\ %#%f(%l\\\,%c):\ %m :set makeprg=msbuild\ /nologo\ /v:q\ /property:GenerateFullPaths=true </code></pre>
How many bits are there in a nibble? <p>binary question :)</p>
<p>The answer is 4 bits. 2 nibbles make a byte.</p> <p><a href="http://www.geneziegler.com/clocktower/DrSeuss.html" rel="nofollow">See here</a> for a cute poem.</p>
Is there a way to prevent google search terms from matching urls? <p>At the moment, I am doing a number of searches which include "html" in them, for example "html rearrange". Unfortunately, I get a lot of hits from sites that include "rearrange" on a .html page but have no mention of html in the page itself.</p> <p>Is there a way to prevent search terms from matching urls?</p>
<p>try something like</p> <p>"html rearrange -inurl:html"</p> <p>the inurl means "match the following pattern in the URL", the - means to exclude those pages</p>
Restrict access to a single application when logging in from the console without replacing GINA <p>Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?</p> <p>The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).</p> <p>As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.</p> <p>Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)</p>
<p>SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon has two values UserInit points to the application that is executed upon successful logon. The default app there, userinit.exe processes domain logon scripts (if any) and then launches the specified Shell= application.</p> <p>By creating or replacing those entries in HKEY_CURRENT_USER or in a HKEY_USERS hive you can replace the shell for a specific user.</p> <p>Once you ahve your own shell in place, you have very little to worry about, unless the "kiosk user" has access to a keyboard and can press ctrl-alt-del. This seems to be hardcoded to launch taskmgr.exe - rather than replacing the exe, you can set the following registry key</p> <pre><code>[SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe] Debugger="A path to an exe file that will be run instead of taskmgr.exe" </code></pre>
Prototype get by tag function <p>How do I get an element or elementlist by it's tag name. Take for example that I want all elements from <code>&lt;h1&gt;&lt;/h1&gt;</code></p>
<p>document.getElementsByTagName('a') returns an array. Look here for more information: <a href="http://developer.mozilla.org/En/DOM/Element.getElementsByTagName" rel="nofollow">http://developer.mozilla.org/En/DOM/Element.getElementsByTagName</a></p>
PHP: GET-data automatically being declared as variables <p>Take this code:</p> <pre><code>&lt;?php if (isset($_POST['action']) &amp;&amp; !empty($_POST['action'])) { $action = $_POST['action']; } if ($action) { echo $action; } else { echo 'No variable'; } ?&gt; </code></pre> <p>And then access the file with ?action=test Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding</p> <pre><code>&amp;&amp; !isset($_GET['action']) </code></pre> <p>Why would I want the variable to be declared for me?</p>
<p>Check your php.ini for the <code>register_globals</code> setting. It is probably on, you want it off.</p> <blockquote> <p>Why would I want the variable to be declared for me?</p> </blockquote> <p><a href="http://us3.php.net/manual/en/security.globals.php" rel="nofollow">You don't.</a> It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global <a href="http://us3.php.net/manual/en/ini.core.php#ini.register-globals" rel="nofollow">(PHP manual)</a>. These are a handful of <a href="http://us.php.net/manual/en/reserved.variables.php" rel="nofollow">reserved variables</a> in PHP.</p>
Why do I get "java.net.BindException: Only one usage of each socket address" if netstat says something else? <ul> <li>I start up my application which uses a Jetty server, using port 9000.</li> <li>I then shut down my application with Ctrl-C</li> <li>I check with "netstat -a" and see that the port 9000 is no longer being used.</li> <li>I restart my application and get:</li> </ul> <blockquote> <pre><code>[ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75) [TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77) [TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73) [TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at ... </code></pre> </blockquote> <p>Is this a Java bug? Can I avoid it somehow before starting the Jetty server?</p> <p><strong>Edit #1</strong> Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)":</p> <blockquote> <pre><code> connector.setReuseAddress( true ); connector.setPort( port ); connector.setStatsOn( true ); connector.setMaxIdleTime( 30000 ); connector.setLowResourceMaxIdleTime( 30000 ); connector.setAcceptQueueSize( maxRequests ); connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() ); </code></pre> </blockquote> <p>Could it have something to do with the idle time?</p> <p><strong>Edit #2</strong> Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot?</p> <p><strong>Edit #3 (4 days later)</strong> - still have the issue. Any thoughts?</p>
<p>During your first invocation of your program, did it accept at least one incoming connection? If so then what you are most likely seeing is the socket linger in effect. </p> <p>For the best explanation dig up a copy of TCP/IP Illustrated by Stevens </p> <p><img src="http://www.kohala.com/start/gifs/tcpipiv1.gif" alt="alt text" /></p> <p>But, as I understand it, because the application did not properly close the connection (that is BOTH client and server sent their FIN/ACK sequences) the socket you were listening on cannot be reused until the connection is considered dead, the so called 2MSL timeout. The value of 1 MSL can vary by operating system, but its usually a least a minute, and usually more like 5. </p> <p>The best advice I have heard to avoid this condition (apart from always closing all sockets properly on exit) is to set the SO_LINGER tcp option to 0 on your server socket during the listen() phase. As freespace pointed out, in java this is the setReuseAddress(true) method.</p>
Why would VS2005 keep checking out a project for editing without any changes being made? <p>I have a VS2005 solution which contains a variety of projects (C++ DLLs, C++ static libraries, C# assemblies, C++ windows executables) that are combined in various ways to produce several executables. For some reason, every time I open the solution, VS2005 wants to check out one of the projects for editing. The project is not modified in any way, it's just checked out. If I configure VS2005 to prompt before checking out, I can cancel the auto-checkout during load with no ill effect that I can see. It may or may not be relevant, but the project it keeps checking out is cppunit version 1.12.0 (the static lib version). How can I stop this annoying behavior?</p> <p>Other potentially relevant (or not) details:</p> <ul> <li>Source control is Team Foundation Server (not Visual SourceSafe)</li> <li>no .suo or .ncb files are checked in</li> <li>the .vcproj and .vspscc files are being checked out</li> <li>When I close the solution or shut down Visual Studio, I'm asked whether I want to save changes to the project. Answering yes results in no changes to the file (Kdiff3 compares my local file to the server version and reports"files are binary equal")</li> <li>Attempting to check in the "modified" files results in a Visual Studio message saying "No Changes to Check In. All of the changes were either unmodified files or locks. The changes have been undone by the server"</li> </ul>
<p>As Charles and Graeme have hinted at, Visual Studio constantly make changes to user option files and such on the backed even if you don't make changes to the project directly.</p> <p>I'm not sure what information is being stored but I do know that it happens. Common remedies is to not include the *.suo files. I also don't stored anything in the bin or obj folders in sauce control as this can have a similar effect as your talking about (if you build). (Checks out the project upon a build. Thought this does take an action to happen). </p> <p>Overall it is unavoidable. It is just how VS2005, 2008 work.</p> <p>Does this answer your question?</p> <p>Regards, Frank</p>
Farseer Physics Tutorials, Help files <p>Is there a tutotial or help file, suitable for a beginner c# programmer to use.</p>
<p>The primary documentation for the Farseer Physics engine is on the homepage.</p> <p><a href="http://www.codeplex.com/FarseerPhysics/Wiki/View.aspx?title=Documentation&amp;referringTitle=Home">http://www.codeplex.com/FarseerPhysics/Wiki/View.aspx?title=Documentation&amp;referringTitle=Home</a></p> <p>You can also check out the source code, they have a demos folder in there, though it's only got one example, but it can show you how to implement the engine</p> <p><a href="http://www.codeplex.com/FarseerPhysics/SourceControl/DirectoryView.aspx?SourcePath=%24%2fFarseerPhysics%2fDemos%2fXNA3%2fGettingStarted&amp;changeSetId=40048">http://www.codeplex.com/FarseerPhysics/SourceControl/DirectoryView.aspx?SourcePath=%24%2fFarseerPhysics%2fDemos%2fXNA3%2fGettingStarted&amp;changeSetId=40048</a></p> <p>For a last resort, check out their forums, and ask some questions. They seem nice enough that they should be able to help you out with any questions.</p> <p><a href="http://www.codeplex.com/FarseerPhysics/Thread/List.aspx">http://www.codeplex.com/FarseerPhysics/Thread/List.aspx</a></p>
Synchronize SourceSafe with SVN <p>Our company has a policy imposing the requirement of keeping source code in a SourceSafe repository. I've tried hard to persuade the management to migrate to SVN with no success (whcih is an another issue, anyway). </p> <p>As I and few of my colleagues use SVN repository placed on my computer (via Apache), I made a PowerShell script which does backups of the repository onto a company server (which is then periodically backed up as well). This works well, but say I wanted also to keep a copy of the source code on our SourceSafe server.</p> <p>Any experience or tips on doing that?</p> <p>Thanks</p>
<p>How about checking in the <strong><em>SVN Repository</em></strong> to SourceSafe?</p>
What's the best way to create a drop-down list in a Windows application using Visual Basic? <p>I'd like to add a drop-down list to a Windows application. It will have two choices, neither of which are editable. What's the best control to use? Is it a combo box with the editing property set to No?</p> <p>I'm using Visual Studio 2008.</p>
<p>I'd suggest taking a look at the <a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" rel="nofollow">Windows Vista User Experience Guide</a>. It sounds like you might be better off with radio buttons, or, if it's an explicit on/off type of situation, using a check box. I think we'd really need more info, though.</p>
What would you say, is the best online-source for PHP-related things? <p>What would you say is the best online-source for interesting things about <code>PHP</code> and stuff around it? I am thinking along the lines of a blog or online-magazine, which tells me about tricks, news and best practices.</p> <p>Please add a short comment about the site you recomment! :)</p> <p>Best regards, B</p>
<p>I find php.net to be a great resource for pretty much everything PHP related. Great reference, great community, and lots of code.</p>
Linq to SQL Association combo box order <p>This is kind of a weird question and more of an annoyance than technical brick wall.</p> <p>When I'm adding tables and such using the Linq-to-SQL designer and I want to create an association using the dialogs. I right click on one of the target tables and choose <em>Add</em> > <em>Association</em> as normal and I am presented with the <strong>Association Editor</strong>.</p> <p>The <em>Parent Class:</em> and <em>Child Class:</em> combo boxes are filled with the tables that currently exist in the designer.</p> <p>But they are not in alphabetical order they are in the order that they were added to the designer.</p> <p>Can I change the order of these combo boxes? And if I can, where do I do this?</p>
<p>I went poking around some and found an answer.</p> <p>The <strong>dbml</strong> file is an XML file that hold all of the basic information about the SQL tables, connections, etc. needed for Linq-to-SQL. By reordering the Table elements, you affect the order of the combo boxes used in the Association editor.</p>
Learning Anaysis Services <p>Can anyone recommend a good resource -- book, website, article, etc -- to help me learn SQL Server Analysis services.</p> <p>I have no knowledge of this technology right now but I do constantly work with SQL server in the traditional sense. </p> <p>I want to learn about Cubes and Using Reporting Services with it. I want to start from the bottom but after I finish with the material, ideally, I'd be able to stumble through a real development project...</p> <p>I'm hoping to get started with a free resource but if anyone knows of a <strong>really good</strong> book, I'd take that too.</p> <p>Or, if you don't know of a resource how did you get started with the technology?</p> <p>Thank you,<br> Frank</p>
<p>Take a look <a href="http://stackoverflow.com/questions/101242/nice-book-on-sql-server-analysis-services">Here</a> for a list of AS resources I compiled in answer to a similar question.</p>
CSS Margin Collapsing <p>So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?</p>
<p>No. When you have two adjacent vertical margins, the greater of the two is used and the other is ignored.</p> <p>So, for instance, if you have two block-display elements, A, followed by B beneath it, and A has a bottom-margin of 3em, while B has a top-margin of 2em, then the distance between them will be 3em.</p> <p>If you set a border or padding, this prevents the collapsing from occurring. In the above example, the distance between the two elements will then be 5em.</p> <p>If you don't set any margins, then there won't be any margins to collapse. It has nothing whatsoever to do with the element type in use - it is applicable to all element types, not just <code>&lt;div&gt;</code> elements.</p> <p>Read <a href="http://www.w3.org/TR/CSS21/box.html#collapsing-margins">the CSS 2.1 specification</a> for more details.</p>
How does c# figure out the hash code for an object? <p>This question comes out of the discussion on <a href="http://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c">tuples</a>.</p> <p>I started thinking about the hash code that a tuple should have. What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.</p> <p>Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.</p> <p>But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!</p> <p>How does it work? What's the analysis made by Object.GetHashCode()? </p> <p>Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)</p> <p>Consider this code as an example:</p> <pre><code>namespace csharp_tricks { class Program { class MyClass { int keyValue; int someInfo; public MyClass(int key, int info) { keyValue = key; someInfo = info; } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return keyValue.Equals(other.keyValue); } public override int GetHashCode() { return keyValue.GetHashCode(); } } static void Main(string[] args) { Dictionary&lt;object, object&gt; dict = new Dictionary&lt;object, object&gt;(); dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 1), 1), 1); //here we get the exception -- an item with the same key was already added //but how did it figure out the hash code? dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 2), 1), 1); return; } } } </code></pre> <p><strong>Update</strong> I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:</p> <ul> <li>Be careful with your keys and their hash codes :-)</li> <li>For complicated dictionary keys you must override Equals() and GetHashCode() correctly.</li> </ul>
<p>Don't override GetHashcode() and Equals() on mutable classes, only override it on immutable classes or structures, else if you modify a object used as key the hash table won't function properly anymore (you won't be able to retrieve the value associated to the key after the key object was modified)</p> <p>Also hash tables don't use hashcodes to identify objects they use the key objects themselfes as identifiers, it's not required that all keys that are used to add entries in a hash table return different hashcodes, but it is recommended that they do, else performance suffers greatly. </p>
css organization and colours <p>I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.</p> <p>i.e.</p> <pre><code>.color1 { color: #3d444d; } </code></pre>
<p>One thing I've done here is break out my palette declarations from other style/layout markup, grouping commonly-colored items in lists, e.g.</p> <pre><code>h1 { padding... margin... font-family... } p { ... } code { ... } /* time passes */ /* these elements are semantically grouped by color in the design */ h1, p, code { color: #ff0000; } </code></pre> <p>On preview, JeeBee's suggestion is a logical extension of this: if it makes sense to handle your color declarations (and, of course, this can apply to other style issues, though color has the unique properties of not changing layout), you might consider pushing it out to a separate css file, yeah. This makes it easier to hot-swap color-only thematic variations, too, by just targeting one or another colorxxx.css profile as your include.</p>
How can I install CPAN modules locally without root access (DynaLoader.pm line 229 error)? <p>Doesn't work with other modules, but to give an example. I installed Text::CSV_XS with a CPAN setting:</p> <pre><code>'makepl_arg' =&gt; q[PREFIX=~/lib], </code></pre> <p>When I try running a test.pl script:</p> <blockquote> <p>$ perl test.pl</p> </blockquote> <pre><code>#!/usr/bin/perl use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi"; use Text::CSV_XS; print "test"; </code></pre> <p>I get</p> <pre> Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229. at test.pl line 6 Compilation failed in require at test.pl line 6. BEGIN failed--compilation aborted at test.pl line 6. </pre> <p>I traced the error back to DynaLoader.pm it happens at this line:</p> <pre><code># Many dynamic extension loading problems will appear to come from # this section of code: XYZ failed at line 123 of DynaLoader.pm. # Often these errors are actually occurring in the initialisation # C code of the extension XS file. Perl reports the error as being # in this perl code simply because this was the last perl code # it executed. my $libref = dl_load_file($file, $module-&gt;dl_load_flags) or croak("Can't load '$file' for module $module: ".dl_error()); </code></pre> <p><b>CSV_XS.so exists in the above directory</b></p>
<p>Personally I would suggest to use <a href="http://search.cpan.org/dist/local-lib/" rel="nofollow">local::lib</a>. :)</p>
Build new computer using Scripts <p>I would like to automate the process of setting up a new PC, this would include downloading and installing the latest windows and office updates; installing software from a network share (some software will require a restart so the script would need to be able to login and continue) adding PC to a domain and setting up local user accounts.</p> <p>Is this possible and what would be the best scripting language to achieve this?</p>
<p>Check out <a href="http://www.nliteos.com/" rel="nofollow">nLite</a>. Allows you to pre-configure many options, slipstream updates and service packs, etc.</p>
Generate a Sandcastle help file for a website without the "Xml Documentation File" option <p>I am trying to generate a Sandcastle help file for a website. In the properties window for project, there aren't any options for creating the XML Documentation File required for Sandcastle.</p> <p>The Build tab in the property pages only contains options for: Start Action, Build Solution Action, and Accessibility validation. I don't have any options for Output, or XML documentation file, like my other projects have.</p> <p>The website I'm working with does not have an actual .proj file, which could be the problem. If this is the problem, what is the best way of creating one for a project that is under source control and being worked on by many people with minimal disruption?</p> <p>This is using Visual Studio 2005 professional.</p>
<p>The problem with websites in VS2k5 is that, when they get compiled, the resulting dlls are a mess. No namespaces, weird names, etc. </p> <p>If you truly want to generate a Sandcastle Help File, look at converting your website into a web application. You can definitely generate source code docs for that.</p>
Is IIS7 migration a piece of cake <p>I wish to migrate a website to windows 2008 platform, is there any obvious pitfalls i should be aware of?</p> <p>code base is c# 3.5,asp.net with ms ajax.</p>
<p>I googled a bit and found this link:</p> <p><a href="http://weblogs.asp.net/steveschofield/archive/2008/09/04/iis6-to-iis7-migration-tips-tricks.aspx" rel="nofollow">http://weblogs.asp.net/steveschofield/archive/2008/09/04/iis6-to-iis7-migration-tips-tricks.aspx</a></p> <p>Biggest Issue i find is that 3rd party components needs to have 64bit version ready to get most of benefits.</p>
Should I store a database ID field in ViewState? <p>I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).</p> <p>I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?</p>
<p>It depends.</p> <p>Do you care if anyone sees the record id? If you do then both hidden fields and viewstate are not suitable; you need to store it in session state, or encrypt viewstate.</p> <p>Do you care if someone submits the form with a bogus id? If you do then you can't use a hidden field (and you need to look at CSRF protection as a bonus)</p> <p>Do you want it unchangable but don't care about it being open to viewing (with some work)? Use viewstate and set enableViewStateMac="true" on your page (or globally)</p> <p>Want it hidden and protected but can't use session state? Encrypt your viewstate by setting the following web.config entries</p> <pre><code>&lt;pages enableViewState="true" enableViewStateMac="true" /&gt; &lt;machineKey ... validation="3DES" /&gt; </code></pre>
What are some project management tips and processes for a single-developer team? <p>I usually have some project that I can do alone that take around 6 months to 1 year. I always try to have some "release" date and write few documentations (external to the code).</p> <p>My question is, what type of management do you use when you do not have a team with you but you are alone?</p> <p>Example, I was thinking about Agile Programming BUT not sure if you can really say that you are Agile when you are alone? What do you use?</p>
<p>Having been in a similar position for years, I base my approach to how I'm billing the project: project based or time/materials based.</p> <p><strong>If I do project based billing</strong>, then I tend to be a little more formal. Meaning that my contract lays out the main project features as well as possible limitations etc. I go over it in detail prior to signing, then that becomes my blueprint.</p> <p>I do allow for changes along the way, but I make those a little more formal as well with signed change request forms describing the change and the modified project costs. </p> <p>On a 6 month to 1 year deal, I may show progress about once every 3 to 4 weeks; or at milestone developments at which point I do incremental billing. This is probably closer to being a waterfall approach than anything else.</p> <p><strong>If I am billing for time and materials</strong> then I tend to be a lot more flexible and have a lot more communication with the client. I may be showing something new every day, or at the very least, once a week. I basically try to show the result of each task I finish. The type of clients that want to bill hourly tend to like this format. This tends to be closer to an agile approach.</p> <p>At the end of the day you just have to go with what works best in your situation. </p>
Finding First Row in a RDLC Table <p>I have a table in a RDLC report which is utilized as a subreport, and the first column of this table is a static string. Does anyone know how I can determine if a row is the first in the table. I tried using "=First("My String")" but it didn't work.</p>
<p>Looking at the link supplied by <a href="http://stackoverflow.com/questions/103240/finding-first-row-in-a-rdlc-table#103388">ThatBloke in his answer</a>, I found the RowNumber command. </p> <p>Which means that this worked:</p> <pre><code>=IIf(RowNumber(Nothing)=1,"myString", "") </code></pre>
Portable way to catch signals and report problem to the user <p>If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.</p> <p>Today our signal handler looks as follows:</p> <pre><code>void catchSignal (int reason) { std :: cerr &lt;&lt; "Caught a signal: " &lt;&lt; reason &lt;&lt; std::endl; exit (1); } </code></pre> <p>I can hear the screams of horror with the above, as I have read from this <a href="http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&amp;q=deadlock#" rel="nofollow">thread</a> that it is evil to call a non-reentrant function from a signal handler.</p> <p>Is there a portable way to handle the signal and provide information to users?</p> <p><strong>EDIT:</strong> Or at least portable within the POSIX framework?</p>
<p>This <a href="http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948">table</a> lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.</p> <p>By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick:</p> <pre><code>#include &lt;csignal&gt; #ifdef _WINDOWS_ #define _exit _Exit #else #include &lt;unistd.h&gt; #endif #define PRINT_SIGNAL(X) case X: \ write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \ break; void catchSignal (int reason) { char s[] = "Caught signal: ("; write (STDERR_FILENO, s, sizeof(s) - 1); switch (reason) { // These are the handlers that we catch PRINT_SIGNAL(SIGUSR1); PRINT_SIGNAL(SIGHUP); PRINT_SIGNAL(SIGINT); PRINT_SIGNAL(SIGQUIT); PRINT_SIGNAL(SIGABRT); PRINT_SIGNAL(SIGILL); PRINT_SIGNAL(SIGFPE); PRINT_SIGNAL(SIGBUS); PRINT_SIGNAL(SIGSEGV); PRINT_SIGNAL(SIGTERM); } _Exit (1); // 'exit' is not async-signal-safe } </code></pre> <p><strong>EDIT:</strong> Building on windows.</p> <p>After trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'.</p> <pre><code>#include &lt;io.h&gt; #define STDIO_FILENO 2 </code></pre> <p><strong>EDIT:</strong> 'exit' should not be called from the signal handler either!</p> <p>As pointed out by <a href="http://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413">fizzer</a>, calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig_atomic_t" type can be used to notify the main program that it should exit.</p> <p>The following I found useful in my searches.</p> <ol> <li><a href="http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html">Introduction To Unix Signals Programming</a> </li> <li><a href="http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html">Extending Traditional Signals</a></li> </ol>
What's the best way to determine the name of your machine in a .NET app? <p>I need to get the name of the machine my .NET app is running on. What is the best way to do this?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx" rel="nofollow"><code>System.Environment.MachineName</code></a></p>
iPhone programming - impressions, opinions? <p>I've been programming in C,C++,C# and a few other languages for many years, mainly for Windows and Linux but also embedded platforms. Recently started to do some iPhone programming as a side project so I'm using Apple platforms for the first time since my Apple II days. I'm wondering what other developers that are coming to Mac OSX, Xcode and iPhone SDK think. Here are my impressions, so far:</p> <ul> <li><p>Mac OSX: very confusing, I tend to end up with too many open windows and don't know what's where. Luckily there's the bird's eye view, without it I'd be lost. With the shell at least there's all the familiar stuff so that helps me a lot.</p></li> <li><p>Xcode: doesn't feel as good as VisualStudio or Eclipse, the two environments I'm familiar with. I think I could get used to it but I'm wondering if Apple wouldn't be better off with Eclipse. Before I found the setting where all the windows are stuck together I hated it, now I can tolerate it.</p></li> <li><p>iPhone SDK: strange indeed. I understand Apple's desire to control their environment but in this day and age it just seems a little sleazy and they are missing out on so much by destroying developer goodwill.</p></li> <li><p>Objective-C: I've known about it for years but never even took a look at it. The syntax is off-putting but I'm actually very intrigued by the language. I think it's an interesting third leg between C++ and C#, both of which I like a lot. Is there any chance Obj-C will break out of the Mac sandbox due to the uptick in the popularity of Apple technology?</p></li> </ul> <p>Curious to read your thoughts,</p> <p>Andrew</p>
<p>I'm in the same boat as you (somewhat). I've been developing in C# for 7 years, ever since .NET 1.0. Over the past couple weeks I've been teaching myself Cocoa and Objective-C. Here are my impressions (note for note with yours)</p> <ul> <li><p>Agreed in that clutter can be a problem. I tend to use Spaces heavily when developing in XCode (put XCode in one space, Interface Builder in another space, Instruments in a third space). If you don't have Leopard (and thus, no spaces), then use Command-H to hide your active window. Using that tends to clean things up quite a bit (however it'd be nice if you could command-h automagically the current window when command-tab'ing to another app).</p></li> <li><p>I'm liking XCode more and more. I hate Visual Studio - I find it to be unstable, slow, and well, just kind of a crappy IDE. Comparatively I've found XCode to be fast, stable, and I like how it organizes and filters your files. I'm not too up on my XCode shortcuts, but I'm hoping there's a way I can quick-switch from one class to another (similar to ctrl +n shortcut in ReSharper). Intellisense could be better with regards to how it displays to the user, but I really like how it essentially creates a template and you can ctrl + / to jump to the next argument in a message.</p></li> <li><p>I'm hating the documentation in XCode. The help system sucks, and for whatever reason it <em>never</em> finds what I'm searching for. I end up just googling for anything I need to know... I hope they improve the documentation. This is my biggest beef right now.</p></li> <li><p>Not quite there yet, as I'm going through the full Cocoa framework for Mac desktops. So far I'm really, really liking what I see. One thing I will say is that it would be nice if the iPhone SDK allowed for garbage collection...</p></li> <li><p>Objective-C - I've never used it, this is my first foray into it. At first I was kinda wierded out by the syntax and the square brackets for messaging, but it's really growing on me. It's so quick to skim a method and see the message calls that method makes. The more I use it, the more Objective-C just feels nice... however templating/generics would be a welcome addition to the language.</p></li> </ul> <p>All in all, my foray into Mac development has been enjoyable, and I'm excited to start working (today! yay!) on some actual mac/iphone projects.</p>
Invalid postback or callback argument <p>I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas?</p> <blockquote> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.</p> </blockquote> <p><strong>Edit:</strong> This seems to only be happening when viewed with IE6 but not with IE7, any ideas?</p>
<p>This can happen if you're posting what appears to be possibly malicious things; such as a textbox that has html in it, but is not encoded prior to postback. If you are allowing html or script to be submitted, you need to encode it so that the characters, such as &lt;, are passed as &amp; lt;.</p>
jQuery Menu and ASP.NET Sitemap <p>Is it possible to use an <a href="http://en.wikipedia.org/wiki/ASP.NET">ASP.NET</a> web.sitemap with a jQuery <a href="http://users.tpg.com.au/j_birch/plugins/superfish/">Superfish</a> menu? </p> <p>If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?</p>
<p>I found this question while looking for the same answer... everyone <em>says</em> it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings...</p> <p>Things I needed:</p> <ul> <li><p><a href="http://users.tpg.com.au/j%5Fbirch/plugins/superfish/#download">Superfish</a> which also includes a version of <a href="http://jquery.com/">jQuery</a></p></li> <li><p><a href="http://cssfriendly.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=2159">CSS Friendly Control Adaptors</a> download DLL and .browsers file (into /bin and /App_Browsers folders respectively)</p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx">ASP.NET SiteMap</a> (a .sitemap XML file and <code>siteMap</code> provider entry in web.config)</p></li> </ul> <p>My finished <code>Masterpage.master</code> has the following <code>head</code> tag:</p> <pre><code>&lt;head runat="server"&gt; &lt;script type="text/javascript" src="/script/jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/script/superfish.js"&gt;&lt;/script&gt; &lt;link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" /&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('ul.AspNet-Menu').superfish(); }); &lt;/script&gt; &lt;/head&gt; </code></pre> <p>Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on <a href="http://www.devx.com/asp/Article/31889">these instructions</a>):</p> <pre><code>&lt;asp:SiteMapDataSource ID="SiteMapDataSource" runat="server" ShowStartingNode="false" /&gt; &lt;asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource" Orientation="Horizontal" CssClass="sf-menu"&gt; &lt;/asp:Menu&gt; </code></pre> <p>Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the <code>CssClass="sf-menu"</code> gets overwritten when the Menu is rendered and the <code>&lt;ul&gt;</code> tag gets a <code>class="AspNet-Menu"</code>. I thought the line <code>$('ul.AspNet-Menu').superfish();</code> would help, but it didn't. </p> <p><strong>ONE MORE THING</strong></p> <p>Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the <code>superfish.css</code> file and <em>search and replacing</em> <strong>sf-menu</strong> with <strong>AspNet-Menu</strong>... and voila! the menu appeared. I thought there would be some configuration setting in the <code>asp:Menu</code> control where I could set the <code>&lt;ul&gt;</code> class but didn't find any hints via google.</p>
Specifying location of new inlineshape in Word VBA? <p>I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.</p> <p>Currently, this is being done as a <code>Shape</code>, rather than an <code>InlineShape</code>. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.</p> <p>The problem with this is that a <code>Shape</code> doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.</p> <p>Long story short, how do I position an <code>InlineShape</code> using VBA in Word?</p> <p>The version I'm using is Word 97.</p>
<p>InlineShape is treated as a letter. Hence, the same technique.</p> <pre><code>ThisDocument.Range(15).InlineShapes.AddPicture "1.gif" </code></pre>
how do I query multiple SQL tables for a specific key-value pair? <p>Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.</p> <p>Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.</p>
<p>What about?</p> <pre><code>SELECT * FROM mod_a WHERE section_id=value UNION ALL SELECT * FROM mod_b WHERE section_id=value UNION ALL SELECT * FROM mod_c WHERE section_id=value </code></pre>
Flash vs. Silverlight <p>We are building a training website where we need to track viewers watching videos and store detailed info about the viewing (when they paused, if they watched the whole video etc)</p> <p>What should we consider when deciding between the two technologies?</p> <p>I forgot to add. This is for an in house app. We have complete control over the environment. If it this was for a public application I would definitely go with Flash.</p> <p>I'm just looking for technical advantages of one over the other from someone who has used both.</p>
<p>I'll chime in because it seems people missed the point of the question: What are the technical advantages of Flash vs Silverlight? (as it pertains to an <em>in-house</em> app)</p> <p><strong>Flash Pros</strong></p> <ul> <li>The "artistic" interface is much better, in my opinion. If you have artists and designers that are used to using Illustrator or Photoshop, this is pretty straight forward.</li> <li>The way their environment integrates frame-based movie timelines is pretty slick and has been for years. It makes it very easy to integrate and layer many different animated elements and sounds into your movie or animation.</li> <li>All coding is done in the JavaScript-esque language ActionScript, so the learning curve for the syntax at least is pretty low for non-microsoft developers.</li> <li>Online support. There are years and years worth of posts that can help you figure out what you need to do to get what you want in Flash.</li> </ul> <p><strong>Silverlight Pros</strong></p> <ul> <li>It uses .Net as a back end. If you have a lot of .Net developers, you'll be able to leverage the .Net framework which is a much more powerful set of tools, programmatically speaking.</li> <li>Easier to debug. In my experience it's easier to debug than Actionscript, largely due to the superior IDE.</li> <li>Bringing me to the IDE. The <em>coding</em> IDE is vastly superior to Flash's clunky, cobbled together, fancified textpad. It has intellisense, auto-complete, etc.</li> </ul> <p><strong>Flash Cons</strong></p> <ul> <li>In my extensive Flash experience, If you're making a highly interactive app, it can be buggy as all get out. Some of the bugs bordering on nonsense, the work arounds being hackish at best.</li> <li>The IDE sucks. Period. It's notepad with some poorly implemented intellisense-esque keyword identification.</li> <li>The language falls on it's face at times. I've seen instances where all of a sudden a var got all type-sensitive on me, where it wasn't just two stanzas prior. My fault? Maybe. Probably. But nonetheless I've seen some weird behavior from ActionScript, whereas C# has always done what I've told it to.</li> <li>No real standard way of doing things. No "best-practice put your code here" way to do things. Flash lets you put code on <em>anything</em>. A frame, a MovieClip, an object, an array... sure whatever, just pop some functions on some stuff and party! This makes finding bugs in someone else's app a real chore.</li> </ul> <p><strong>Silverlight Cons</strong></p> <ul> <li>Not a lot of documentation yet, in my opinion.</li> <li>Substandard "artist" interface by comparision. If you're going for a certain look, it may be harder for your designer to acheive.</li> <li>If you're not used to XAML, layouts can be a real pain in the butt. If you've never used XAML, and you've got a sort timeline to get this thing done, you best be prepared to put in some extra time, or be okay with a less than stellar look and feel. It's not quite as easy to get the look that you want with XAML as it is in Flash.</li> </ul> <p>Again, all of this is in my own <em>opinion</em> and from my <em>experiences</em>. Other people may have different opinions.</p> <p>If you have a few designers and some Flash experience, go with flash. If you want to learn something new, pad your resume, and you've got nothing but .Net experience, go with Silverlight.</p> <p>In the end, do whatever it is that makes you like coming to work. (as long as it meets your deadlines. lol)</p> <p>Oh, and I should note, I wasn't talking about FLEX here, but Flash.</p>
SQL Query Help: Transforming Dates In A Non-Trivial Way <p>I have a table with a "Date" column, and I would like to do a query that does the following:</p> <p>If the date is a <strong>Monday</strong>, <strong>Tuesday</strong>, <strong>Wednesday</strong>, or <strong>Thursday</strong>, the displayed date should be shifted up by 1 day, as in <pre>DATEADD(day, 1, [Date])</pre> On the other hand, if it is a <strong>Friday</strong>, the displayed date should be incremented by 3 days (i.e. so it becomes the following <em>Monday</em>).</p> <p>How do I do this in my SELECT statement? As in,</p> <pre>SELECT somewayofdoingthis([Date]) FROM myTable</pre> <p>(This is SQL Server 2000.)</p>
<p>Here is how I would do it. I do recommend a function like above if you will be using this in other places.</p> <pre><code>CASE WHEN DATEPART(dw, [Date]) IN (2,3,4,5) THEN DATEADD(d, 1, [Date]) WHEN DATEPART(dw, [Date]) = 6 THEN DATEADD(d, 3, [Date]) ELSE [Date] END AS [ConvertedDate] </code></pre>
Tips on refactoring an outdated database schema <p>Being stuck with a legacy database schema that no longer reflects your data model is every developer's nightmare. Yet with all the talk of refactoring code for maintainability I have not heard much of refactoring outdated database schemas. </p> <p>What are some tips on how to transition to a better schema without breaking all the code that relies on the old one? I will propose a specific problem I am having to illustrate my point but feel free to give advice on other techniques that have proven helpful - those will likely come in handy as well.</p> <p><hr /></p> <p>My example:</p> <p>My company receives and ships products. Now a product receipt and a product shipment have some very different data associated with them so the original database designers created a separate table for receipts and for shipments. </p> <p>In my one year working with this system I have come to the realization that the current schema doesn't make a lick of sense. After all, both a receipt and a shipment are basically a transaction, they each involve changing the amount of a product, at heart only the +/- sign is different. Indeed, we frequently need to find the total amount that the product has changed over a period of time, a problem for which this design is downright intractable. </p> <p>Obviously the appropriate design would be to have a single Transactions table with the Id being a foreign key of either a ReceiptInfo or a ShipmentInfo table. Unfortunately, the wrong schema has already been in production for some years and has hundreds of stored procedures, and thousands of lines of code written off of it. How then can I transition the schema to work correctly?</p>
<p>Here's a whole catalogue of database refactorings:</p> <p><a href="http://databaserefactoring.com/">http://databaserefactoring.com/</a></p>
How to generate all permutations of a list in Python <p>How do you generate all the permutations of a list in Python, independently of the type of elements in that list?</p> <p>For example:</p> <pre><code>permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] </code></pre> <p>EDIT: Eliben pointed to a solution that's similar to mine although simpler, so I'm choosing it as the accepted answer, although Python 2.6+ has a builtin solution in the <strong>itertools</strong> module:</p> <pre><code>import itertools itertools.permutations([1, 2, 3]) </code></pre>
<p>And in <a href="http://docs.python.org/dev/whatsnew/2.6.html">Python 2.6</a> onwards:</p> <pre><code>import itertools itertools.permutations([1,2,3]) </code></pre> <p>(returned as a generator. Use <code>list(permutations(l))</code> to return as a list.)</p>
Flash/FLEX 3 Argument Error 2082 <p>Has anyone else experienced this error? Sometimes it pops up at the beginning of loading the application with Argument Error 2082. The only way I can solve it is by rebooting my machine. Restarting the browser doesn't even solve it. I have read about some solutions on the web, but I am interested in knowing what others have tried using that solved the error for them? Thanks in advance.</p>
<p>It's a known bug in Flash, there's a pretty long discussion about it here:</p> <p><a href="http://tech.groups.yahoo.com/group/flexcoders/message/63829" rel="nofollow">http://tech.groups.yahoo.com/group/flexcoders/message/63829</a></p> <p>The long and short of it is you should wrap your localConnection.connect() in a try catch. </p>
WPF Validation for the whole form <p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p> <p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p> <p>I can do this using my own ValidationEngine framework: </p> <pre><code>Customer customer = new Customer(); customer.FirstName = "John"; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.BrokenRules.Count &gt; 0) { // do something display the broken rules! } </code></pre>
<p>A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx">IDataErrorInfo</a> interface on your business object, using Bindings with <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx"><code>ValidatesOnDataErrors</code></a><code>=true</code>. For customizing the look of individual controls in the case of errors, set a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx"><code>Validation.ErrorTemplate</code></a>.</p> <h3>XAML:</h3> <pre><code>&lt;Window x:Class="Example.CustomerWindow" ...&gt; &lt;Window.CommandBindings&gt; &lt;CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCanExecute" Executed="SaveExecuted" /&gt; &lt;/Window.CommandBindings&gt; &lt;StackPanel&gt; &lt;TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;Button Command="ApplicationCommands.Save" IsDefault="True"&gt;Save&lt;/Button&gt; &lt;TextBlock Text="{Binding Error}"/&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>This creates a <code>Window</code> with two <code>TextBox</code>es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The <code>TextBlock</code> beneath the button shows the current errors, so the user knows what's up.</p> <p>The default <code>ErrorTemplate</code> is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at <a href="http://www.codeproject.com/KB/WPF/wpfvalidation.aspx">Validation in Windows Presentation Foundation</a> article on CodeProject for an in-depth look into what can be done about that.</p> <p>To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.</p> <h3>Code Behind</h3> <pre><code>// The CustomerWindow class receives the Customer to display // and manages the Save command public class CustomerWindow : Window { private Customer CurrentCustomer; public CustomerWindow(Customer c) { // store the customer for the bindings DataContext = CurrentCustomer = c; InitializeComponent(); } private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ValidationEngine.Validate(CurrentCustomer); } private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { CurrentCustomer.Save(); } } public class Customer : IDataErrorInfo, INotifyPropertyChanged { // holds the actual value of FirstName private string FirstNameBackingStore; // the accessor for FirstName. Only accepts valid values. public string FirstName { get { return FirstNameBackingStore; } set { FirstNameBackingStore = value; ValidationEngine.Validate(this); OnPropertyChanged("FirstName"); } } // similar for LastName string IDataErrorInfo.Error { get { return String.Join("\n", BrokenRules.Values); } } string IDataErrorInfo.this[string columnName] { get { return BrokenRules[columnName]; } } } </code></pre> <p>An obvious improvement would be to move the <code>IDataErrorInfo</code> implementation up the class hierarchy, since it only depends on the <code>ValidationEngine</code>, but not the business object.</p> <p>While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.</p>
Always have to use .css files? <p>Are .css files always needed? Or may I have a .css "basic" file and store other style items inside the HTML page?</p> <p>Does padding, borders and so on always have to be defined into a .css file stored separately, or may I use them normally into an HTML page?</p>
<p>It is technically possible to use inline CSS formatting exclusively and have no external stylesheet. You can also embed the stylesheet within the HTML document. The best practice in web design is to separate out the CSS into a separate stylesheet. The reason for this is that the CSS stylesheet exists for the purpose of defining the presentation style of the document. The HTML file exists to define the structure and content of the document. And perhaps you may have JavaScript files which exist to add additional behavior to the document.</p> <p>Keeping the presentation, markup, and behavior separate creates a cleaner design.</p> <p>From a practical perspective, if you have a single external CSS stylesheet the browser can cache it. If multiple pages on your site have the same look and feel, they can use the same external stylesheet which only needs to be downloaded once by the web browser. This will make your network bandwidth bills lower as well as creating a faster end user experience.</p>
Any good SQL Anywhere database schema comparison tools? <p>Are there any good database schema comparison tools out there that support Sybase SQL Anywhere version 10? I've seen a litany of them for SQL Server, a few for MySQL and Oracle, but nothing that supports SQL Anywhere correctly. </p> <p>I tried using DB Solo, but it turned all my non-unique indexes into unique ones, and I didn't see any options to change that.</p>
<p>If you are willing to download SQL Anywhere Version 11, and Compare It!, check out the comparison technique shown here:</p> <p><a href="http://sqlanywhere.blogspot.com/2008/08/comparing-database-schemas.html" rel="nofollow">http://sqlanywhere.blogspot.com/2008/08/comparing-database-schemas.html</a></p> <p>You don't have to upgrade your SQL Anywhere Version 10 database.</p>
How can I disable the eclipse server startup timeout? <p>By default when using a webapp server in Eclipse Web Tools, the server startup will fail after a timeout of 45 seconds. I can increase this timeout in the server instance properties, but I don't see a way to disable the timeout entirely (useful when debugging application startup). Is there a way to do this?</p>
<p><img src="http://i.stack.imgur.com/SmwTY.png" alt="enter image description here"> In Eclipse Indigo, you can edit the default timeout by double-clicking on the server in the "servers" view and changing the timeout for start (see graphic). Save your changes, and you're good to go!</p>
C#: Test if string is a guid without throwing exceptions? <p>I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (</p> <ul> <li>for performance reasons - exceptions are expensive</li> <li>for usability reasons - the debugger pops up </li> <li>for design reasons - the expected is not exceptional</li> </ul> <p>In other words the code:</p> <pre><code>public static Boolean TryStrToGuid(String s, out Guid value) { try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } } </code></pre> <p>is not suitable.</p> <p>I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. </p> <p>Additionally, I thought certain Guid values are invalid(?)</p> <hr> <p><strong>Update 1</strong></p> <p><a href="http://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829">ChristianK</a> had a good idea to catch only <code>FormatException</code>, rather than all. Changed the question's code sample to include suggestion.</p> <hr> <p><strong>Update 2</strong></p> <p>Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? </p> <p>The answer is <em>yes</em>. That is why I am using TryStrToGuid - I <strong>am</strong> expecting bad data.</p> <p><strong>Example 1</strong> <a href="http://msdn.microsoft.com/en-us/library/cc144096%28VS.85%29.aspx">Namespace extensions can be specified by appending a GUID to a folder name</a>. I might be parsing folder names, checking to see if the text after the final <strong>.</strong> is a GUID.</p> <pre><code>c:\Program Files c:\Program Files.old c:\Users c:\Users.old c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666} c:\Windows c:\Windows.old </code></pre> <p><strong>Example 2</strong> I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.</p> <p><strong>Example 3</strong> I might be parsing a search expression entered by a user. </p> <p><img src="http://i.stack.imgur.com/Ghb12.png" alt="enter image description here"></p> <p>If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)</p> <hr> <p><strong>Update 3 - Performance benchmarks</strong></p> <p>Test converting 10,000 good Guids, and 10,000 bad Guids.</p> <pre><code>Catch FormatException: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen with try-catch: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks </code></pre> <p><em>p.s. I shouldn't have to justify a question.</em></p>
<p><strong>Performance Benchmarks</strong></p> <pre><code>Catch exception: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks </code></pre> <p><strong>COM Intertop (Fastest) Answer:</strong></p> <pre><code>/// &lt;summary&gt; /// Attempts to convert a string to a guid. /// &lt;/summary&gt; /// &lt;param name="s"&gt;The string to try to convert&lt;/param&gt; /// &lt;param name="value"&gt;Upon return will contain the Guid&lt;/param&gt; /// &lt;returns&gt;Returns true if successful, otherwise false&lt;/returns&gt; public static Boolean TryStrToGuid(String s, out Guid value) { //ClsidFromString returns the empty guid for null strings if ((s == null) || (s == "")) { value = Guid.Empty; return false; } int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value); if (hresult &gt;= 0) { return true; } else { value = Guid.Empty; return false; } } namespace PInvoke { class ObjBase { /// &lt;summary&gt; /// This function converts a string generated by the StringFromCLSID function back into the original class identifier. /// &lt;/summary&gt; /// &lt;param name="sz"&gt;String that represents the class identifier&lt;/param&gt; /// &lt;param name="clsid"&gt;On return will contain the class identifier&lt;/param&gt; /// &lt;returns&gt; /// Positive or zero if class identifier was obtained successfully /// Negative if the call failed /// &lt;/returns&gt; [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)] public static extern int CLSIDFromString(string sz, out Guid clsid); } } </code></pre> <p><hr /></p> <p>Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop. </p> <p>If you need to convert a guid in String representation to a Guid, use</p> <pre><code>new Guid(someString); </code></pre>
Dealing with the rate of change in software development <p>I am primarily a .NET developer, and in that sphere alone there are at any given time probably close to a dozen fascinating emerging technologies, some of them real game-changers, that I would love to delve into. </p> <p>Sadly, this appears to be beyond the limits of human capacity. </p> <p>I read an article by Rocky Lhotka (.NET legend, inventor of CSLA, etc) where he mentioned, almost in passing, that last year he felt very terribly overwheled by the rate of change. He made it sound like maybe it wasn't possible to stay on the bleeding edge anymore, that maybe he wasn't going to try so hard because it was futile. </p> <p>It was a surprise to me that true geniuses like Lhotka (who are probably expected to devote a great deal of their time to playing with the latest technology and should be able to pick things up quickly) also feel the burn!</p> <p>So, how do you guys deal with this? Do you just chalk it up to the fact that development is vast, and it's more important to be able to find things quickly than to learn it all? Or do you have a continuing education strategy that actually allows you to stay close to the cutting edge?</p>
<p>I have been in IT for 30 years now, so perhaps I can offer some perspective. Yes, there is an increasing amount of material to keep abreast of. But the rate of <i>change</i> (as in "progress") is not increasing - if anything, it is decreasing. What we are seeing is a <i>widening</i> of the field.</p> <p>Take a simple example: Once upon a time there was HTML/1. Then came HTML/2 and that was progress. Now we have HTML/4, HTML/5, XHTML/1, Flash, Silverlight, and on and on. Any one of these is progress, but each is progress in a different direction and all are in active use.</p> <p>Stay on top of this? Forget it - it's not possible. On the other hand, good IT folks can pick up a new language or a new technology in a few weeks at most - no big deal. Try to pick out the genuinely new ideas and learn about them. Ignore all the specific technologies (IIS 7, SQL Server 2008, etc.) unless and until you need them.</p> <p>Continuing the Internet as an example, the last real innovation were the ideas behind Web 2.0. I took the opportunity to learn Ruby at the same time - did a couple of small, throw-away projects in Ruby on Rails. If a project in this area comes along, the ideas will be the same in whatever environment.</p> <p>One does occasionally get frustrated. It's not always easy to pick out the truly new ideas amidst all the marketing hype.</p> <p>All the best...</p> <p>Brad</p>
Is there a .NET performance counter to show the rate of p/invoke calls being made? <p>Is there a .NET performance counter to show the rate of p/invoke calls made? I've just noticed that the application I'm debugging was making a call into native code from managed land within a tight loop. The intended implementation was for a p/invoke call to be made once and then cached. I'm wondering if I could have noticed this mistake via a CLR Interop or Remoting .NET performance counter. Any ideas?</p>
<p>Try the ".NET CLR Interop" for "# of marshalling" performance counter.</p> <p>See this article for more <a href="http://msdn.microsoft.com/en-us/library/ms998551.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms998551.aspx</a>.</p>
Are there any ORM tools for Haskell? <p>What is the best way to interact with a database using Haskell? I'm accustomed to using some sort of ORM (Django's ORM, hibernate, etc.) and something similar would be nice when creating apps with <a href="http://www.happs.org/">HAppS</a>.</p> <p><strong>Edit:</strong> I'd like to be free to choose from Postgresql MySql and SQLite as far as the actual databases go. </p>
<p>The library I have in mind is not an ORM, but it may still do what you want.</p> <p>If you want something that makes your database accesses safe while integrating things into your program nicely then try out <a href="http://www.haskell.org/haskellwiki/Applications_and_libraries/Database_interfaces/HaskellDB">HaskellDB</a>. It basically looks at your schema, generates some data structures, and then gives you type safe ways to query. It's been around for quite a while and the community opinion is that it's good and stable.</p> <p>To use it, you'll need some underlying Haskell DB library like HSQL.</p> <p>Good luck!</p>
How should a blog be structured to easily extract its data? <p>I'm currently using Wordpress to run my website. However, with each new release I become more concerned with software bloat and the convoluted table structures used to store my data. Maybe this is a fruitless pursuit. Features are always added to blogging software until it claims to be a CMS--and at that point your data is probably stuck.</p>
<p>You do have the option of sticking with the 2.0 branch. This will be maintained with just bug fixes until 2010. Take a look at <a href="http://wordpress.org/download/legacy/" rel="nofollow">http://wordpress.org/download/legacy/</a></p>
CSS: Display differences <p>What is the difference between display:block and display:inline</p>
<p>display: block <br />will cause the object to force other objects within a container on to a new line.</p> <p>display: inline <br />tries to display the object on the same line as other objects.</p> <p>display:block</p> <pre> Item 1 Item 2 Item 3 </pre> <p>display:inline</p> <pre> Item 1 Item 2 Item 3 </pre>
Why use WinDbg vs the Visual Studio (VS) debugger? <p>What are the major reasons for using <a href="http://en.wikipedia.org/wiki/WinDbg">WinDbg</a> vs the Visual Studio debugger?</p> <p>And is it commonly used as a complete replacement for the Visual Studio debugger, or more for when the need arises.</p>
<p>If you are wondering why you should use windbg over Visual Studio, then you need to read <a href="http://rads.stackoverflow.com/amzn/click/0321374460">Advanced Windows Debugging</a>. Any time you need to debug a truly ugly problem windbg has better technology to do it with than Visual Studio. Windbg has a more powerful scripting language and allows you to write DLLs to automate difficult problems. It will install gflags.exe, which gives you better control over the heap for debugging memory overwrites. </p> <p>You don't actually need to run the install, you can just copy the files over and be ready to go. Also it installs adsplus.vb, so you can take mini-dumps of running processes. It is also very easy to setup to perform remote debugging. There is nothing better than being able to debug a problem from your own desk instead of fighting the 15" monitor that flickers on a test PC. </p> <p>For day to day code writing I use Visual Studio, but once you need to start debugging problems from other computers or find yourself in a very ugly situation, windbg is the only way to go. Spending some time learning windbg is a great investment. Also if you look at crash dumps there are two great resources, <a href="http://www.dumpanalysis.org/blog">http://www.dumpanalysis.org/blog</a> and <a href="http://blogs.msdn.com/ntdebugging/default.aspx">http://blogs.msdn.com/ntdebugging/default.aspx</a> that do all their debugging using windbg. </p>
Where'd my generic ActionLink go? <p>Moved from preview 2 to preview 5 and now my Html.ActionLink calls are all failing. It appears that the generic version has been replaced with a non-type safe version.</p> <pre><code>// used to work &lt;li&gt; &lt;%= Html.ActionLink&lt;HomeController&gt;(c =&gt; c.Index(), "Home")%&gt; &lt;/li&gt; // what appears I can only do now &lt;li&gt; &lt;%= Html.ActionLink&lt;HomeController&gt;("Index", "Home")%&gt; &lt;/li&gt; </code></pre> <p>Why did The Gu do this? Has it been moved to Microsoft.Web.Mvc or somewhere else as a "future"? Is there a replacement that is generic? Halp! </p>
<p>Don't blame the GU, it's my fault. That method has been moved to MvcFutures. Here's a <a href="http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx">blog post that provides the foundation for why this change was made</a>.</p>
Automated way to detect tests that can't fail, checked in to get by minmum code coverage? <p>I have a dev, that will get around our code coverage by writing tests that never fail.</p> <p>The code is just atrocious, but the tests never catch it because they assert(true).</p> <p>I code review, but I can't do everyones work for them, all the time. How do you get people like this motivated to make good software?</p> <p>Is there a build plugin for detecting tests that can't fail?</p> <p>C#, mbUnit tests.</p>
<p>Real motiviation comes from within. Some people will game the system every chance they get sometimes for no other reason than they can. Others do it simply because they are hacks.</p> <p>That said, assuming your the manager, have a "come to jesus" meeting with the dev. If that still doesn't work, there's always the door.</p> <p>If you're not the manager, then take it up the proper channels.</p>
Is there a Java-based ray tracing model that can be adapted for use in underwater acoustics? <p>I am looking for an open-source Java-based raytracing system suitable for use in modeling underwater ray-based acoustics. Such a package might be similar to the Comprehensive Acoustic System Simulation (CASS) with the Gaussian Ray Bundle (GRAB) but I would prefer an open-source, free-to-use or free-to-modify model that I can use in presentations to an open forum (e.g., JavaOne).</p> <p>The best model for my needs would provide ray path modeling based on an environmental model, bathymetry (also known as ocean bottom topography) and emitter frequency spectra. Note: multipath effects (including reflection and refraction) are my primary points of interest so the best package would provide that right out of the box.</p> <p>Slightly less optimal would be a standard Java-based ray-tracing package (optical or acoustic) that can handle a a varying speed through the medium. Another way of saying this would be that the index of refraction varies in a continuous fashion throughout the medium (though its first derivative might not be continuous).</p>
<p>The <a href="http://sourceforge.net/projects/rapsor" rel="nofollow">RaPSor</a> project appears to be a java based ray-tracing simulator. It actually stands for Radio Propagation Simulator and was developed initially to support radio signal propagation for things like projecting dead spots in the WiFi coverage in buildings.</p> <p>Reading through some of the <a href="http://sourceforge.net/projects/rapsor/files/RaPSor.pdf/download" rel="nofollow">use case paper</a> for it shows that it does ray tracing and can be extends to support acoustic ray tracing. The <a href="http://netbeans.org/community/articles/interviews/ray-simulation-analysis.html" rel="nofollow">blog</a> article that tipped me off refers to the idea of figuring out the acoustic sound field for a room, but I don't see why it needs to be limited to in-air propagation.</p> <p>Also, it was built using the NetBeans project.</p>
What are indexes and how can I use them to optimize queries in my database? <p>I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures.</p> <p>I always hear that "adding an index" can be done to help performance. I am certainly no DBA, and I do not understand what indexes are, why they help, and how to create them.</p> <p>I basically need an indexes 101. </p> <p>Can anyone give me resources so that I can learn?</p>
<p>As a rule of thumb, indexes should be on any fields that you use in joins or where clauses (if they have enough different values to make using an index worthwhile, field with only a few possible values doesn't benefit from an index which is why it is pointless to try to index a bit field). </p> <p>If your structure has formally created primary keys (which it should, I never create a table without a primary key), those are by definition indexed becasue a primary key is required to have a unique index on it. People often forget that they have to index the foreign keys becasue an index is not automatically created when you set up the foreign key relationsship. Since the purpose of a foreign key is to give you a field to join on, most foreign keys should probably be indexed.</p> <p>Indexes once created need to be maintained. If you have a lot of data change activity, they can get fragmented and slow performance and need to be refreshed. Read in Books online about indexes. You can also find the syntax for the create index statement there.</p> <p>Indexes are a balancing act, every index you add usually will add time to data inserts, updates and deletes but can potentially speed up selects and joins in complex inserts, updates and deletes. There is no one formula for what are the best indexes although the rule of thumb above is a good place to start.</p>
How do I stop Blend 2.5 June Preview replacing Canvas.ZIndex with Panel.ZIndex on SL1.0 XAML? <p>I have a Silverlight 1.0 application that I edit with Blend 2.5. Whenever I touch a <code>UIElement</code> in the designer that has a Canvas attribute such as <code>Canvas.ZIndex="1"</code>, when it updates the XAML, it changes the Canvas prefix to Panel, leaving <code>Panel.ZIndex="1"</code>, causing the page to fail to load.</p> <p>How do I make it stop the insanity!?!</p> <p>I have uninstalled 2.5 and reinstalled an older Blend 2 preview and that was better, but then compatibility with VS2k8 was not as good, and I'm also working on some SL2.0 projects from time to time, as well as WPF apps, both of which I prefer Blend 2.5 for.</p>
<p>Looks like it's a reported bug in 2.5,</p> <p><a href="http://social.expression.microsoft.com/forums/en-US/blend/thread/db02b75c-922e-4de1-8943-bd525d9862c0/" rel="nofollow">http://social.expression.microsoft.com/forums/en-US/blend/thread/db02b75c-922e-4de1-8943-bd525d9862c0/</a></p> <p>Their suggested workaround is to use 2.0 for SL1. Still, I expect there will be a new version of Blend released fairly shortly, since SL2 is likely to be released around PDC this year (end of October).</p>
VSTO Excel 2007 PivotTable, having a PivotField in more than one column <p>I am using VSTO with Excel 2007 to generate PivotTables and PivotCharts dynamically. I am having a problem when I need to have a PivotField in more than one column. </p> <p>To accomplish this I create a PivotTable in Excel and serialize its properties into an XML document, which I then use to rebuild the PivotTable.</p> <p>Ie: as a Value and as a Column</p> <p>This is possible when building the PivotTable in Excel. Has found a way to do this using C# ?</p> <p><a href="http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx" rel="nofollow">Creating a PivotTable Programmatically</a></p>
<p>If you add a calculated field to a Piviot Table and make the formula simply be the name of the field you need a duplicate of that allows you to use the same field twice, the Calculated Field does have to be a Value field. </p> <p>Prehaps you can do this programaticly.</p>
What is a good functional language on which to build a web service? <p>Is there a functional language that has good support and tools for building web services? I've been looking at Scala (which compiles to the JVM and can use the Java libraries) and F# (which is .NET), but these are young and have some inefficiencies. Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM). F# is very new and doesn't seem to be fully supported yet, which makes it riskier than a more conventional language.</p> <p>Is it possible to build a web service using Haskell, ML, or any of the other more traditional functional languages, or would it be better to go with Scala or F#? Any other suggestions?</p>
<p>If .NET is an option for the platform, don't discount F# because of its youth. As it get closer to becoming an official product, it is getting better and better integration with Visual Studio and inherits all the goodness afforded by .NET. </p> <p>There is also active and accessible support by both Microsoft and an enthusiastic community.</p>
What are some excellent examples of user sign-up forms on the web? <p>I'm trying to get a sampling of what people think are the best sign-up forms. Good design, usability. Smart engineering. Helpful feedback.</p>
<p>One of my all-time fave sign-up forms was the original <a href="http://www.vox.com/" rel="nofollow">Vox</a> one, which has since been changed; there was <a href="http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html" rel="nofollow">a great break-down</a> of it published online, and it goes into the things that made it so great to me. How they implemented the CSS layout of their forms, how they used in-form validation with pop-up tips, etc. -- it was nice.</p>
.NET String.Format() to add commas in thousands place for a number <p>I want to add a comma in the thousands place for a number. <code>String.Format()</code>?</p>
<pre><code>String.Format("{0:n}", 1234); string.Format("{0:n0}", 9876); // no digits after the decimal point. </code></pre>
How do I get a string type of a hex value that represents an upper ascii value character <p>Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).</p> <p>In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)</p> <p>Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?</p> <p>Calling code :</p> <pre><code>// S is Hex number!!! return Convert.ToChar(HexStringToInt(s)).ToString(); </code></pre> <p>Helper method:</p> <pre><code>private static int HexStringToInt(string hexString) { int i; try { i = Int32.Parse(hexString, NumberStyles.HexNumber); } catch (Exception ex) { throw new ApplicationException("Error trying to convert hex value: " + hexString, ex); } return i; } </code></pre>
<p>This looks like a character encoding issue to me. Unicode doesn't include any characters with numbers in the upper-ASCII 128-255 range, so trying to convert character 133 will fail.</p> <p>Need to convert it first to a character using the proper decoding, Convert.toChar appears to be using UTF-16.</p> <p>Sometimes there's a manual bit manipulation hack to convert the character from upper ASCII to the appropriate unicode char, but since the ellipsis wasn't in most of the widely used extended ASCII codepages, that's unlikely to work here.</p> <p>What you really want to do is use the <a href="http://msdn.microsoft.com/en-us/library/744y86tc.aspx" rel="nofollow">Encoding.GetString(Byte[])</a> method, with the proper encoding. Put your value into a byte array, then GetString to get the C# native string for the character.</p> <p>You can learn more about RTF character encodings on the <a href="http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding" rel="nofollow">RTF Wikipedia page</a>.</p> <p>FYI: The horizontal ellipsis is <a href="http://unicode.org/charts/PDF/U2000.pdf" rel="nofollow">character U+2026 (pdf)</a>.</p>
SEO and hard links with dynamic URLs <p>With ASP.NET MVC (or using HttpHandlers) you can dynamically generate URLs, like the one in this question, which includes the title.</p> <p>What happens if the title changes (for example, editing it) and there's a link pointing to the page from another site, or Google's Pagerank was calculated for that URL?</p> <p>I guess it's all lost right? (The link points to nowhere and the pagerank calculated is lost)</p> <p>If so, is there a way to avoid it?</p>
<p>I use the same system as is in place here, everything after the number in the URL is not used in the db query, then I 301 redirect anything else to be the title.</p> <p>In other words, if the title changed, then it would redirect to the correct place. I do it in PHP rather than htaccess as it's easier to manage more complex ideas.</p>
How do I set the default database in Sql Server from code? <p>I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.</p>
<p><code>ALTER LOGIN</code> should be used for SQL Server 2005 or later:</p> <p><a href="http://technet.microsoft.com/en-us/library/ms189828.aspx">http://technet.microsoft.com/en-us/library/ms189828.aspx</a></p> <pre><code>ALTER LOGIN &lt;login_name&gt; WITH DEFAULT_DATABASE = &lt;default_database&gt; </code></pre> <p><code>sp_defaultdb</code> eventually will be removed from SQL Server:</p> <p><a href="http://technet.microsoft.com/en-us/library/ms181738.aspx">http://technet.microsoft.com/en-us/library/ms181738.aspx</a></p>
Which SharePoint 2007 features are not available to Office 2003 users? <p>I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?</p> <p>I have been searching for awhile but I cannot seem to find a comprehensive list.</p> <p>Thanks :)</p>
<p>There is an entire MS white paper on Office integration with SharePoint:</p> <p><a href="http://download.microsoft.com/download/5/d/c/5dcfc15a-c31e-4a14-93cf-b44bce3e447e/Microsoft%20Office%20and%20SharePoint%20Integration%20White%20Paper.doc" rel="nofollow">http://download.microsoft.com/download/5/d/c/5dcfc15a-c31e-4a14-93cf-b44bce3e447e/Microsoft%20Office%20and%20SharePoint%20Integration%20White%20Paper.doc</a></p>
How can I best connect Seam and GWT in a stateful web application? <p>We have a web application that was implemented using GWT. What it presents is fetched from a Jboss/Seam server using the remoting mechanism, and this works fine. However, the application is now extended to support sessions and users. The Seam GWT service doesn't seem to provide a way to let me log in such that Seam can return restricted data back to the GWT application, and so it looks to me that I will have to wrap the GWT application in facelets.</p> <p>It is not obvious to me that a login using the Seam session mechanism will help me get correct data into the GWT application however, so my question is whether I will be lucky and it will just work, or if I need to do some client side magic, server side magic or if my perception of missing login functionality in the Seam GWT service actually is wrong.</p> <p>Bonus points to anyone that can provide me with a complete example showing something similar.</p>
<p>It turns out that things are "just working" as I hoped. By using Seam's Identity and login mechanism, I can access the current logged in user via <code>Identity.instance().getUsername();</code> in the service code that gets requests from the GWT portion of the application.</p> <p>I tried to put a <code>@Restrict</code> annotation on the service, but this did not appear to work, however this is not something that is not needed as long as I can provide results to the GWT application based on the logged in user.</p>
What is your favorite Visual Studio add-in/setting? <p>What add-in/setting in Visual Studio can you not live without? Which one improves your productivity or fixes something you can't stand in Visual Studio? Why is it your favorite?</p> <p>My favorite is <a href="http://www.ardentdev.com/blog/index.php/aspxedithelper">aspx edit helper</a> because it does really improve my productivity when working with ASP.NET applications. What it does is provide a quick way to type out server side controls, it automatically fills in runat="server" and id="" and puts your cursor in between the quotes of ID so you can type it in.</p> <p><strong>Here is a summarized list of all the plugins discussed so far</strong></p> <ol> <li><a href="http://www.ardentdev.com/blog/index.php/aspxedithelper">ASPX Edit Helper</a> - Snippets for editing asp.net</li> <li><a href="http://www.jetbrains.com/resharper/index.html">Re-Sharper</a> - Fast Refactoring</li> <li><a href="http://code.msdn.microsoft.com/PowerCommands">Power Commands</a></li> <li><a href="http://www.red-gate.com/products/reflector/">Reflector</a></li> <li><a href="http://www.roland-weigelt.de/ghostdoc/">GhostDoc</a> - Generates XML comments</li> <li><a href="http://www.wholetomato.com/">Visual Assist X</a></li> <li><a href="http://www.hanselman.com/blog/IntroducingRockScroll.aspx">Rock Scroll</a></li> <li><a href="http://testdriven.net/">TestDriven.NET</a></li> <li><a href="http://www.ncover.com/">NCover</a></li> <li><a href="http://ankhsvn.open.collab.net/">AnkhSVN</a> - SVN Integration</li> <li><a href="http://www.viemu.com/">ViEmu</a> - Vim Emulation</li> <li><a href="http://www.visualsvn.com/">VisualSVN</a> - SVN Integration</li> <li><a href="http://frickinsweet.com/tools/Theme.mvc.aspx">Theme Generator</a></li> <li><a href="http://www.codeproject.com/KB/dotnet/Skype%5Fin%5FVisual%5FStudio.aspx">Skype Add-in</a></li> <li><a href="http://www.codeplex.com/xmlexplorer">XML Explorer</a></li> <li><a href="http://www.codeplex.com/ResourceRefactoring">Resource Refactoring</a></li> <li><a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx">Linq2Sql Debugger Visualizer</a> - Easily debug Linq2SQL</li> <li><a href="http://www.mindscape.co.nz/products/vsfileexplorer/">Visual Studio File Explorer</a></li> <li><a href="http://www.codeplex.com/VSWindowManager">Visual Studio Window Manager</a></li> <li><a href="http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx">TFS PowerToys</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/bb397975.aspx">Expression Tree Visualizer</a></li> <li><a href="http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1425">StyleCop</a></li> <li><a href="http://janyou.itpub.net/post/8897/460372">Regions Manager</a></li> <li><a href="http://www.rauchy.net/regionerate/">Regionerate</a></li> <li><a href="http://www.codekeep.net/addins.aspx">Code Keep</a> - Manage Code Snippets from anywhere</li> <li><a href="http://code.google.com/p/cr-documentor/">CR Documentor</a></li> <li><a href="http://code.google.com/p/dxcorecommunityplugins/">DXCore Community Plugins</a></li> <li><a href="http://www.nunit.org">NUnit</a></li> <li><a href="http://msdn.microsoft.com/en-us/vcsharp/dd218053.aspx">CodeRush Xpress</a></li> <li><a href="http://www.codeplex.com/jslint">JSLint</a></li> <li><a href="http://www.codeplex.com/NUnitForVS">NUnit for VS</a> - NUnit integration</li> <li><a href="http://www.developerfusion.com/community/blog-entry-redirect/8388451/">Instant Gratification</a> - Tells you how awesome your code is</li> <li><a href="http://entrian.com/source-search/">Entrian Source Search</a>, a Code Search add-in. "Find In Files" on steroids.</li> <li><a href="http://www.redlizards.com/">Goanna</a> - static analysis for C/C++</li> <li><a href="http://www.exactmagic.com/products/studiotools/index.html">StudioTools</a></li> <li><a href="http://www.usysware.com/dpack/">USysWare DPack Code Browser</a> - Fast code navigation </li> </ol>
<p><a href="http://www.jetbrains.com/resharper/index.html">ReSharper!</a> - It blows away the refactoring utils that are built-in to VS, and the default hotkeys as well. Once you get used to it, you'll never want to work on a VS installation that doesn't have it!</p> <p>And if you use Subversion, <a href="http://visualsvn.com/">VisualSVN</a> is awesome! </p>
Fetch top X users, plus a specific user (if they're not in the top X) <p>I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?</p> <p>Thanks!</p>
<p>If I understand correctly, you could do:</p> <pre><code>select * from users order by max(rank) desc limit 0, 49 union select * from users where user = x </code></pre> <p>This way you get 49 top users plus your particular user.</p>
Changing the default settings for a console application <p>I would prefer that a console app would default to </p> <p>multithreaded debug. warning level 4. build browse information. no resource folder.</p> <p>Does anyone know of any technique that would allow me to create a console app, with my desired options, without manually setting it.</p>
<p>Yes, you can do that. What you want is to create your own project template. You can then select that template from the New Project wizard. I wasn't able to location documentation on how to create a project template in Visual Studio 6, but <a href="http://msdn.microsoft.com/en-us/library/ms247120(VS.80).aspx" rel="nofollow">this MSDN article</a> explains the procedure for Visual Studio 2005. Hopefully you will find those instructions to sufficiently similar.</p>
Why do I need to SEM_PRIORITY_Q when using a VxWorks inversion safe mutex? <p>In VxWorks, I am creating a mutex with the SEM_INVERSION_SAFE option, to protect against the priority inversion problem.<br /> The manual says that I <strong>must</strong> also use the SEM_PRIORITY_Q option. Why is that?</p>
<p>When creating a mutex semaphore in VxWroks, you have two options to deal with multiple tasks queued (waiting) for the semaphore: FIFO or Highest priority task first.</p> <p>When you use the SEM_INVERSION_SAFE option, the task holding the mutex will be bumped up to the same priority as the highest priority task waiting for the semaphore.</p> <p>If you were to use a FIFO queue for the semaphore, the kernel would have to traverse the queue of tasks waiting for the mutex to find the one with the highest priority. This operation is not deterministic, as the time to traverse the queue changes as the number of tasks queued changes.</p> <p>When you use a SEM_PRIORITY_Q option, the kernel simply has to look at the task at the head of the queue, as it is the highest priority. This is a constant time operation.</p>
Why unicode() uses str() on my object only with no encoding given? <p>I start by creating a string variable with some <strong>non-ascii</strong> <em>utf-8</em> encoded data on it:</p> <pre><code>&gt;&gt;&gt; text = 'á' &gt;&gt;&gt; text '\xc3\xa1' &gt;&gt;&gt; text.decode('utf-8') u'\xe1' </code></pre> <p>Using <code>unicode()</code> on it raises errors...</p> <pre><code>&gt;&gt;&gt; unicode(text) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) </code></pre> <p>...but if I know the encoding I can use it as second parameter:</p> <pre><code>&gt;&gt;&gt; unicode(text, 'utf-8') u'\xe1' &gt;&gt;&gt; unicode(text, 'utf-8') == text.decode('utf-8') True </code></pre> <p>Now if I have a class that returns this text in the <code>__str__()</code> method:</p> <pre><code>&gt;&gt;&gt; class ReturnsEncoded(object): ... def __str__(self): ... return text ... &gt;&gt;&gt; r = ReturnsEncoded() &gt;&gt;&gt; str(r) '\xc3\xa1' </code></pre> <p><code>unicode(r)</code> seems to use <code>str()</code> on it, since it raises the same error as <code>unicode(text)</code> above:</p> <pre><code>&gt;&gt;&gt; unicode(r) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) </code></pre> <p>Until now everything is as planned!</p> <p><strong>But as no one would ever expect, <code>unicode(r, 'utf-8')</code> won't even try:</strong></p> <pre><code>&gt;&gt;&gt; unicode(r, 'utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found </code></pre> <p>Why? Why this inconsistent behavior? Is it a bug? is it intended? Very awkward.</p>
<p>The behaviour does seem confusing, but intensional. I reproduce here the entirety of the unicode documentation from the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow">Python Built-In Functions documentation</a> (for version 2.5.2, as I write this):</p> <blockquote> <p><strong>unicode([object[, encoding [, errors]]])</strong></p> <p>Return the Unicode string version of object using one of the following modes:</p> <p>If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised. Error handling is done according to errors; this specifies the treatment of characters which are invalid in the input encoding. If errors is 'strict' (the default), a ValueError is raised on errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded. See also the <a href="http://docs.python.org/lib/module-codecs.html" rel="nofollow">codecs</a> module.</p> <p>If no optional parameters are given, unicode() will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings. More precisely, if object is a Unicode string or subclass it will return that Unicode string without any additional decoding applied.</p> <p>For objects which provide a __unicode__() method, it will call this method without arguments to create a Unicode string. For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode.</p> <p>New in version 2.0. Changed in version 2.2: Support for __unicode__() added. </p> </blockquote> <p>So, when you call <code>unicode(r, 'utf-8')</code>, it requires an 8-bit string or a character buffer as the first argument, so it coerces your object using the <code>__str__()</code> method, and attempts to decode that using the <code>utf-8</code> codec. Without the <code>utf-8</code>, the <code>unicode()</code> function looks for a for a <code>__unicode__()</code> method on your object, and not finding it, calls the <code>__str__()</code> method, as you suggested, attempting to use the default codec to convert to unicode.</p>
Standard concise way to copy a file in Java? <p>It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution.</p> <p>Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?</p>
<p>As toolkit mentions above, Apache Commons IO is the way to go, specifically <a href="https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html" rel="nofollow">FileUtils</a>.<a href="https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#copyFile(java.io.File,%20java.io.File)" rel="nofollow">copyFile()</a>; it handles all the heavy lifting for you.</p> <p>And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; <a href="http://www.javalobby.org/java/forums/t17036.html" rel="nofollow">NIO can significantly increase file-copying performance</a>, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.</p>
Unit Testing Guidelines <p>Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):</p> <ul> <li>Should tests be in the same project as application logic?</li> <li>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</li> <li>How should I name my test classes, methods, and projects (if they go in different projects)</li> <li>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</li> <li>Should unit and integration tests be separated?</li> <li>Is there a <strong>good</strong> reason not to have 100% test coverage?</li> </ul> <p>What am I not asking about that I should be?</p> <p>An online resource would be best.</p>
<p>I would recommend <a href="http://rads.stackoverflow.com/amzn/click/0321146530">Kent Beck's</a> book on TDD.</p> <p>Also, you need to go to <a href="http://martinfowler.com/articles/mocksArentStubs.html">Martin Fowler's</a> site. He has a lot of good information about testing as well.</p> <p>We are pretty big on TDD so I will answer the questions in that light.</p> <blockquote> <p>Should tests be in the same project as application logic?</p> </blockquote> <p>Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests</p> <blockquote> <p>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</p> </blockquote> <p>Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution.</p> <blockquote> <p>How should I name my test classes, methods, and projects (if they go in different projects)</p> </blockquote> <p>I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so:</p> <pre><code>public class UserBehavior </code></pre> <p>Methods should be named to describe the behavior that you expect.</p> <pre><code>public void ShouldBeAbleToSetUserFirstName() </code></pre> <p>Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization.</p> <blockquote> <p>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</p> </blockquote> <p>Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change.</p> <blockquote> <p>Should unit and integration tests be separated?</p> </blockquote> <p>Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well.</p> <blockquote> <p>Is there a good reason not to have 100% test coverage?</p> </blockquote> <p>I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point.</p> <p>In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.</p>
What is Java EE? <p>I realize that literally it translates to Java Enterprise Edition. But what I'm asking is what does this really mean? When a company requires Java EE experience, what are they really asking for? Experience with EJBs? Experience with Java web apps? </p> <p>I suspect that this means something different to different people and the definition is subjective.</p>
<p>Java EE is a collection of specifications for developing and deploying enterprise applications.</p> <p>In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.</p> <p>The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.</p> <p>The 13 core technologies that make up Java EE are:</p> <ol> <li>JDBC</li> <li>JNDI</li> <li>EJBs</li> <li>RMI</li> <li>JSP</li> <li>Java servlets</li> <li>XML</li> <li>JMS</li> <li>Java IDL</li> <li>JTS</li> <li>JTA</li> <li>JavaMail</li> <li>JAF</li> </ol> <p>The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications. </p> <p>When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.</p>
How best to draw in the console? <p>I'm trying to write a console (as in terminal, not gaming console) pong game in python and I'm having trouble figuring how best to (re)draw the game.</p> <p>I was thinking of having an 2d array as a sort of bitmap, editing the array to reflect the ball/paddles new positions and then casting each row to a string and printing it. However that means that the old "frames" will remain, and if the dimensions of the game are smaller than the console window, old frames will still be visible.</p> <p>Is there a way to delete characters from the console? '\b' I've heard is unreliable.</p> <p>Or is there an easier alternative route to outputting to the console for this sort of app?</p>
<p>It looks like there is a <a href="http://en.wikipedia.org/wiki/Curses_(programming_library)" rel="nofollow">curses</a> port/library for Python:</p> <p><a href="https://docs.python.org/library/curses.html" rel="nofollow">https://docs.python.org/library/curses.html</a></p>
InternalsVisibleTo attribute isn't working <p>I am trying to use the <code>InternalsVisibleTo</code> assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says:</p> <blockquote> <p>'MyClassName' is inaccessible due to its protection level</p> </blockquote> <p>Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas?</p>
<p>Are you absolutely sure you have the correct public key specified in the attribute? Note that you need to specify the full public key, not just the public key token. It looks something like:</p> <pre><code>[assembly: InternalsVisibleTo("MyFriendAssembly, PublicKey=0024000004800000940000000602000000240000525341310004000001000100F73 F4DDC11F0CA6209BC63EFCBBAC3DACB04B612E04FA07F01D919FB5A1579D20283DC12901C8B66 A08FB8A9CB6A5E81989007B3AA43CD7442BED6D21F4D33FB590A46420FB75265C889D536A9519 674440C3C2FB06C5924360243CACD4B641BE574C31A434CE845323395842FAAF106B234C2C140 6E2F553073FF557D2DB6C5")] </code></pre> <p>It's 320 or so hex digits. Not sure why you need to specify the full public key - possibly with just the public key token that is used in other assembly references it would be easier for someone to spoof the friend assembly's identity.</p>
How can I get source and variable values in ruby tracebacks? <p>Here's the last few frames of a typical Ruby on Rails traceback: <img src="http://img444.imageshack.us/img444/8990/rails-lastfew.png" alt="application trace" /></p> <p>And here are the last few frames of a typical Nevow traceback in Python: <img src="http://img444.imageshack.us/img444/9173/nw-lastfew.png" alt="alt text" /></p> <p>It's not just the web environment either, you can make similar comparisons between ipython and irb. How can I get more of these sorts of details in Ruby?</p>
<p>AFAIK, once an exception has been caught it's too late to grab the context in which it was raised. If you trap the exception's new call, you could use evil.rb's Binding.of_caller to grab the calling scope, and do</p> <pre><code>eval("local_variables.collect { |l| [l, eval(l)] }", Binding.of_caller) </code></pre> <p>But that's quite a big hack. The right answer is probably to extend Ruby to allow some inspection of the call stack. I'm not sure if some of the new Ruby implementations will allow this, but I do remember a backlash against Binding.of_caller because it will make optimizations much harder.</p> <p>(To be honest, I don't understand this backlash: as long as the interpreter records enough information about the optimizations performed, Binding.of_caller should be able to work, although perhaps slowly.)</p> <h1>Update</h1> <p>Ok, I figured it out. Longish code follows:</p> <pre><code>class Foo &lt; Exception attr_reader :call_binding def initialize # Find the calling location expected_file, expected_line = caller(1).first.split(':')[0,2] expected_line = expected_line.to_i return_count = 5 # If we see more than 5 returns, stop tracing # Start tracing until we see our caller. set_trace_func(proc do |event, file, line, id, binding, kls| if file == expected_file &amp;&amp; line == expected_line # Found it: Save the binding and stop tracing @call_binding = binding set_trace_func(nil) end if event == :return # Seen too many returns, give up. :-( set_trace_func(nil) if (return_count -= 1) &lt;= 0 end end) end end class Hello def a x = 10 y = 20 raise Foo end end class World def b Hello.new.a end end begin World.new.b rescue Foo =&gt; e b = e.call_binding puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect end </code></pre>
ASP.NET TreeView and Selecting the Selected Node <p>How do I capture the event of the clicking the Selected Node of a TreeView? It doesn't fire the <strong>SelectedNodeChanged</strong> since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?</p> <p><strong>UPDATE</strong>: When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.</p> <p>I'll probably do this over the Christmas holidays and I'll report back with the results.</p> <p><strong>UPDATE</strong>: I have come up with a solution below that sub-classes the TreeView control.</p>
<p>Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method.</p> <pre><code>protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){ // Do whatever you're doing TreeView1.SelectedNode.Selected = false; } </code></pre>
How does one add a custom build step to an automake-based project in KDevelop? <p>I recently started work on a personal coding project using C++ and KDevelop. Although I started out by just hacking around, I figure it'll be better in the long run if I set up a proper unit test suite before going too much further. I've created a seperate test-runner executable as a sub project, and the tests I've added to it appear to function properly. So far, success.</p> <p>However, I'd really like to get my unit tests running every time I build, not only when I explicitly run them. This will be especially true as I split up the mess I've made into convenience libraries, each of which will probably have its own test executable. Rather than run them all by hand, I'd like to get them to run as the final step in my build process. I've looked all through the options in the project menu and the automake manager, but I can't figure out how to set this up.</p> <p>I imagine this could probably be done by editing the makefile by hand. Unfortunately, my makefile-fu is a bit weak, and I'm also afraid that KDevelop might overwrite any changes I make by hand the next time I change something through the IDE. Therefore, if there's an option on how to do this through KDevelop itself, I'd much prefer to go that way.</p> <p>Does anybody know how I could get KDevelop to run my test executables as part of the build process? Thank you!</p> <p>(I'm not 100% tied to KDevelop. If KDevelop can't do this, or else if there's an IDE that makes this much easier, I could be convinced to switch.)</p>
<p> Although you <i>could</i> manipulate the default `make` target to run your tests, it is generally not recommended, because every invocation of </p> <pre>make</pre> <p> would run all the tests. You should use the "check" target instead, which is an accepted quasi-standard among software packages. By doing that, the tests are only started when you run </p> <pre>make check</pre> <p> You can then easily configure KDevelop to run "make check" instead of just "make". </p> <p> Since you are using automake (through KDevelop), you don't need to write the "check" target yourself. Instead, just edit your `Makefile.am` and set some variables: </p> <pre> TESTS = ... </pre> <p>Please have a look at the <a href="http://www.gnu.org/software/automake/manual/html_node/Tests.html#Tests" rel="nofollow">automake documentation, "Support for test suites"</a> for further information.</p>
What's the difference between a POST and a PUT HTTP REQUEST? <p>They both seem to be sending data to the server inside the body, so what makes them different?</p>
<p><strong>HTTP PUT:</strong></p> <p>PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT is <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2">idempotent</a>, but paradoxically PUT responses are not cacheable.</p> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6">HTTP 1.1 RFC location for PUT</a></p> <p><strong>HTTP POST:</strong> </p> <p>POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2">idempotent</a>, however POST responses <em>are</em> cacheable so long as the server sets the appropriate Cache-Control and Expires headers.</p> <p>The official HTTP RFC specifies POST to be:</p> <ul> <li>Annotation of existing resources;</li> <li>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;</li> <li>Providing a block of data, such as the result of submitting a form, to a data-handling process;</li> <li>Extending a database through an append operation. </li> </ul> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP 1.1 RFC location for POST</a></p> <p><strong>Difference between POST and PUT:</strong></p> <p>The RFC itself explains the core difference:</p> <blockquote> <p>The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.</p> </blockquote> <p><strong>Using the right method, unrelated aside:</strong></p> <p>One benefit of <a href="http://en.wikipedia.org/wiki/Resource_oriented_architecture">REST ROA</a> vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods. So for example you would only use PUT when you want to create a resource at that exact location. And you would never use GET to create or modify a resource.</p>
Tools to annotate images <p>What tools do you use to annotate images?</p> <p>I mean, for example, placing a screenshot into documentation with some text bubbles, arrows, numbers for references in text and so on.</p> <p>Sure, you can do all of these in general graphics editor, but a specialized tool (or plugin for a generic editor) would be so much nicer and should produce more consistent results.</p>
<p>The best program I have come across is <a href="http://screenshot-program.com/" rel="nofollow">Screenshot Studio</a>. It is commercial software though and only available for Windows.</p> <p>As mentioned in the comments, there is a free version called <a href="http://screenshot-program.com/fireshot/" rel="nofollow">Fireshot</a>. It is limited to grabbing web pages. The feature set matches up fairly equitably with Screenshot Studio, so should be a viable option for doing web app documentation.</p>
How to compute the critical path of a directional acyclic graph? <p>What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?</p> <p>For example, if I have the following structure:</p> <pre><code> Node A (weight 3) / \ Node B (weight 4) Node D (weight 7) / \ Node E (weight 2) Node F (weight 3) </code></pre> <p>The critical path should be A->B->F (total weight: 10)</p>
<p>I would solve this with dynamic programming. To find the maximum cost from S to T:</p> <ul> <li>Topologically sort the nodes of the graph as S = x_0, x_1, ..., x_n = T. (Ignore any nodes that can reach S or be reached from T.)</li> <li>The maximum cost from S to S is the weight of S.</li> <li>Assuming you've computed the maximum cost from S to x_i for all i &lt; k, the maximum cost from S to x_k is the cost of x_k plus the maximum cost to any node with an edge to x_k.</li> </ul>
Can Flash save content without server-side help? <p>As far as I know, Flash has to pass info off to another external process in order to save files - POSTing to PHP or talking to an executable, right? But every once in a while I hear rumors that Flash is able to open a file, make changes, then save/write those changes, all on its own - is it possible?</p>
<p>This will be available in Flash Player 10:</p> <p>Reading and Writing Local Files in Flash Player 10</p> <p><a href="http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/">http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/</a></p> <p>Otherwise you need to use Adobe AIR, or bounce it off the server.</p> <p>mike chambers</p> <p>[email protected]</p>
How to display latest revision in a file? <p>I'm wondering how do you deal with displaying release revision number when pushing live new versions of your app?</p> <p>You can use <code>$Rev$</code> in a file to get latest revision, but only after you update the file.</p> <p>What if I want to update a string in one file every time I change any file in the repository/directory?</p> <p>Is there a way?</p>
<p>The best way to do this is have a build script for releases that will determine the revision number using <code>svnversion</code> or <code>svn info</code> and insert it into a file. It's always helpful to have a script which:</p> <ol> <li>checks out a clean copy of the source into an empty directory</li> <li>uses <code>svnversion</code> or something similar to compute a build number</li> <li>compiles source into a product</li> <li>creates an archive (zip or tarball or whatever) of the product</li> <li>cleans up: deletes everything but the archive</li> </ol> <p>Then you have a one-step process to create a release with an easily identifiable version. It also helps you avoid giving someone a build from your own working copy, which may have changes that were never checked into source control.</p>
Optimal multiplayer maze generation algorithm <p>I'm working on a simple multiplayer game in which 2-4 players are placed at separate entrypoints in a maze and need to reach a goal point. Generating a maze in general is very easy, but in this case the goal of the game is to reach the goal before everyone else and I don't want the generation algorithm to drastically favor one player over others.</p> <p>So I'm looking for a maze generation algorithm where the optimal path for each player from the startpoint to the goal is no more than 10% more steps than the average path. This way the players are on more or less an equal playing field. Can anyone think up such an algorithm?</p> <p>(I've got one idea as it stands, but it's not well thought out and seems far less than optimal -- I'll post it as an answer.)</p>
<p>An alternative to freespace's answer would be to generate a random maze, then assign each cell a value representing the number of moves to reach the end of the maze (you can do both at once if you decide that you're starting at the 'end'). Then pick a distance (perhaps the highest one with n points at that distance?) and place the players at squares with that value.</p>
Parse multiple XML files with ASP.NET (C#) and return those with particular element <p>Greetings.</p> <p>I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element.</p> <p>Example XML file 1:</p> <pre><code>&lt;file&gt; &lt;title&gt;Title 1&lt;/title&gt; &lt;someContent&gt;Content&lt;/someContent&gt; &lt;filter&gt;filter&lt;/filter&gt; &lt;/file&gt; </code></pre> <p>Example XML file 2:</p> <pre><code>&lt;file&gt; &lt;title&gt;Title 2&lt;/title&gt; &lt;someContent&gt;Content&lt;/someContent&gt; &lt;filter&gt;filter, different filter&lt;/filter&gt; &lt;/file&gt; </code></pre> <p>Example case 1:</p> <p>Give me all XML that has a filter of 'filter'.</p> <p>Example case 2:</p> <p>Give me all XML that has a title of 'Title 1'.</p> <p>Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case.</p> <p>I would prefer that this be done on the server-side, so that I can cache on that end.</p> <p>Functionality from any version of the .NET Framework can be used.</p> <p>Thanks!</p> <p>~James</p>
<p>If you are using .Net 3.5, this is extremely easy with LINQ:</p> <pre><code>//get the files XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); //Give me all XML that has a filter of 'filter'. var filter_elements1 = from p in xe1.Descendants("filter") select p; var filter_elements2 = from p in xe2.Descendants("filter") select p; var filter_elements = filter_elements1.Union(filter_elements2); //Give me all XML that has a title of 'Title 1'. var title1 = from p in xe1.Descendants("title") where p.Value.Equals("Title 1") select p; var title2 = from p in xe2.Descendants("title") where p.Value.Equals("Title 1") select p; var titles = title1.Union(title2); </code></pre> <p>This can all be written shorthand and get you your results in just 4 lines total:</p> <pre><code>XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); var _filter_elements = (from p1 in xe1.Descendants("filter") select p1).Union(from p2 in xe2.Descendants("filter") select p2); var _titles = (from p1 in xe1.Descendants("title") where p1.Value.Equals("Title 1") select p1).Union(from p2 in xe2.Descendants("title") where p2.Value.Equals("Title 1") select p2); </code></pre> <p>These will all be IEnumerable lists, so they are super easy to work with:</p> <pre><code>foreach (var v in filter_elements) Response.Write("value of filter element" + v.Value + "&lt;br /&gt;"); </code></pre> <p>LINQ rules!</p>
Best way to extract a timezone from a mail Date header in Java? <p>I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?</p>
<p>Probably easiest to parse with JodaTime as it supports ISO8601 see <a href="http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html" rel="nofollow">Date and Time Parsing and Formatting in Java with Joda Time</a>.</p> <pre><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); System.out.println(parser2.parseDateTime(your_date_string)); </code></pre> <p>Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone.</p> <p>You must store the date with the timezone after converting to UTC.</p> <p>If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone.</p>
Subclassed form not behaving properly in Designer view (VS 2008) <p>I have subclassed <code>Form</code> to include some extra functionality, which boils down to a <code>List&lt;Image&gt;</code> which displays in a set of predefined spots on the form. I have the following:</p> <pre><code>public class ButtonForm : Form { public class TitleButton { public TitleButton() { /* does stuff here */ } // there's other stuff too, just thought I should point out there's // a default constructor. } private List&lt;TitleButton&gt; _buttons = new List&lt;TitleButton&gt;(); public List&lt;TitleButton&gt; TitleButtons { get { return _buttons; } set { _buttons = value; } } // Other stuff here } </code></pre> <p>Then my actual form that I want to use is a subclass of <code>ButtonForm</code> instead of <code>Form</code>. This all works great, Designer even picks up the new property and shows it up on the property list. I thought this would be great! It showed the collection, I could add the buttons into there and away I would go. So I opened the collection editor, added in all the objects, and lo and behold, there sitting in the designer was a picture perfect view of what I wanted.</p> <p>This is where it starts to get ugly. For some reason or another, Designer refuses to actually generate code to create the objects and attach them to the collection, so while it looks great in Design mode, as soon as I compile and run it, it all disappears again and I'm back to square one. I'm at a total loss as to why this would happen; if the Designer can generate it well enough to get a picture perfect view of my form with the extra behaviour, why can't/won't it generate the code into the actual code file?</p>
<p>First of all you need to inherit your TitleButton class from Component so that the designer knows it is a component that can be created via designer generated code. Then you need to instruct the designer code generator to work on the contents of the collection and not the collection instance itself. So try the following...</p> <pre><code>public class TitleButton : Component { // ... } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List&lt;TitleButton&gt; TitleButtons { // ... } </code></pre>
Code behind in ASP.NET MVC <p>What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?</p>
<p>Here's my list of reasons why code-behind can be useful taken from <a href="http://stackoverflow.com/questions/489415/how-to-get-a-codebehind-file-for-an-asp-net-mvc-view-in-rc1-to-be-created-by-de">my own post</a>. I'm sure there are many more.</p> <ul> <li>Databinding legacy ASP.NET controls - if an alternative is not available or a temporary solution is needed.</li> <li>View logic that requires recursion to create some kind of nested or hierarchical HTML.</li> <li>View logic that uses temporary variables. I refuse to define local variables in my tag soup! I'd want them as properties on the view class at the very least.</li> <li>Logic that is specific only to one view or model and does not belong to an HtmlHelper. As a side note I don't think an HtmlHelper should know about any 'Model' classes. Its fine if it knows about the classes defined inside a model (such as IEnumerable, but I dont think for instance you should ever have an HtmlHelper that takes a ProductModel. HtmlHelper methods end up becoming visible from ALL your views when you type Html+dot and i really want to minimize this list as much as possible.</li> <li>What if I want to write code that uses HtmlGenericControl and other classes in that namespace to generate my HTML in an object oriented way (or I have existing code that does that that I want to port).</li> <li>What if I'm planning on using a different view engine in future. I might want to keep some of the logic aside from the tag soup to make it easier to reuse later.</li> <li>What if I want to be able to rename my Model classes and have it automatically refactor my view without having to go to the view.aspx and change the class name.</li> <li>What if I'm coordinating with an HTML designer who I don't trust to not mess up the 'tag soup' and want to write anythin beyond very basic looping in the .aspx.cs file.</li> <li>If you want to sort the data based upon the view's default sort option. I really dont think the controller should be sorting data for you if you have multiple sorting options accessible only from the view.</li> <li>You actually want to debug the view logic in code that actuallky looks like .cs and not HTML.</li> <li>You want to write code that may be factored out later and reused elsewhere - you're just not sure yet.</li> <li>You want to prototype what may become a new HtmlHelper but you haven't yet decided whether its generic enough or not to warrant creating an HtmlHelper. (basically same as previous point)</li> <li>You want to create a helper method to render a partial view, but need to create a model for it by plucking data out of the main page's view and creating a model for the partial control which is based on the current loop iteration.</li> <li>You believe that programming complex logic IN A SINGLE FUNCTION is an out of date and unmaintainable practice. </li> <li>You did it before RC1 and didn't run into any problems !!</li> </ul> <p><strong>Yes! Some views should not need codebehind at all.</strong></p> <p><strong>Yes! It sucks to get a stupid .designer file created in addition to .cs file.</strong></p> <p><strong>Yes! Its kind of annoying to get those little + signs next to each view.</strong></p> <p><strong>BUT</strong> - It's really not that hard to NOT put data access logic in the code-behind.</p> <p>They are most certainly NOT <a href="http://stevesmithblog.com/blog/codebehind-files-in-asp-net-mvc-are-evil/" rel="nofollow">evil</a>.</p>
best way to get started in setting up Mono for ASP.NET on Mac <p>I have recently gained access to a Mac. I am wondering if anyone has any tips/advice for setting up <a href="http://www.mono-project.com/Main_Page">Mono</a> on a mac for development and execution of ASP.NET? Most resources point to Linux implementations which tend to differ a lot from the way Mac's do things. Any tips or advice would be helpful</p>
<p>To launch the development ASP.NET server, just open a terminal window and run the "xsp2" command from the Mono installation.</p> <p>The only thing that is missing from the Mono distribution on the Mac compared to Linux is the Apache module, that one you will have to compile yourself if you want to deploy your application in production on OSX.</p>
The ideal multi-server LAMP environment <p>There's alot of information out there on setting up LAMP stacks on a single box, or perhaps moving MySQL onto it's own box, but growing beyond that doesn't seem to be very well documented.</p> <p>My current web environment is having capacity issues, and so I'm looking for <strong>best-practices</strong> regarding <strong>configuration tuning</strong>, determining <strong>bottlenecks</strong>, <strong>security</strong>, etc. </p> <p>I presently host around 400 sites, with a fair need for redundany and security, and so I've grown beyond the single-box solution - but am not at the level of a full ISP or dedicated web-hosting company.</p> <p>Can anyone point me in the direction of some good <strong>expertise on setting up a great apache web-farm</strong> with a view to security and future expansion?</p> <p>My web environment consists of 2 redundant MySQL servers, 2 redundant web-content servers, 2 load balancing front-end apache servers that mount the content via nfs and share apache config and sessions directories between them, and a single "developer's" server which also mounts the web-content via nfs, and contains all the developer accounts. </p> <p>I'm pretty happy with alot of this setup, but it seems to be choking on the load prematurely.</p> <p>Thanks!!</p> <p>--UPDATE--</p> <p>Turns out the "choking on the load" is related to <code>mod_log_sql</code>, which I use to send my apache logs to a mysql database. By re-configuring the webservers to write their sql statements to a disk file, and then creating a separate process to submit those to the database it allows the webservers to free up their threads much quicker, and handle a much greater load.</p>
<p>You need to be able to identify bottlenecks and test improvements.</p> <p>To identify bottlenecks, you need to use your system's reporting tools. Some examples:</p> <ul> <li>MySQL has a slow query log. </li> <li>Linux provides stats like load average, iostat, vmstat, netstat, etc.</li> <li>Apache has the access log and the server-status page.</li> <li>Programming languages have profilers, like <a href="http://pear.php.net/package/Benchmark/" rel="nofollow">Pear Benchmark</a>.</li> </ul> <p>Use these tools to identifyy the slowest/biggest offenders and concentrate on them. Try an improvement and measure to see if it actually improves performance. </p> <p>This becomes a never ending loop for two reasons: there's always something in a complex system that can be faster and as your system grows, different functions will start slowing down.</p> <p>Based on the description of your system, my first hunch would be disk io and network io on the NFS servers, then I'd look at MySQL query times. I'd also check the performance of the shared sessions.</p>
Script.aculo.us Autocompleter problem in IE <p>I'm struggling with a problem with the Script.aculo.us Autocompleter control in IE (I've tried it in IE6 &amp; 7). The suggestions fail to appear for the first character is entered into the text box after the page has been loaded. After that initial failure, the control works as it should.</p> <p>I've verified that the suggestions data is returned from the server correctly; the problem appears to have something to do with the positioning of the suggestions element, as other relatively positioned elements on the page move out of position at the moment that you'd expect the suggestions to appear.</p> <p>Has anyone heard of such a problem or have any suggestions on how to fix it?</p> <p>Edit: In response to Chris, I have set the partialChars parameter to 1 and the control works in all the other browsers I've tried, which are the latest versions of Firefox, Safari, Opera, and Chrome. I should probably have made that clear in the first place. Thanks.</p>
<p>I am indeed having the exact same problem. The problem only occurs in IE (also in 8.0 beta)</p> <p>Both Firefox and Chrome I tried, have no issues what-so-ever. </p> <p>According to others this is due to the DOCTYPE declaration in the HTML file. Check here: <a href="http://prototype.lighthouseapp.com/projects/8887/tickets/32-ajax-autocomplete-in-ie-with-doctype" rel="nofollow">http://prototype.lighthouseapp.com/projects/8887/tickets/32-ajax-autocomplete-in-ie-with-doctype</a></p> <p>The bug has also got a ticket at the ruby developer boards: <a href="http://dev.rubyonrails.org/ticket/11051" rel="nofollow">http://dev.rubyonrails.org/ticket/11051</a></p> <p>Both links have got solutions to fix the problem.</p> <p>Hopefully the bug will be fixed in the next version of prototype/scriptaculous :)</p>
Do you use TestLink and are you happy with it? <p>In our project, we use this software for test management. What is your experience with this software ? Does it scale correctly with thousands of tests ? </p>
<p>I used it a while back and liked it, but I didn't have thousands of tests.</p>
Programmatically updating FILEVERSION in a MFC app w/SVN revision number <p>How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <a href="http://www.compuphase.com/svnrev.htm" rel="nofollow">http://www.compuphase.com/svnrev.htm</a> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info. </p> <p>What's the best way to proceed?</p>
<p>An <code>.rc</code> file can <code>#include</code> header files just like <code>.c</code> files can. I have an auto-generated <code>version.h</code> file, which defines things like:</p> <pre><code>#define MY_PRODUCT_VERSION "0.47" #define MY_PRODUCT_VERSION_NUM 0,47,0,0 </code></pre> <p>Then I just have my <code>.rc</code> file <code>#include "version.h"</code> and use those defines.</p> <pre><code>VS_VERSION_INFO VERSIONINFO FILEVERSION MY_PRODUCT_VERSION_NUM PRODUCTVERSION MY_PRODUCT_VERSION_NUM ... VALUE "FileVersion", MY_PRODUCT_VERSION "\0" VALUE "ProductVersion", MY_PRODUCT_VERSION "\0" ... </code></pre> <p>I haven't tried this technique with an MFC project. It might be necessary to move your <code>VS_VERSION_INFO</code> resource to your <code>.rc2</code> file (which won't get edited by Visual Studio).</p>
How do I use (require :PACKAGE) in clisp under Ubuntu Hardy? <p>I am trying to evaluate the answer <a href="http://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp">provided here</a>, and am getting the error: <code>"A file with name ASDF-INSTALL does not exist"</code> when using clisp:</p> <pre><code>dsm@localhost:~$ clisp -q [1]&gt; (require :asdf-install) *** - LOAD: A file with name ASDF-INSTALL does not exist The following restarts are available: ABORT :R1 ABORT Break 1 [2]&gt; :r1 [3]&gt; (quit) dsm@localhost:~$ </code></pre> <p>cmucl throws a similar error:</p> <pre><code>dsm@localhost:~$ cmucl -q Warning: #&lt;Command Line Switch "q"&gt; is an illegal switch CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile With core: /usr/lib/cmucl/lisp.core Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS. or to [email protected] type (help) for help, (quit) to exit, and (demo) to see the demos Loaded subsystems: Python 1.1, target Intel x86 CLOS based on Gerd's PCL 2004/04/14 03:32:47 * (require :asdf-install) Error in function REQUIRE: Don't know how to load ASDF-INSTALL [Condition of type SIMPLE-ERROR] Restarts: 0: [ABORT] Return to Top-Level. Debug (type H for help) (REQUIRE :ASDF-INSTALL NIL) Source: ; File: target:code/module.lisp (ERROR "Don't know how to load ~A" MODULE-NAME) 0] (quit) dsm@localhost:~$ </code></pre> <p>But sbcl works perfectly:</p> <pre><code>dsm@localhost:~$ sbcl -q This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp. More information about SBCL is available at &lt;http://www.sbcl.org/&gt;. SBCL is free software, provided as is, with absolutely no warranty. It is mostly in the public domain; some portions are provided under BSD-style licenses. See the CREDITS and COPYING files in the distribution for more information. * (require :asdf-install) ; loading system definition from ; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #&lt;PACKAGE "ASDF0"&gt; ; registering #&lt;SYSTEM SB-BSD-SOCKETS {AB01A89}&gt; as SB-BSD-SOCKETS ; registering #&lt;SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}&gt; as SB-BSD-SOCKETS-TESTS ("SB-BSD-SOCKETS" "ASDF-INSTALL") * (quit) </code></pre> <p>Any ideas on how to fix this? I found <a href="https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208" rel="nofollow">this post</a> on the internet, but using that didn't work either.</p>
<p>try this before anything else:</p> <pre><code>(require :asdf) </code></pre> <p>you can steal some ideas from the environment we use. it's available at: <a href="http://dwim.hu/darcsweb/darcsweb.cgi?r=HEAD%20hu.dwim.environment;a=summary" rel="nofollow">darcsweb</a></p> <p>see environment.lisp that loads and sets up asdf for us. (sbcl has asdf already loaded)</p>