input
stringlengths
51
42.3k
output
stringlengths
18
55k
Yaws uses old config file <p>I'm developing a web app on Yaws 1.65 (installed through apt) running on Debian etch on a VPS with UML. Whenever I do /etc/init.d/yaws restart or a stop/start, it initializes according to an old version of the config file (/etc/yaws/yaws.conf).</p> <p>I know this because I changed the docroot from the default to another directory (call it A), then a few weeks later changed it to directory B, and the config file has stayed with B for the last several months. But then, after a restart, it switches back to A. If it switched back to the package default, that would be understandable, but it switches to an old customized version instead.</p> <p>The funny thing is that if I leave it stopped for several minutes, when I start it again, everything switches back to normal (using directory B). But while it's stopped, if I run ps, I don't see any yaws-related processes (yaws, heart, etc). This problem has survived several reboots, so it's got to be an old cached copy of the config somewhere, but I have yet to find anything like that.</p> <p>Any idea what could be going on?</p> <p>Update: @Gorgapor - I stopped yaws, renamed the config file and tried to start it again. It failed to start. However, I was able to restart a couple of times and this time it didn't switch back to the old version.</p>
<p>I'm completely inexperienced with yaws, but I have a troubleshooting suggestion: What happens if you remove the config file completely? If it still starts yaws without a config file, that could be a clear sign that something is being cached.</p> <p>For what it's worth, with a quick 5 minutes of googling, I found no mention of any caching behavior.</p>
Dealing with circular dependencies in OCaml <p>I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed.</p> <p>The only way I know of to solve this is to define all three types at once:</p> <pre><code>type defn = ... and stmt = ... and expr = ... </code></pre> <p>It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code?</p>
<p>Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expressions into separate modules, you can do so using <a href="http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc100">recursive modules</a>, but they will still need to appear in the same file. DAG-ifying inter-file dependencies is one of the annoyances of OCaml.</p>
How to pass a single object[] to a params object[] <p>I have a method which takes params object[] such as:</p> <pre><code>void Foo(params object[] items) { Console.WriteLine(items[0]); } </code></pre> <p>When I pass two object arrays to this method, it works fine:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[] </code></pre> <p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[] </code></pre> <p>How do I pass a single object[] as a first argument to a params array?</p>
<p>A simple typecast will ensure the compiler knows what you mean in this case.</p> <pre><code>Foo((object)new object[]{ (object)"1", (object)"2" })); </code></pre> <p>As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.</p> <p>Edit: Woops, typoed my example code.</p>
What are the important Ruby commands? <p>I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there?</p> <p>Since it might matter, I'm running Windows.</p>
<p>By Ruby commands you probably mean the command line programs for Ruby. These are also called Ruby Helper programs. Here are a few:</p> <ul> <li><p><a href="http://linux.die.net/man/1/ruby">ruby</a> - The interpreter itself. Run Ruby scripts or statements.</p></li> <li><p><a href="http://www.rubygems.org/read/book/2">gem</a> - Ruby Package Manager. Great for automatically downloading or updating small Ruby modules like XML libraries, web servers, or even whole Ruby programs.</p></li> <li><p><a href="http://www.rubycentral.com/pickaxe/irb.html">irb</a> - Interactive Ruby Prompt. This is an entire Ruby shell that will let you execute any Ruby code you want. You can load libraries, test code directly, anything you can do with Ruby you can do in this shell. Believe me, there is quite a lot that you can do with it to improve your Ruby development workflow <a href="http://stackoverflow.com/questions/32537/what-is-the-best-way-to-use-a-console-when-developing#32686">[1]</a>.</p></li> <li><p><a href="http://www.caliban.org/ruby/rubyguide.shtml#ri">ri</a> - Quick shell access to Ruby documentation. You can find the RDoc information on nearly any Ruby Class or method. The same kind of documentation that you would find on the online ruby-docs.</p></li> <li><p><a href="http://stdlib.rubyonrails.org/libdoc/erb/rdoc/index.html">erb</a> - Evaluates embedded Ruby in Ruby Templated documents. Embedded Ruby is just like embedding php into a document, and this is an interpreter for that kind of document. This is really more for the rails crowd. An alternative would be <a href="http://haml.hamptoncatlin.com/">haml</a>.</p></li> <li><p><a href="http://ruby-doc.org/stdlib/libdoc/rdoc/rdoc/index.html">rdoc</a> - Generate the standard Ruby documentation for one of your Ruby classes. Its like Javadocs. It parses the Ruby source files and generates the standard documentation from special comments.</p></li> <li><p><strong>testrb</strong> and <strong>rake</strong>. I'm not familiar enough with these. I'd love it if someone could fill these in!</p></li> </ul> <p>Hopefully this was what you were looking for!</p>
Viewing DirectX application remotely <p>We're working on an application that displays information through a Direct3D visualisation. A late client request is the ability to view this application via some Remote Desktop solution.</p> <p>Has anyone done anything similar? What options are available / unavailable? I'm thinking RDC, VNC, Citrix...</p> <p>Any advice?</p>
<p>I think you can still use all of the normal D3D tools, but you won't be able to render to a surface associated with the screen. You'll have to render to a DIB (or some such) and Blt it with GDI to a normal window HDC. RDC/VNC/Citrix should all work with this technique.</p> <p>Performance will definitely suffer - but that's going to be the case over remote desktop anyway. In fact, if I were you, I would mock up a VERY simple prototype and demonstrate the performance before committing to it. </p> <p>Good luck!</p>
SQL Query, Count with 0 count <p>I have three tables: page, attachment, page-attachment</p> <p>I have data like this:</p> <pre><code>page ID NAME 1 first page 2 second page 3 third page 4 fourth page attachment ID NAME 1 foo.word 2 test.xsl 3 mm.ppt page-attachment ID PAGE-ID ATTACHMENT-ID 1 2 1 2 2 2 3 3 3 </code></pre> <p>I would like to get the number of attachments per page <strong>also when that number is 0</strong>. I have tried with: </p> <pre><code>select page.name, count(page-attachment.id) as attachmentsnumber from page inner join page-attachment on page.id=page-id group by page.id </code></pre> <p>I am getting this output: </p> <pre><code>NAME ATTACHMENTSNUMBER second page 2 third page 1 </code></pre> <p>I would like to get this output:</p> <pre><code>NAME ATTACHMENTSNUMBER first page 0 second page 2 third page 1 fourth page 0 </code></pre> <p>How do I get the 0 part?</p>
<p>Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."</p> <pre><code>select page.name, count(page-attachment.id) as attachmentsnumber from page left outer join page-attachment on page.id=page-id group by page.name </code></pre>
Version Control for word documents <p>How would people recommend doing version control for word documents? Is the in build control up to the job or is it better to rely on dedicated version control systems, and if so, which ones?</p>
<p>@<a href="#36834">lomaxx</a>:</p> <blockquote> <p>Subversion has built in support for word documents </p> </blockquote> <p>More specifically, <a href="http://tortoisesvn.tigris.org">TortoiseSVN</a> does. If you use the TortoiseSVN context menu in explorer to, e.g., bring up a diff, Tortoise will call a script that uses Word's built-in comparison feature to do the actual diff'ing.</p>
Changing a CORBA interface without recompiling <p>I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients?</p> <p>I'm using TAO.</p>
<p>Recompilation of clients is not required (and should not be, regardless of the ORB that you use). As Adam indicated, lookups are done by operation name (a straight text comparison).</p> <p>I've done what you're describing with our ACE/TAO-based system, and encountered no issues (servers were in ACE/TAO C++, clients were ACE/TAO C++, C# using Borland's Janeva, and OmniORBPy).</p>
How to best implement software updates on windows? <p>I want to implement an "automatic update" system for a windows application. Right now I'm semi-manually creating an <a href="http://connectedflow.com/appcasting/">"appcast"</a> which my program checks, and notifies the user that a new version is available. (I'm using <a href="http://nsis.sourceforge.net/Main_Page">NSIS</a> for my installers).</p> <p>Is there software that I can use that will handle the "automatic" part of the updates, perhaps similar to <a href="http://sparkle.andymatuschak.org/">Sparkle</a> on the mac? Any issues/pitfalls that I should be aware of?</p>
<p>There's now a Windows port of Sparkle, see <a href="http://winsparkle.org">http://winsparkle.org</a>.</p>
What is the meaning of "non temporal" memory accesses in x86 <p>This is a somewhat low-level question. In x86 assembly there are two SSE instructions: </p> <blockquote> <p><code>MOVDQA <i><em>xmmi, m128</em></i></code></p> </blockquote> <p>and </p> <blockquote> <p><code>MOVNTDQA <i><em>xmmi, m128</em></i></code></p> </blockquote> <p>The IA-32 Software Developer's Manual says that the <em>NT</em> in MOVNTDQA stands for <em>Non-Temporal</em>, and that otherwise it's the same as MOVDQA.</p> <p>My question is, what does <em>Non-Temporal</em> mean? </p>
<p>Non-Temporal SSE instructions (MOVNTI, MOVNTQ, etc.), don't follow the normal cache-coherency rules. Therefore non-temporal stores must be followed by an SFENCE instruction in order for their results to be seen by other processors in a timely fashion.</p> <p>When data is produced and not (immediately) consumed again, the fact that memory store operations read a full cache line first and then modify the cached data is detrimental to performance. This operation pushes data out of the caches which might be needed again in favor of data which will not be used soon. This is especially true for large data structures, like matrices, which are filled and then used later. Before the last element of the matrix is filled the sheer size evicts the first elements, making caching of the writes ineffective.</p> <p>For this and similar situations, processors provide support for non-temporal write operations. Non-temporal in this context means the data will not be reused soon, so there is no reason to cache it. These non-temporal write operations do not read a cache line and then modify it; instead, the new content is directly written to memory. </p> <p>Source: <a href="http://lwn.net/Articles/255364/">http://lwn.net/Articles/255364/</a></p>
Checking the results of a Factory in a unit test <p>I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has worked correctly?</p> <p>I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.</p> <p>Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.</p>
<p>Since I don't know how your factory method looks like, all I can advise right now is to </p> <ol> <li><p>Check to see the object is the correct concrete implementation you were looking for:</p> <pre><code>IMyInterface fromFactory = factory.create(...); Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1); </code></pre></li> <li><p>You can check if the factory setup the concrete instances with valid instance variables.</p></li> </ol>
How to convert .ICO to .PNG? <p>What tool can I use to convert a .ICO file to a .PNG file?</p>
<p>Google has an ico to png converter, I saw it on <a href="http://www.reddit.com/r/programming/comments/6ytnt/googles_free_favicon_png_online_converter/">reddit</a> the other day.</p> <p><a href="http://www.google.com/s2/favicons?domain=stackoverflow.com">http://www.google.com/s2/favicons?domain=stackoverflow.com</a></p>
Best GUI tool for documenting a SQL Server DB <p>What tool(s) do you use to generate documentation for a database (preferably into a .chm help file)?</p>
<p><H1> SQL Doc </H1></p> <p><strong>Document SQL Server 2000, 2005 and 2008 databases</strong></p> <p><a href="http://www.red-gate.com/products/SQL_Doc/index.htm" rel="nofollow"><img src="http://www.red-gate.com/images/boxshots/large/sqldoc.gif" alt="alt text" /></a></p> <p><a href="http://www.red-gate.com/products/SQL_Doc/video.htm" rel="nofollow">Demo Video</a></p> <p><H1>Apex SQL Doc</H1></p> <p><a href="http://www.apexsql.com/sql_tools_doc.asp" rel="nofollow"><img src="http://www.apexsql.com/images/apex_doc_icon.jpg" alt="alt text" /></a></p>
How to implement a file download in asp.net <p>What is the best way to implement, from a web page a download action using asp.net 2.0?</p> <p>Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.</p>
<p>Does this help:</p> <p><a href="http://www.west-wind.com/weblog/posts/76293.aspx">http://www.west-wind.com/weblog/posts/76293.aspx</a></p> <pre><code>Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt"); Response.TransmitFile( Server.MapPath("~/logfile.txt") ); Response.End(); </code></pre> <p>Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.</p>
How do I implement a chromeless window with WPF? <p>I want to show a chromeless modal window with a close button in the upper right corner. Is this possible?</p>
<p>You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this:</p> <pre><code>&lt;Window WindowStyle="None"&gt; </code></pre> <p>That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration.</p>
How do you display a dialog from a hidden window application? <p>I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog.</p> <p>The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control.</p> <p>My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing.</p> <p>However, if I make a call to <code>::MessageBox()</code> immediately before <code>DoModal()</code> the dialog displays and behaves correctly after first showing the MessageBox.</p> <p>I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'.</p> <p>I have tried using both NULL and the return value from <code>::GetConsoleWindow()</code> as the dialog's parent, neither have worked.</p> <p>The dialog itself is an ATL/WTL CPropertySheetImpl.</p> <p>The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party.</p> <p>I do know that I can successfully call <code>::MessageBox()</code> or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog.</p> <p>Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface.</p>
<p>Are you using a parent for the Dialog? e.g.</p> <pre><code>MyDialog dialog(pParent); dialog.DoModal(); </code></pre> <p>If you are, try removing the parent. Especially if the parent is the desktop window.</p>
C# string concatenation and string interning <p>When performing string concatentation of an existing string in the intern pool, is a new string entered into the intern pool or is a reference returned to the existing string in the intern pool? According to this article, String.Concat and StringBuilder will insert new string instances into the intern pool? </p> <p><a href="http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx" rel="nofollow">http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx</a></p> <p>Can anyone explain how concatenation works with the intern pool?</p>
<p>If you create new strings, they will not automatically be put into the intern pool, unless you concatenate constants compile-time, in which case the compiler will create one string result and intern that as part of the JIT process.</p>
Best .NET Wrapper for Google Maps or Yahoo Maps? <p>I need to do a quick demo app using Google Maps (or Yahoo Maps, or any similar service). So far I haven't had much luck finding .NET wrappers for any of these services.</p> <p>Any suggestions or pointers?</p> <p>I'm not opposed to using the native javascript api to do this, but I assumed someone would have already written a wrapper to easily integrate this into an ASP.NET application.</p>
<p>I always check <a href="http://www.CodePlex.com" rel="nofollow">CodePlex.com</a></p> <p><a href="http://www.codeplex.com/googlemap" rel="nofollow">http://www.codeplex.com/googlemap</a></p> <p><a href="http://www.codeplex.com/YahooMap" rel="nofollow">http://www.codeplex.com/YahooMap</a></p> <p>The GoogleMaps project above has a lot of good examples on the project leader's website.</p>
How to prevent Write Ahead Logging on just one table in PostgreSQL? <p>I am considering log-shipping of <a href="http://www.postgresql.org/docs/8.2/static/runtime-config-wal.html">Write Ahead Logs (WAL)</a> in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, <strong>is there a way to prevent any activity on one table from being recorded in the WALs?</strong></p>
<p>Ran across this old question, which now has a better answer. Postgres 9.1 introduced "Unlogged Tables", which are tables that don't log their DML changes to WAL. See the docs for more info, but at least now there is a solution for this problem. </p> <p>See <a href="http://www.depesz.com/2011/01/03/waiting-for-9-1-unlogged-tables/" rel="nofollow">Waiting for 9.1 - UNLOGGED tables</a> by depesz, and the <a href="http://www.postgresql.org/docs/9.1/static/sql-createtable.html" rel="nofollow">9.1 docs</a>.</p>
Parallelize Bash Script with maximum number of processes <p>Lets say I have a loop in bash:</p> <pre><code>for foo in `some-command` do do-something $foo done </code></pre> <p><code>do-something</code> is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 <code>do-something</code>'s at once.</p> <p>The naive approach seems to be:</p> <pre><code>for foo in `some-command` do do-something $foo &amp; done </code></pre> <p>This will run <em>all</em> <code>do-something</code>s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing <em>all</em> at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the <code>do-something</code>s are finished.</p> <p>How would you write this loop so there are always X <code>do-something</code>s running at once?</p>
<p>Depending on what you want to do xargs also can help (here: converting documents with pdf2ps):</p> <pre><code>cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w ) find . -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps </code></pre> <p>From the docs:</p> <pre><code>--max-procs=max-procs -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done. </code></pre>
How do I read a disk directly with .Net? <p>Is is possible to read a disk directly with .Net? By directly I mean via the device bypassing the file system. I think I would go about this by opening the device some way "\Device\Ide\IdeDeviceP2T0L0-1" for example. </p> <p>If I can't open the device with a .NET api knowing which Win32 API to use would be helpful. </p>
<p>Cool, thank you Mark, I had forgotten that CreateFile opens things too. I was looking at the volume management API and not seeing how to open things. </p> <p>Here is a little class that wraps things up. It might also be possible/correct to just pass the SafeFileHandle into a FileStream.</p> <pre><code>using System; using System.Runtime.InteropServices; using System.IO; using Microsoft.Win32.SafeHandles; namespace ReadFromDevice { public class DeviceStream : Stream, IDisposable { public const short FILE_ATTRIBUTE_NORMAL = 0x80; public const short INVALID_HANDLE_VALUE = -1; public const uint GENERIC_READ = 0x80000000; public const uint GENERIC_WRITE = 0x40000000; public const uint CREATE_NEW = 1; public const uint CREATE_ALWAYS = 2; public const uint OPEN_EXISTING = 3; // Use interop to call the CreateFile function. // For more information about CreateFile, // see the unmanaged MSDN reference library. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool ReadFile( IntPtr hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToRead, // number of bytes to read ref int lpNumberOfBytesRead, // number of bytes read IntPtr lpOverlapped // // ref OVERLAPPED lpOverlapped // overlapped buffer ); private SafeFileHandle handleValue = null; private FileStream _fs = null; public DeviceStream(string device) { Load(device); } private void Load(string Path) { if (string.IsNullOrEmpty(Path)) { throw new ArgumentNullException("Path"); } // Try to open the file. IntPtr ptr = CreateFile(Path, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); handleValue = new SafeFileHandle(ptr, true); _fs = new FileStream(handleValue, FileAccess.Read); // If the handle is invalid, // get the last Win32 error // and throw a Win32Exception. if (handleValue.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override void Flush() { return; } public override long Length { get { return -1; } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// &lt;summary&gt; /// &lt;/summary&gt; /// &lt;param name="buffer"&gt;An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. &lt;/param&gt; /// &lt;param name="offset"&gt;The zero-based byte offset in buffer at which to begin storing the data read from the current stream. &lt;/param&gt; /// &lt;param name="count"&gt;The maximum number of bytes to be read from the current stream.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public override int Read(byte[] buffer, int offset, int count) { int BytesRead =0; var BufBytes = new byte[count]; if (!ReadFile(handleValue.DangerousGetHandle(), BufBytes, count, ref BytesRead, IntPtr.Zero)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } for (int i = 0; i &lt; BytesRead; i++) { buffer[offset + i] = BufBytes[i]; } return BytesRead; } public override int ReadByte() { int BytesRead = 0; var lpBuffer = new byte[1]; if (!ReadFile( handleValue.DangerousGetHandle(), // handle to file lpBuffer, // data buffer 1, // number of bytes to read ref BytesRead, // number of bytes read IntPtr.Zero )) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); ;} return lpBuffer[0]; } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void Close() { handleValue.Close(); handleValue.Dispose(); handleValue = null; base.Close(); } private bool disposed = false; new void Dispose() { Dispose(true); base.Dispose(); GC.SuppressFinalize(this); } private new void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { if (handleValue != null) { _fs.Dispose(); handleValue.Close(); handleValue.Dispose(); handleValue = null; } } // Note disposing has been done. disposed = true; } } } } </code></pre> <p>And an example of using the class</p> <pre><code>static void Main(string[] args) { var reader = new BinaryReader(new DeviceStream(@"\\.\PhysicalDrive3")); var writer = new BinaryWriter(new FileStream(@"g:\test.dat", FileMode.Create)); var buffer = new byte[MB]; int count; int loopcount=0; try{ while((count=reader.Read(buffer,0,MB))&gt;0) { writer.Write(buffer,0,count); System.Console.Write('.'); if(loopcount%100==0) { System.Console.WriteLine(); System.Console.WriteLine("100MB written"); writer.Flush(); } loopcount++; } } catch(Exception e) { Console.WriteLine(e.Message); } reader.Close(); writer.Flush(); writer.Close(); } </code></pre> <p>Standard disclaimers apply, this code may be hazardous to your health.</p>
What non-programming books should programmers read? <p>This is a <a href="http://stackoverflow.com/questions/tagged/polls">poll</a> asking the Stackoverflow community what <strong>non-programming</strong> books they would recommend to fellow programmers.</p> <h3>Please read the following before posting:</h3> <ul> <li><p>Please post only <em>ONE BOOK PER ANSWER</em>.</p></li> <li><p>Please <em>search for your recommendation on this page before posting</em> (there are over NINE PAGES so it is advisable to check them all). Many books have already been suggested and we want to avoid duplicates. If you find your recommendation is already present, vote it up or add some commentary.</p></li> <li><p><strong>Please elaborate</strong> <em>on <strong>why</strong> you think a given book is worth reading</em> <strong><em>from a programmer's perspective.</em></strong></p></li> </ul> <p>Note: <a href="http://stackoverflow.com/questions/31274/best-non-development-book-for-software-developers">this article</a> is similar and contains other useful suggestions.</p>
<h2><a href="http://rads.stackoverflow.com/amzn/click/0345453743" rel="nofollow">The Hitchhiker's Guide to the Galaxy</a></h2> <p>by Douglas Adams</p> <p><img src="http://upload.wikimedia.org/wikipedia/en/1/1c/Hitchhiker%27s_Guide_%28book_cover%29.jpg" alt="alt text"></p> <p>Life, the universe, and everything</p> <p>"See first, think later, then test. But always see first. Otherwise you will only see what you were expecting. Most scientists forget that." -- Wonko the Sane</p>
Best browser for web application <p>I am in a position where I can choose the client browser for my web app. The app is being used internally, and we are installing each client "manually".I would like to find a better solution for the browser,so :</p> <p>What is a good browser that I can use as a client to a web application?</p> <p>General functionalities I would like to have:</p> <ul> <li>opening the browser from a shortcut, directly to the application's URL </li> <li>ability to restrict navigation to a set of allowed URLs </li> <li>fullscreen mode, no menu, no address bar</li> <li>javascript </li> <li>good CSS support</li> <li>ability to cancel Back button (or at least solve the "Webpage has expired" IE problem)</li> </ul> <p>IE7 and FireFox are good candidates, but each seem to have it's own problems and issues.</p>
<p><a href="http://developer.mozilla.org/en/Prism" rel="nofollow">Mozilla Prism</a> seems ideal for your purposes.</p> <p>It shares code with Firefox but is designed to run web applications without the usual Browser interface to make them appear more like desktop applications. So no back button or address bar to worry about.</p> <p><strong>Edit:</strong> <a href="http://www.google.com/chrome" rel="nofollow">Google Chrome</a> has <a href="http://www.google.com/support/chrome/bin/answer.py?answer=95710&amp;hl=en_GB" rel="nofollow">Application Shortcuts</a> so that may now be a better option.</p>
PHP : session variable aren't usable when site is redirected <p>I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;www.mysmallwebsite.com&lt;/title&gt; &lt;/head&gt; &lt;frameset&gt; &lt;frame src="http://www.myIsv.com/myWebSite/" name="redir"&gt; &lt;noframes&gt; &lt;p&gt;Original location: &lt;a href="www.myIsv.com/myWebSite/"&gt;http://www.myIsv.com/myWebSite/&lt;/a&gt; &lt;/p&gt; &lt;/noframes&gt; &lt;/frameset&gt; &lt;/html&gt; </code></pre> <p>It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?</p> <p>Edit: This doesn't work both on IE and on Firefox (no plugins)</p> <p>Thanks</p>
<p>Sessions are tied to the server <strong>AND</strong> the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do. </p> <p>Try using apache mod rewrite to create a "passthrough redirection", the "<strong>proxy</strong>" flag ([P]) in the rule is the magic flag that you need</p> <p>Documentation at <a href="http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html" rel="nofollow">http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html</a></p>
C# WinForms - DataGridView/SQL Compact - Negative integer in primary key column <p>I'm just getting dirty in WinForms, and I've discovered, through a lovely tutorial, the magic of dragging a database table onto the design view of my main form. So, all is lovely, I've got my DataGridView with all of the columns represented beautifully.</p> <p>BUT...</p> <p>When I run my application against this brand new, empty .sdf (empty save for the two tables I've created, which are themselves empty), I get a -1 in the column corresponding to my primary key/identity column whenever I try to create that first record.</p> <p>Any idea why this might be happening? If it helps, the column is an <code>int</code>.</p>
<p>@Brian -1 is a good choice for the default value since no "real" rows are likely to have identities less than zero. If it defaulted to 0 or 1 then there'd be a chance that it'd clash with an existing row, causing a primary key violation.</p> <p>For applications that stay offline and create multiple rows before saving, a common practice is to continue counting backwards (-2, -3, -4) for each new row's identity. Then when they're saved, the server can replace them with the true "next" value from the table.</p>
ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008 <p>Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. </p> <p>I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.</p> <p>After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. </p> <p>In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. </p> <p>I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. </p> <p>Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.</p> <p>I doubt anyone has run into this, but have you? </p> <p>Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. </p> <p>Thank you. </p> <p><hr /></p> <p><strong>Jon Limjap:</strong> I edited the title to both make it clear and descriptive <em>and</em> make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.</p>
<p>The above fix (deleting the temp files) did not work for me. I had to delete the <code>PageName.aspx.designer.cs</code> file, then right-click my page, and choose "Convert to Web Application" from the context menu. </p> <p>When Visual Studio attempted to rebuild the designer file, it encountered (and revealed to me) the source of the problem. In my case, VS had lost a reference to a DLL needed by one of the controls on my page, so I had to clean out the generated bin folders in my project.</p>
How to provide next page of updated content? <p>Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example.</p> <p>You get a screenful of stackoverflow questions by requesting <code>/questions ?sort=newest</code> page. Next page link leads to <code>/questions?page=2 &amp;sort=newest</code>. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!)</p> <p>Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still.</p> <p>The best idea I have (apart from storing request history per client) is to use <code>/questions?answer_id=NNN</code> format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? </p> <p>Is it how it usually done? Or there is a better way?</p>
<p>This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upvoted post could have been moved to page 1 or 2.</p> <p>Only way to do it is to load the complete list in someones session. Please don't...</p> <p>As already mentioned, let's hope people are used to this by now.</p>
Which class design is better? <p>Which class design is better and why?</p> <pre><code>public class User { public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee : User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member : User { public String MemberId; public String JoinDate; public String ExpiryDate; } </code></pre> <p>OR</p> <pre><code>public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; } public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; } public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; } </code></pre>
<p>The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship.</p> <ul> <li>An employee IS A user</li> <li>An employee HAS A userinfo</li> </ul> <p>Which one is correct? This is your answer.</p>
One or Two Primary Keys in Many-to-Many Table? <p>I have the following tables in my database that have a many-to-many relationship, which is expressed by a connecting table that has foreign keys to the primary keys of each of the main tables:</p> <ul> <li>Widget: WidgetID (PK), Title, Price </li> <li>User: UserID (PK), FirstName, LastName</li> </ul> <p>Assume that each User-Widget combination is unique. I can see two options for how to structure the connecting table that defines the data relationship:</p> <ol> <li>UserWidgets1: UserWidgetID (PK), WidgetID (FK), UserID (FK) </li> <li>UserWidgets2: WidgetID (PK, FK), UserID (PK, FK)</li> </ol> <p>Option 1 has a single column for the Primary Key. However, this seems unnecessary since the only data being stored in the table is the relationship between the two primary tables, and this relationship itself can form a unique key. Thus leading to option 2, which has a two-column primary key, but loses the one-column unique identifier that option 1 has. I could also optionally add a two-column unique index (WidgetID, UserID) to the first table.</p> <p>Is there any real difference between the two performance-wise, or any reason to prefer one approach over the other for structuring the UserWidgets many-to-many table?</p>
<p>You only have one primary key in either case. The second one is what's called a compound key. There's no good reason for introducing a new column. In practise, you will have to keep a unique index on all candidate keys. Adding a new column buys you nothing but maintenance overhead.</p> <p>Go with option 2.</p>
Enforce constraint checking only when inserting rows in MSSQL? <p>Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?</p> <p>Update: I mean FK constraint.</p>
<p>You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through.</p> <pre><code>CREATE TRIGGER employee_insupd ON employee FOR INSERT AS /* Get the range of level for this job type from the jobs table. */ DECLARE @min_lvl tinyint, @max_lvl tinyint, @emp_lvl tinyint, @job_id smallint SELECT @min_lvl = min_lvl, @max_lvl = max_lvl, @emp_lvl = i.job_lvl, @job_id = i.job_id FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id JOIN jobs j ON j.job_id = i.job_id IF (@job_id = 1) and (@emp_lvl &lt;&gt; 10) BEGIN RAISERROR ('Job id 1 expects the default level of 10.', 16, 1) ROLLBACK TRANSACTION END ELSE IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl) BEGIN RAISERROR ('The level for job_id:%d should be between %d and %d.', 16, 1, @job_id, @min_lvl, @max_lvl) ROLLBACK TRANSACTION END </code></pre>
php mail() not working windows 2003, IIS SMTP <p>I'm getting this problem:</p> <pre><code>PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for [email protected] in c:\inetpub\wwwroot\mailtest.php on line 12 </code></pre> <p>from this script:</p> <pre><code>&lt;?php $to = "[email protected]"; $subject = "test"; $body = "this is a test"; if (mail($to, $subject, $body)){ echo "mail sent"; } else { echo "problem"; } ?&gt; </code></pre> <p>section from php.ini on the server:</p> <pre><code>[mail function] ; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25 ; For Win32 only. sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ;sendmail_path = </code></pre> <p>(note that "server" and "domain" refer accurately to the actual server and domain name)</p> <p>In IIS, SMTP is running. Under <code>"Access"</code> tab, <code>"Relay"</code> button, the Select which computers may relay through this virtual server is set to <code>checkbox "only the list below"</code> and on the list is <code>"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).</code></p> <p>Server is running <code>Windows Server 2003 Service Pack 2</code>, fully patched as of 5 PM Sept 1st 2008. I assume it is running <code>IIS7</code> (how to check?).</p> <p>Any ideas?</p> <p>In reponse to <a href="http://stackoverflow.com/users/2257/espo">Espo</a>: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.</p> <p>Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.</p> <p>Thanks to both Espo and Yaakov for helping me out.</p>
<p>Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed.</p>
Generate field in MySQL SELECT <p>If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:</p> <pre><code>SELECT Field1, Field2 FROM Table </code></pre> <p>And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:</p> <pre><code>SELECT Field1, Field2, Field3 = 'Value' FROM Table </code></pre> <p>Is this possible at all?</p>
<pre><code>SELECT Field1, Field2, 'Value' Field3 FROM Table </code></pre> <p>or for clarity</p> <pre><code>SELECT Field1, Field2, 'Value' AS Field3 FROM Table </code></pre>
How to find out if a file exists in C# / .NET? <p>I would like to test a string containing a path to a file for existence of that file (something like the <code>-e</code> test in Perl or the <code>os.path.exists()</code> in Python) in C#.</p>
<p>Use:</p> <pre><code>File.Exists(path) </code></pre> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx">http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx</a></p> <p>Edit: In System.IO</p>
Programmable, secure FTP replacement <p>We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. </p> <p>Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?</p>
<p><a href="http://www.codeproject.com/KB/IP/sharpssh.aspx" rel="nofollow">sharpssh</a> implements sending files via scp.</p>
"Similar Posts" like functionality using MS SQL Server? <p>I have lots of article store in MS SQL server 2005 database in a table called Articles-</p> <pre><code>"Articles (ArticleID, ArticleTitle, ArticleContent)" </code></pre> <p>Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.</p> <p>Is it possible to do this in MS SQL Server 2005?</p>
<p>Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search.</p> <pre><code>Select Top 10 ArticleID, ArticleTitle, ArticleContent From Articles Order By (Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc, (Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleTitle) &gt; 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleTitle) &gt; 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleTitle) &gt; 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleContent) &gt; 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleContent) &gt; 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleContent) &gt; 0 Then 1 Else 0 End) Desc </code></pre> <p>You can then add/remove case statements from the order by clause to improve the list based on your data.</p>
What do you call the tags in Subversion and CVS that add automatic content? <p>Things like <code>$log$</code> and <code>$version$</code> which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.</p>
<p>Both Subversion and CVS call them <code>Keywords</code>.</p> <p><a href="http://svnbook.red-bean.com/en/1.0/ch07s02.html#svn-ch-7-sect-2.3" rel="nofollow">Have a look in the SVN manual here</a> (scroll down to <strong>svn:keywords</strong>) or <a href="http://badgertronics.com/writings/cvs/keywords.html" rel="nofollow">here for CVS</a>.</p>
How do I check job status from SSIS control flow? <p>Here's my scenario - I have an SSIS job that depends on another prior SSIS job to run. I need to be able to check the first job's status before I kick off the second one. It's not feasible to add the 2nd job into the workflow of the first one, as it is already way too complex. I want to be able to check the first job's status (Failed, Successful, Currently Executing) from the second one's, and use this as a condition to decide whether the second one should run, or wait for a retry. I know this can be done by querying the MSDB database on the SQL Server running the job. I'm wondering of there is an easier way, such as possibly using the WMI Data Reader Task? Anyone had this experience?</p>
<p>You may want to create a third package the runs packageA and then packageB. The third package would only contain two execute package tasks.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms137609.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms137609.aspx</a></p> <p>@Craig A status table is an option but you will have to keep monitoring it.</p> <p>Here is an article about events in SSIS for you original question.<br /> <a href="http://www.databasejournal.com/features/mssql/article.php/3558006" rel="nofollow">http://www.databasejournal.com/features/mssql/article.php/3558006</a></p>
How to use the SharePoint MultipleLookupField control? <p>I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.</p>
<p>I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!</p> <p>Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.</p> <p>Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.</p> <p>Now create a web part, do all the usual boilerplate and then add this:</p> <pre><code>Label l; MultipleLookupField mlf; protected override void CreateChildControls() { base.CreateChildControls(); SPList list = SPContext.Current.Web.Lists["Shared Documents"]; if (list != null &amp;&amp; list.Items.Count &gt; 0) { LiteralControl lit = new LiteralControl("Associate tasks to " + list.Items[0].Name); this.Controls.Add(lit); mlf = new MultipleLookupField(); mlf.ControlMode = SPControlMode.Edit; mlf.FieldName = "Related"; mlf.ItemId = list.Items[0].ID; mlf.ListId = list.ID; mlf.ID = "Related"; this.Controls.Add(mlf); Button b = new Button(); b.Text = "Change"; b.Click += new EventHandler(bClick); this.Controls.Add(b); l = new Label(); this.Controls.Add(l); } } void bClick(object sender, EventArgs e) { l.Text = ""; foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value) { l.Text += val.LookupValue.ToString() + " "; } SPListItem listitem = mlf.List.Items[0]; listitem["Related"] = mlf.Value; listitem.Update(); mlf.Value = listitem["Related"]; } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); } </code></pre> <p>Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.</p> <p>The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...</p>
javascript locals()? <p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
<ul> <li><p>locals() - No. </p></li> <li><p>globals() - Yes.</p></li> </ul> <p><code>window</code> is a reference to the global scope, like <code>globals()</code> in python.</p> <pre><code>globals()["foo"] </code></pre> <p>is the same as:</p> <pre><code>window["foo"] </code></pre>
Is overloading the only way to have default function arguments in C#? <p>Is it true that the only way to handle default function arguments is through function overloading?</p> <p>For example, in PHP I can do this:</p> <pre><code>function foo($x, $y=0) { } </code></pre> <p>Would the best way to handle it in C# be this?</p> <pre><code>void foo(int x) { foo(x, 0); } void foo(int x, int y) { } </code></pre> <p><strong><em><a href="http://bytes.com/forum/thread224970.html" rel="nofollow">Example lifted from here</a></em></strong></p> <p>Edit</p> <p><strong><em>Made the C# example into actual C# (Thanks Blair Conrad)</em></strong></p>
<p>Just to satisfy some curiosity:</p> <p>From <a href="http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx">Why doesn't C# support default parameters?</a>:</p> <blockquote> <p>In languages such as C++, a default value can be included as part of the method declaration:</p> <p>void Process(Employee employee, bool bonus = false)</p> <p>This method can be called either with:</p> <p>a.Process(employee, true);</p> <p>or</p> <p>a.Process(employee);</p> <p>in the second case, the parameter bonus is set to false.</p> <p>C# doesn't have this feature.</p> <p>One reason we don't have this feature is related to a specific implementation of the feature. In the C++ world, when the user writes:</p> <p>a.Process(employee);</p> <p>the compiler generates</p> <p>a.process(employee, false);</p> <p>In other words, the compiler takes the default value that is specified in the method prototype and puts it into the method call - it's just as if the user wrote 'false' as the second parameter. There's no way to change that default value without forcing the user of the class to recompile, which is unfortunate.</p> <p>The overloading model works better in this respect. The framework author just defines two separate methods, and the single-parameter one calls the two-parameter method. This keeps the default value in the framework, where it can be modified if necessary.</p> <p>It would be possible for a compiler to take something like the C++ definition and produce the overloads, but there are a few issues with that approach.</p> <p>The first one is that the correlation between the code that the user writes and the code the compiler generates is less obvious. We generally try to limit magic when possible, as it makes it harder for programmers. The second issue has to do with things like XML doc comments and intellisense. The compiler would have to have special rules for how it generates doc comments for the overloaded methods, and intellisense would need to have smarts to collapse the overloaded methods into a single method.</p> <p>Writing overloads yourself is a bit less convenient, but we think it's an acceptable solution. </p> </blockquote>
GUIDs as Primary Keys - Offline OLTP <p>We are working on designing an application that is typically OLTP (think: purchasing system). However, this one in particular has the need that some users will be offline, so they need to be able to download the DB to their machine, work on it, and then sync back once they're on the LAN.</p> <p>I would like to note that I know this has been done before, I just don't have experience with this particular model.</p> <p>One idea I thought about was using GUIDs as table keys. So for example, a Purchase Order would not have a number (auto-numeric) but a GUID instead, so that every offline client can generate those, and I don't have clashes when I connect back to the DB.</p> <p>Is this a bad idea for some reason? Will access to these tables through the GUID key be slow?</p> <p>Have you had experience with these type of systems? How have you solved this problem?</p> <p>Thanks!<br /> Daniel</p>
<p>Using Guids as primary keys is acceptable and is considered a fairly standard practice for the same reasons that you are considering them. They can be overused which can make things a bit tedious to debug and manage, so try to keep them out of code tables and other reference data if at all possible.</p> <p>The thing that you have to concern yourself with is the human readable identifier. Guids cannot be exchanged by people - can you imagine trying to confirm your order number over the phone if it is a guid? So in an offline scenario you may still have to generate <strong>something</strong> - like a publisher (workstation/user) id and some sequence number, so the order number may be 123-5678 -. </p> <p>However this may not satisfy business requirements of having a sequential number. In fact regulatory requirements can be and influence - some regulations (SOX maybe) require that invoice numbers are sequential. In such cases it may be neccessary to generate a sort of proforma number which is fixed up later when the systems synchronise. You may land up with tables having OrderId (Guid), OrderNo (int), ProformaOrderNo (varchar) - some complexity may creep in.</p> <p>At least having guids as primary keys means that you don't have to do a whole lot of cascading updates when the sync does eventually happen - you simply update the human readable number.</p>
Is Java "pass-by-reference" or "pass-by-value"? <p>I always thought Java was <strong>pass-by-reference</strong>; however I've seen a couple of blog posts (for example, <a href="http://javadude.com/articles/passbyvalue.htm">this blog</a>) that claim it's not. I don't think I understand the distinction they're making. </p> <p>What is the explanation?</p>
<p>Java is always <strong>pass-by-value</strong>. Unfortunately, they decided to call pointers references, thus confusing newbies. Because those <em>references</em> are passed by value.</p> <p>It goes like this:</p> <pre><code>public static void main( String[] args ){ Dog aDog = new Dog("Max"); foo(aDog); if (aDog.getName().equals("Max")) { //true System.out.println( "Java passes by value." ); } else if (aDog.getName().equals("Fifi")) { System.out.println( "Java passes by reference." ); } } public static void foo(Dog d) { d.getName().equals("Max"); // true d = new Dog("Fifi"); d.getName().equals("Fifi"); // true } </code></pre> <p>In this <a href="http://ideone.com/oUEPbg">example</a> <code>aDog.getName()</code> will still return <code>"Max"</code>. The value <code>aDog</code> within <code>main</code> is not overwritten in the function <code>foo</code> with the <code>Dog</code> <code>"Fifi"</code> as the object reference is passed by value. If it were passed by reference, then the <code>aDog.getName()</code> in <code>main</code> would return <code>"Fifi"</code> after the call to <code>foo</code>.</p> <p>Likewise:</p> <pre><code>Dog aDog = new Dog("Max"); foo(aDog); aDog.getName().equals("Fifi"); // true public void foo(Dog d) { d.getName().equals("Max"); // true d.setName("Fifi"); } </code></pre> <p>In the above example, <code>FiFi</code> is the dog's name after call to <code>foo(aDog)</code>. Any operations that <code>foo</code> performs on <code>d</code> are such that, for all practical purposes, they are performed on <code>aDog</code> itself (except <code>d=new Dog("Boxer")</code>).</p>
jQuery and Prototype Selector Madness <p>Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. </p> <p>For example, in Prototype this works:</p> <pre><code>$$('li')[5].addClassName('active'); </code></pre> <p>But this will not work no matter how I try to cast the variable as a number or integer:</p> <pre><code>$$('li')[currentPage].addClassName('active'); </code></pre> <p>In jQuery I get similar weirdness. This will work:</p> <pre><code>jQuery('li').eq(5).addClass("active"); </code></pre> <p>But this will not work again even though the value of currentPage is 5 and its type is number:</p> <pre><code>jQuery('li').eq(currentPage).addClass("active"); </code></pre> <p>I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.</p>
<p>Are you certain that <code>currentPage</code> is an integer? Try something like:</p> <pre><code>var currentPage = 5; jQuery('li').eq(currentPage); </code></pre> <p>as a simple sanity check. If that works, you should try casting to <code>Integer</code>.</p>
How do I get the full url of the page I am on in C# <p>I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?</p>
<p>Here is a list I normally refer to for this type of information:</p> <pre><code>Request.ApplicationPath : /virtual_dir Request.CurrentExecutionFilePath : /virtual_dir/webapp/page.aspx Request.FilePath : /virtual_dir/webapp/page.aspx Request.Path : /virtual_dir/webapp/page.aspx Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\virtual_dir\ Request.QueryString : /virtual_dir/webapp/page.aspx?q=qvalue Request.Url.AbsolutePath : /virtual_dir/webapp/page.aspx Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue Request.Url.Host : localhost Request.Url.Authority : localhost:80 Request.Url.LocalPath : /virtual_dir/webapp/page.aspx Request.Url.PathAndQuery : /virtual_dir/webapp/page.aspx?q=qvalue Request.Url.Port : 80 Request.Url.Query : ?q=qvalue Request.Url.Scheme : http Request.Url.Segments : / virtual_dir/ webapp/ page.aspx </code></pre> <p>Hopefully you will find this useful!</p>
How do you give a C# Auto-Property a default value? <p>How do you give a C# Auto-Property a default value? I either use the constructor, or revert to the old syntax. </p> <p><strong> Using the Constructor:</strong></p> <pre><code>class Person { public Person() { Name = "Default Name"; } public string Name { get; set; } } </code></pre> <p><strong>Using normal property syntax</strong> (with a default value)</p> <pre><code>private string name = "Default Name"; public string Name { get { return name; } set { name = value; } } </code></pre> <p>Is there a better way?</p>
<p>In C# 5 and earlier, to give auto implemented properties a default value, you have to do it in a constructor.</p> <p>The ability to have auto property initializers is included since C# 6.0. The syntax is:</p> <pre><code>public int X { get; set; } = x; // C# 6 or higher </code></pre>
Cannot create an environment variable in the registry <p>I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is:</p> <pre><code> using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } </code></pre> <p>Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.</p>
<p>What OS is this? Is it on a 64-bit system? What is the nature of the failure: silent or is an exception thrown?</p> <p>You could try running <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">ProcessMonitor</a> and seeing if it sees the attempt to set the value.</p>
Smarty integration into the Code Igniter framework <p><strong>A Little Background Information</strong>:<br> I've been looking at a few PHP framework recently, and it came down to two. The Zend Framework or CodeIgniter. </p> <p>I prefer CodeIgniter, because of its simple design. It's very bare bone, and it is just kept simple. The thing I don't like though is the weak template system. The template system is important for me, because I will be working with another designer. Being able to give him a good template system is a big plus.</p> <p>Zend was the second choice, because of the better template system that is built in. Zend is a different beast though compared to CodeIgniter. It emphasis "loose coupling between modules", but is a bigger framework. I don't like to feel like I have many things running under the hood that I never use. That is unnecessary overhead in my opinion, so I thought about putting a template system into CodeIgniter: Smarty.</p> <p><strong>Question(s)</strong>: How easy/hard is the process to integrate Smarty into CodeIgniter? From my initial scan of the CodeIgniter documentation, I can see that the layout of the framework is easy enough to understand, and I anticipate no problems. I want to know if anyone has used it before, and therefore are aware of any "gotchas" you my have experienced that is going to make this harder than it should be or impossible to pull off. I also want to know if this is a good thing to do at all. Is the template system in CodeIgniter enough for normal use? Are there any other template modules that are good for CodeIgniter aside from Smarty? I better off with Zend Framework? Is any wheel being invented here? Thank you for your help! </p>
<p>Sorry to resurrect an old question - but none of the answers have been flagged as "accepted" yet.</p> <p>There's a library called "template" that does a great job of allowing you to use just about any template parser you want:</p> <p><a href="http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html#parsers" rel="nofollow">Template CI Library - Parsers</a></p> <p>The syntax is pretty easy for integrating into your CI application and the smarty integration spot on.</p>
Where do you store your database connectionstring? <p>I usually store my connectionstring in web.config or in the application settings of my Visual Studio project. The application I'm currently working on makes a lot of trips to the database which means it will look up the connectionstring every time. Should I be putting the connectionstring in the cache or should I be looking at storing the whole SqlConnection object in the cache to eliminate the need to open and close them all the time?</p> <p><strong>Update</strong>: Seems like the consensus is to store the connection string in a configuration file and leave the caching in the trusting hand of ADO.NET</p>
<p>I wouldn't cache the connection object, that will defeat the built-in connection pooling -- ADO.NET will handle connections (assuming you instantiate and close them) efficiently by itself.</p> <p>As far as the connection string itself, you shouldn't need to cache it if you load it from connection -- the connection manager object in the .NET 2.0 framework loads the config into memory when you first access it, so there are no repeat trips to the file system.</p>
Is there a best .NET algorithm for credit card encryption? <p>The .NET <code>System.Security.Cryptography</code> namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best?</p> <p>It clearly needs to be secure for a relatively short string. </p> <p>EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.</p>
<p>No offense, but the question is a little "misguided". There is no "silver bullet" solution. I would recommend to read up on cryptography in general and then do some threat modeling. Some questions (by no means a comprehensive list) you should ask yourself:</p> <ul> <li>Is the module doing the encryption the one which needs to decrypt it (in this case use symmetric crypto) or will it send data to an other module (on an other machine) which will use it (in which case you should consider public-key crypto)</li> <li>What do you want to protect against? Someone accessing the database but not having the sourcecode (in which case you can hardcode the encryption key directly into the source)? Someone sniffing your local network (you should consider transparent solutions like IPSec)? Someone stealing your server (it can happen even in data centers - in which case full disk encryption should be considered)?</li> <li>Do you really need to keep the data? Can't you directly pass it to the credit card processor and erase it after you get the confirmation? Can't you store it locally at the client in a cookie or Flash LSO? If you store it at the client, make sure that you encrypt it at the server side before putting it in a cookie. Also, if you are using cookies, make sure that you make them http only.</li> <li>Is it enough to compare the equality of the data (ie the data that the client has given me is the same data that I have)? If so, consider storing a hash of it. Because credit card numbers are relatively short and use a reduced set of symbols, a unique salt should be generated for each before hashing.</li> </ul> <p><em>Later edit</em>: note that standard encryption algorithms from the same category (for example 3DES and AES - both being symmetric block cyphers) are of comparable strength. Most (commercial) systems are not broken because somebody bruteforced their encryption, but because their threat modelling was not detailed enough (or flat out they didn't have any). For example you can encrypt all the data, but if you happen to have a public facing web interface which is vulnerable to SQL injection, it won't help you much.</p>
File Access Strategy in a Multi-Threaded Environment (Web App) <p>I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is <em>very</em> static, but just <em>might</em> change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.</p> <p>I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.</p> <p>This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?</p> <p>Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)</p> <ul> <li><strong>Am I missing something?</strong></li> <li><strong>What is the best file access strategy in a multi-threaded environment?</strong> <hr /></li> </ul> <h3>Edit</h3> <p>Sorry - I should have said this is using <strong>ASP.NET 2.0</strong> :)</p>
<p>Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time:</p> <pre><code> /// &lt;summary&gt; /// Blocks until the file is not locked any more. /// &lt;/summary&gt; /// &lt;param name="fullPath"&gt;&lt;/param&gt; bool WaitForFile(string fullPath) { int numTries = 0; while (true) { ++numTries; try { // Attempt to open the file exclusively. using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)) { fs.ReadByte(); // If we got this far the file is ready break; } } catch (Exception ex) { Log.LogWarning( "WaitForFile {0} failed to get an exclusive lock: {1}", fullPath, ex.ToString()); if (numTries &gt; 10) { Log.LogWarning( "WaitForFile {0} giving up after 10 tries", fullPath); return false; } // Wait for the lock to be released System.Threading.Thread.Sleep(500); } } Log.LogTrace("WaitForFile {0} returning true after {1} tries", fullPath, numTries); return true; } </code></pre> <p>Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.</p>
Emacs in Windows <p>How do you run Emacs in Windows?</p> <p>What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?</p>
<p>I use <a href="http://www.emacswiki.org/emacs/EmacsW32">EmacsW32</a>, it works great. <em>EDIT: I now use regular GNU Emacs 24, see below.</em></p> <p>See its <a href="http://www.emacswiki.org/cgi-bin/wiki/EmacsW32">EmacsWiki page</a> for details.</p> <p>To me, the biggest advantage is that:</p> <ul> <li>it has a version of emacsclient that starts the Emacs server if no server is running (open all your files in the same Emacs window)</li> <li>it includes several useful packages such as Nxml</li> <li>it has a Windows installer or you can build it from sources</li> </ul> <p>And concerning XEmacs, according to <a href="http://steve-yegge.blogspot.com/2008/04/xemacs-is-dead-long-live-xemacs.html">this post</a> by Steve Yegge:</p> <blockquote> <p>To summarize, I've argued that XEmacs has a much lower market share, poorer performance, more bugs, much lower stability, and at this point probably fewer features than GNU Emacs. When you add it all up, it's the weaker candidate by a large margin.</p> </blockquote> <p><em>EDIT: I now use regular GNU Emacs 24. It also contains Nxml, can be installed or built from sources, and with <a href="http://www.emacswiki.org/emacs/EmacsClient#toc2">this wrapper</a>, the Emacs server starts if no server is running. Cheers!</em></p>
Working on a Visual Studio Project with multiple users? <p>I just wonder what the best approach is to have multiple users work on a Project in Visual Studio 2005 Professional.</p> <p>We got a Solution with multiple Class Libraries, but when everyone opens the solution, we keep getting the "X was modified, Reload/Discard?" prompt all the time. Just opening one project is an obvious alternative, but I find it harder to use as you can't just see some of the other classes in other projects that way.</p> <p>Are there any Guidelines for Team Development with VS2005 Pro?</p> <p>Edit: Thanks. The current environment is a bit limited in the sense there is only 1 PC with RDP Connection, but that will change in the future. Marking the first answer as Accepted, but they are all good :)</p>
<p>What you need is source control.</p> <p>You should definitely not open the same files over the network on multiple machines. For one thing, Visual Studio has safeguards in place to prevent you from modifying certain files during a build, but it has none of that that will prevent others from modifying the same files over the network.</p> <p>By setting up source control, each developer will have a separate copy of the files locally on his or her developer machine, and periodically communicate with the source control system to check in/commit changes. After that, other developers can ask for the latest updates when they're ready to retrieve them.</p>
How to detect the presence of a default recording device in the system? <p>How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p> <p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
<p>Using the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ea4894b5-e98d-44f6-842d-e32147237638&amp;DisplayLang=en" rel="nofollow">DirectX SDK</a>, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device".</p> <p>If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs:</p> <pre><code>#include &lt;tchar.h&gt; #include &lt;windows.h&gt; #include "mmsystem.h" int _tmain( int argc, wchar_t *argv[] ) { UINT deviceCount = waveInGetNumDevs(); if ( deviceCount &gt; 0 ) { for ( int i = 0; i &lt; deviceCount; i++ ) { WAVEINCAPSW waveInCaps; waveInGetDevCapsW( i, &amp;waveInCaps, sizeof( WAVEINCAPS ) ); // do some stuff with waveInCaps... } } return 0; } </code></pre>
How to wrap a function with variable length arguments? <p>I am looking to do this in C/C++.</p> <p>I came across <a href="http://www.swig.org/Doc1.3/Varargs.html"><strong>Variable Length Arguments</strong></a> but this suggests a solution with Python &amp; C using <a href="http://sourceware.org/libffi/">libffi</a>.</p> <p>Now, if I want to wrap <code>printf</code> function with <code>myprintf</code></p> <p>What I do is like below:</p> <pre><code>void myprintf(char* fmt, ...) { va_list args; va_start(args,fmt); printf(fmt,args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b); return 0; } </code></pre> <p>But the results are not as expected!</p> <pre><code>This is a number: 1244780 and this is a character: h and another number: 29953463 </code></pre> <p>Any point where did I miss??</p>
<p>the problem is that you cannot use 'printf' with va_args. You must use <strong>vprintf</strong> if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)</p> <p>You sample works as follows:</p> <pre><code>void myprintf(char* fmt, ...) { va_list args; va_start(args,fmt); vprintf(fmt,args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b); return 0; } </code></pre>
What are the differences between GPL v2 and GPL v3 licenses? <p>In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.</p>
<p>The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences:</p> <ul> <li><p>internationalization: they used new terminology, rather than using language tied to US legal concepts</p></li> <li><p>patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer)</p></li> <li><p>“Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software</p></li> <li><p>DRM: they address digital rights management (which they call digital restrictions management)</p></li> <li><p>compatibility: they addressed compatibility with some other open source licenses</p></li> <li><p>termination: they addressed specifically what happens if the license is violated and the cure of violations</p></li> </ul> <p>I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. Although GPLv3 is a complex legal document, it was designed to be read and reasonable understood by software developers. There is also a guide to understanding it and in depth discussion of the changes from v2 to v3 at <a href="http://copyleft.org/guide/">http://copyleft.org/guide/</a>.</p>
Should I Keep Registering A Failure? <p>I'm working on an automated regression test suite for an app which I maintain. While developing the automated regression test, I ran across some behavior that's almost certainly a bug. So, for now, I've modified the automated regression test to not register a failure--it's deliberately allowing this bad behavior to go by, I mean. </p> <p>So, I am interested in the opinions of others on this site. Obviously, I'll add a bug to our defect tracking to make sure this error behavior gets fixed. But are there any compelling reasons (either way) to either change the regression test to constantly indicate failure or leave the regression test broken and not have a failure until we can get to fixing the defective behavior? I think of this as a 6 of one and a half-dozen of the other type of question but I ask here because I thought others may see it differently.</p> <hr> <p>@Paul Tomblin,</p> <p>Just to be clear--I've never considered removing the test; I was simply considering modifying the pass/fail condition to allow for the failure without it being thrown up in my face every time I run the test. </p> <p>I'm a little concerned about repeated failures from known causes eventually getting treated like warnings in C++. I know developers who see warnings in their C++ code and simply ignore them because they think they're just useless noise. I'm afraid leaving a known failure in the regression suite might cause people to start ignoring other, possibly more important, failures. </p> <p>BTW, lest I be misunderstood, I consider warnings in C++ to be an important aid in crafting strong code but judging from other C++ developers I've met I think I'm in the minority.</p>
<p>If you stop testing it, how are you going to know when it's fixed, and more importantly, how are you going to know if it gets broken again? I'm against taking out the test, because you're likely to forget to add it back in again.</p>
How do you properly use namespaces in C++? <p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p> <p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>
<p>Namespaces are packages essentially. They can be used like this:</p> <pre><code>namespace MyNamespace { class MyClass { }; } </code></pre> <p>Then in code:</p> <pre><code>MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); </code></pre> <p>Hope that helps.</p> <p>Or, if you want to always use a specific namespace, you can do this:</p> <pre><code>using namespace MyNamespace; MyClass* pClass = new MyClass(); </code></pre> <p><strong>Edit:</strong> Following what <a href="http://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624">bernhardrusch</a> has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).</p> <p>And as you asked <a href="http://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615">below</a>, you can use as many namespaces as you like.</p>
is it possible to concat arguments to a command line using backquotes ? <p>I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.</p> <p>I know that's possible by using keyword <em>system</em> like that :</p> <pre><code>#!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory </code></pre> <p>but is that possible by using the "backquotes or backticks syntax" ? (I mean by using that syntax : <code>ls</code>)</p>
<p>No, that will just concatenate the output from <code>ls</code> and the contents of <code>directory</code>.</p> <p>But you can do this:</p> <pre><code>#!/usr/bin/env ruby directory = '/home/paulgreg/' `ls #{directory}` </code></pre>
Mute Specific Application in Vista <p>I am in need of a way to mute a specific application in Vista.</p> <p>Example: Mute just Firefox, but not all of the other application. Much similar to muting a specific program from within the volume mixer in vista. </p> <p>If there is a program that will do this, i would appreciate that. Otherwise if there is a way to do this, I will write a small app(Preferrably something .net).</p> <p>EDIT: I want to automate this procedure, possibly key-map it.</p>
<p>I suggest using the built in Mixer in Vista...</p> <p>Why do you want to use an 3rd party program?</p>
Lightweight fuzzy search library <p>Can you suggest some light weight fuzzy text search library?</p> <p>What I want to do is to allow users to find correct data for search terms with typos.</p> <p>I could use full-text search engines like Lucene, but I think it's an overkill.</p> <p><strong>Edit:</strong><br> To make question more clear here is a main scenario for that library:<br> I have a large list of strings. I want to be able to search in this list (something like MSVS' intellisense) but it should be possible to filter this list by string which is not present in it but close enough to some string which is in the list.<br> Example: </p> <ul> <li>Red</li> <li>Green</li> <li>Blue</li> </ul> <p>When I type 'Gren' or 'Geen' in a text box, I want to see 'Green' in the result set.</p> <p>Main language for indexed data will be English.</p> <p>I think that Lucene is to heavy for that task.</p> <p><strong>Update</strong>:</p> <p>I found one product matching my requirements. It's <a href="http://shuffletext.com/Highlight/">ShuffleText</a>.<br> Do you know any alternatives?</p>
<p>Lucene is very scalable&mdash;which means its good for little applications too. You can create an index in memory very quickly if that's all you need.</p> <p>For fuzzy searching, you really need to decide what algorithm you'd like to use. With information retrieval, I use an <a href="http://en.wikipedia.org/wiki/N-gram#n-grams_for_approximate_matching" rel="nofollow">n-gram</a> technique with Lucene successfully. But that's a special indexing technique, not a "library" in itself.</p> <p>Without knowing more about your application, it won't be easy to recommend a suitable library. How much data are you searching? What format is the data? How often is the data updated?</p>
Why does the Bourne shell printf iterate over a %s argument? <p>What's going on here?</p> <p>printf.sh:</p> <pre><code>#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME </code></pre> <p>Command line session:</p> <pre><code>$ ./printf.sh Hello, George Hello, W. Hello, Bush </code></pre> <p>UPDATE: <code>printf "Hello, %s\n" "$NAME"</code> works. For why I'm not using <code>echo</code>, consider</p> <p>echo.sh:</p> <pre><code>#! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" </code></pre> <p>Command-line:</p> <pre><code>$ ./echo.sh Filename: C: mp </code></pre> <p>The <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="nofollow">POSIX spec for <code>echo</code></a> says, "New applications are encouraged to use <code>printf</code> instead of <code>echo</code>" (for this and other reasons). </p>
<p>Your NAME variable is being substituted like this:</p> <pre><code>printf "Hello, %s\n" George W. Bush </code></pre> <p>Use this:</p> <pre><code>#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME" </code></pre>
How can I unit test a Windows Service? <p>.NET Framework: 2.0 Preferred Language: C#</p> <p>I am new to TDD (Test Driven Development).</p> <p>First of all, is it even possible to unit test Windows Service?</p> <p>Windows service class is derived from ServiceBase, which has overridable methods, </p> <ol> <li>OnStart </li> <li>OnStop</li> </ol> <p>How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?</p> <p>At this point, am I even doing a Unit testing? or an Integration test?</p> <p>I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.</p>
<p>I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service.</p> <p>In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.</p>
Managing LINQ to SQL .dbml model complexity <p>This question is addressed to a degree in this question on <a href="http://stackoverflow.com/questions/33664/best-practices-for-managing-linq-to-sql-dbml-files" rel="nofollow">LINQ to SQL .dbml best practices</a>, but I am not sure how to add to a question.</p> <p>One of our applications uses LINQ to SQL and we have currently have one .dbml file for the entire database which is becoming difficult to manage. We are looking at refactoring it a bit into separate files that are more module/functionality specific, but one problem is that many of the high level classes would have to be duplicated in several .dbml files as the associations can't be used across .dbml files (as far as I know), with the additional partial class code as well.</p> <p>Has anyone grappled with this problem and what recommendations would you make?</p>
<p>Take advantage of the namespace settings. You can get to it in properties from clicking in the white space of the ORM.</p> <p>This allows me to have a Users table and a User class for one set of business rules and a second (but the same data store) Users table and a User class for another set of business rules.</p> <p>Or, break up the library, which should also have the affect of changing the namespacing depending on your company's naming conventions. I've never worked on an enterprise app where I needed access to every single table.</p>
Custom titlebars/chrome in a WinForms app <p>I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked.</p> <p>Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding <code>WndProc</code> to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked?</p> <p>I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.</p>
<p>Here's an article with full code sample on how to use your own custom "chrome" for an application:</p> <p><a href="http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx">http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx</a></p> <p>This looks like some really good stuff. There are a total of 3 articles in it's series, and it runs great, and on Vista too!</p>
TFS - Branching for experimental development: Solution fails to load <p><em>Disclaimer: I'm stuck on TFS and I hate it.</em></p> <p>My source control structure looks like this:</p> <ul> <li>/dev</li> <li>/releases</li> <li>/branches</li> <li>/experimental-upgrade</li> </ul> <p>I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.</p> <p>I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me: </p> <blockquote> <p>"Projects have recently been added to this solution. Would you like to get them from source control?</p> </blockquote> <p>If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.</p> <p>Comparing my sln in both branches tells me that they are equal.</p> <p>Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...</p> <p>TIA.</p> <hr> <p><strong>UPDATE:</strong></p> <p>I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev &amp; branches folders)</p> <p>If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...</p> <blockquote> <p>Cannot load the project c:\sandbox\my_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my_solution\branches\experimental-upgrade\proj1\proj1.csproj</p> </blockquote> <p>What in the world is pointing these projects <em>outside</em> of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.</p> <p>Ideas?</p>
<p>@Ben</p> <p>You can actually do a full delete in TFS, but it is highly not recommended unless you know what you are doing. You have to do it from the command line with the command tf destroy</p> <pre><code>tf destroy [/keephistory] itemspec1 [;versionspec] [itemspec2...itemspecN] [/stopat:versionspec] [/preview] [/startcleanup] [/noprompt] Versionspec: Date/Time Dmm/dd/yyyy or any .Net Framework-supported format or any of the date formats of the local machine Changeset number Cnnnnnn Label Llabelname Latest version T Workspace Wworkspacename;workspaceowner </code></pre> <p>Just before you do this make sure you try it out with the /preview. Also everybody has their own methodology for branching. Mine is to branch releases, and do all development in the development or root folder. Also it sounded like branching worked fine for you, just the solution file was screwed up, which may be because of a binding issue and the vssss file.</p>
Extract Address Information from a Web Page <p>I need to take a web page and extract the address information from the page. Some are easier than others. I'm looking for a firefox plugin, windows app, or VB.NET code that will help me get this done.</p> <p>Ideally I would like to have a web page on our admin (ASP.NET/VB.NET) where you enter a URL and it scraps the page and returns a Dataset that I can put in a Grid.</p>
<p>What type of address information are you referring to?</p> <p>There are a couple FireFox plugins <a href="https://addons.mozilla.org/en-US/firefox/addon/4106" rel="nofollow">Operator</a> &amp; <a href="http://blog.codeeg.com/tails-firefox-extension-03/" rel="nofollow">Tails</a> that allow you to extract and view microformats from web pages.</p>
Metalanaguage to describe the Model from MVC to generate identical client and server side code <p>I am looking for a powerful meta-language to describa behaviour for an application i intend to use in offline mode (google-gears + javascript) and server side sqlite + (php/ruby/java etc) and looking for a good format to describe the model's behaviour which can be easily converted to the target languages. Am I completely off track, and there is a much better way?</p>
<p>Have you looked at <a href="http://code.google.com/webtoolkit/" rel="nofollow">Google Web Toolkit</a>? GWT allows you to write server side Java objects which get translated into Javascript for you. This allows you to not deal with the browser quirks at all. I'm not sure how well integrated the Gears and GWT projects are, however. If it isn't integrated yet, I'm sure it will be in fairly short order.</p> <p>Edit: This is probably more of an alternate way of doing what you're looking for, rather than a suggestion for a meta language.</p>
SQL Server Views, blessing or curse? <p>I once worked with an architect who banned the use of SQL views. His main reason was that views made it too easy for a thoughtless coder to needlessly involve joined tables which, if that coder tried harder, could be avoided altogether. Implicitly he was encouraging code reuse via copy-and-paste instead of encapsulation in views.</p> <p>The database had nearly 600 tables and was highly normalised, so most of the useful SQL was necessarily verbose.</p> <p>Several years later I can see at least one bad outcome from the ban - we have many hundreds of dense, lengthy stored procs that verge on unmaintainable.</p> <p>In hindsight I would say it was a bad decision, but what are your experiences with SQL views? Have you found them bad for performance? Any other thoughts on when they are or are not appropriate?</p>
<p>There are some very good uses for views; I have used them a lot for tuning and for exposing less normalized sets of information, or for UNION-ing results from multiple selects into a single result set.</p> <p>Obviously any programming tool can be used incorrectly, but I can't think of any times in my experience where a poorly tuned view has caused any kind of drawbacks from a performance standpoint, and the value they can provide by providing explicitly tuned selects and avoiding duplication of complex SQL code can be significant.</p> <p>Incidentally, I have never been a fan of architectural "rules" that are based on keeping developers from hurting themselves. These rules often have unintended side-effects -- the last place I worked didn't allow using NULLs in the database, because developers might forget to check for null. This ended up forcing us to work around "1/1/1900" dates and integers defaulted to "0" in all the software built against the databases, and introducing a litany of bugs caused by devs working around places where NULL was the appropriate value.</p>
Which Dynamic .NET language makes more sense to learn, Iron Ruby or Iron Python? <p>I'd like to take some time to learn more about dynamic languages built on top of the DLR and I'm not sure which language would be better to learn.</p> <p>Having limited time, I really only have time to look learn one of them.</p> <p>Any opinions on which of the two (Iron Ruby or Iron Python) would be more useful in the long run?</p>
<p>Without getting into the relative merits of the languages (which would be an entire pissing contest in itself), IronPython (stable 1.1.1, beta 2.0) is further along in development than IronRuby (alpha)</p>
Efficient synthesis of a 4-to-1 function in Verilog <p>I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:</p> <pre><code>wire [3:0] a; wire b; wire [15:0] c; assign c = 16'b0100110010111010; //for example but could be any constant assign b = c[a]; </code></pre> <p>Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?</p>
<p>What you have is fine. A case statement would also work equally well. It's just a matter of how expressive you wish to be. </p> <p>Your solution, indexing, works fine if the select encodings don't have any special meaning (a memory address selector for example). If the select encodings do have some special semantic meaning to you the designer (and there aren't too many of them), then go with a case statement and enums.</p> <p>Synthesis wise, it doesn't matter which one you use. Any decent synthesis tool will produce the same result.</p>
What is WCF in simple terms? <p>What is WCF in simple terms?</p> <p>It's hard to distill the meaning from <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation">the Wikipedia page</a>.</p>
<p>WCF - <a href="http://msdn.microsoft.com/en-us/library/ms731082.aspx">Windows Communication Framework</a> - is Microsoft's framework to make inter-process communication easier. It let's you do this communication through various means, plain old asmx web services, Remoting, MS Message Queuing, and a couple more.</p> <p>It let's you talk with other .NET apps, or non-Microsoft technologies (like J2EE). It's extensible enough to allow for newer stuff, like REST too (I don't think REST is built-in).</p>
Writing/Using C++ Libraries <p>I am looking for basic examples/tutorials on:</p> <ol> <li><p>How to write/compile libraries in C++ (<code>.so</code> files for Linux, <code>.dll</code> files for Windows).</p></li> <li><p>How to import and use those libraries in other code.</p></li> </ol>
<h2>The code</h2> <p><em>r.cc</em> :</p> <pre><code>#include "t.h" int main() { f(); return 0; } </code></pre> <p><em>t.h</em> :</p> <pre><code>void f(); </code></pre> <p><em>t.cc</em> :</p> <pre><code>#include&lt;iostream&gt; #include "t.h" void f() { std::cout &lt;&lt; "OH HAI. I'M F." &lt;&lt; std::endl; } </code></pre> <h2>But how, how, how?!</h2> <pre><code>~$ g++ -fpic -c t.cc # get t.o ~$ g++ -shared -o t.so t.o # get t.so ~$ export LD_LIBRARY_PATH="." # make sure t.so is found when dynamically linked ~$ g++ r.cc t.so # get an executable </code></pre> <p>The <code>export</code> step is not needed if you install the shared library somewhere along the global library path.</p>
Setting Focus with ASP.NET AJAX Control Toolkit <p>I'm using the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow">AutoComplete</a> control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. </p> <p>I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. </p> <p>Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.</p>
<p>We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: <a href="http://www.drive.com.au" rel="nofollow">http://www.drive.com.au</a> </p> <p>The textbox id is <code> MainSearchBox_SearchTextBox</code>. Have a look at about line 586 &amp; you can see where I'm wiring up all the events (I'm actually using prototype for this bit.</p> <p>Basically on the focus event of the textbox I set a global var called <code>textBoxHasFocus</code> to true and on the blur event I set it to false. The on the load event of the page I call this script:</p> <pre><code>if (textBoxHasFocus) { $get("MainSearchBox_SearchTextBox").blur(); $get("MainSearchBox_SearchTextBox").focus(); } </code></pre> <p>This resets the textbox. It's really dodgy, but it's the only solution I could find</p>
Get Last Day of the Month in Python <p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
<p>I didn't notice this earlier when I was looking at the <a href="https://docs.python.org/2/library/calendar.html">documentation for the calendar module</a>, but a method called <a href="http://docs.python.org/library/calendar.html#calendar.monthrange">monthrange</a> provides this information:</p> <blockquote> <p><b>monthrange(year, month)</b><br> &nbsp;&nbsp;&nbsp;&nbsp;Returns weekday of first day of the month and number of days in month, for the specified year and month. </p> </blockquote> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.monthrange(2002,1) (1, 31) &gt;&gt;&gt; calendar.monthrange(2008,2) (4, 29) &gt;&gt;&gt; calendar.monthrange(2100,2) (0, 28) </code></pre> <p>so:</p> <pre><code>calendar.monthrange(year, month)[1] </code></pre> <p>seems like the simplest way to go.</p> <p>Just to be clear, <code>monthrange</code> supports leap years as well:</p> <pre><code>&gt;&gt;&gt; from calendar import monthrange &gt;&gt;&gt; monthrange(2012, 2) (2, 29) </code></pre> <p><a href="http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python#43088">My previous answer</a> still works, but is clearly suboptimal.</p>
How to use p4merge as the merge/diff tool for Mercurial? <p>Does anyone know how to setup <a href="http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial">Mercurial</a> to use <a href="http://www.perforce.com/perforce/products/merge.html">p4merge</a> as the merge/diff tool on OS X 10.5?</p>
<p>Place this into your <code>~/.hgrc</code> (or, optionally, your <code>Mercurial.ini</code> on Windows):</p> <pre><code>[merge-tools] p4.priority = 100 p4.premerge = True # change this to False if you're don't trust hg's internal merge p4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge p4.gui = True p4.args = $base $local $other $output </code></pre> <p>Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed.</p>
Regex to match against something that is not a specific substring <p>I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.</p> <p>Example:</p> <pre><code>// Updated to be correct, thanks @Apocalisp ^foo.*(?&lt;!bar)$ </code></pre> <p>Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. </p> <p>I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. </p> <p>Thanks to @Kibbee for verifying that this works in C# as well. </p>
<p>I think in this case you want <strong>negative lookbehind</strong>, like so:</p> <pre><code>foo.*(?&lt;!bar) </code></pre>
What are some resources for getting started in operating system development? <p>One thing I've always wanted to do is develop my very own operating system (not necessarily fancy like Linux or Windows, but better than a simple boot loader which I've already done).</p> <p>I'm having a hard time finding resources/guides that take you past writing a simple "Hello World" OS. </p> <p>I know lots of people will probably recommend I look at Linux or BSD; but the code base for systems like that is (presumably) so big that I wouldn't know where to start.</p> <p>Any suggestions?</p> <p>Update: To make it easier for people who land on this post through Google here are some OS development resources:</p> <ul> <li><p><a href="https://web.archive.org/web/20120506110242/http://osix.net/modules/article/?id=359">Writing Your Own Operating System</a> (Thanks Adam)</p></li> <li><p><a href="http://www.linuxfromscratch.org/">Linux From Scratch</a> (Thanks John)</p></li> <li><p><a href="http://en.wikipedia.org/wiki/SharpOS_(operating_system)">SharpOS (C# Operating System)</a> (Thanks lomaxx)</p></li> <li><p><a href="http://www.minix3.org/">Minix3</a> and <a href="http://minix1.woodhull.com/mxdownld.html">Minix2</a> (Thanks Mike)</p></li> <li><p><a href="http://wiki.osdev.org/Main_Page">OS Dev Wiki</a> and <a href="http://forum.osdev.org/">Forums</a> (Thanks Steve)</p></li> <li><p><a href="http://www.osdever.net/">BonaFide</a> (Thanks Steve)</p></li> <li><p><a href="http://osdever.net/bkerndev/Docs/intro.htm">Bran</a> (Thanks Steve)</p></li> <li><p><a href="http://www.jamesmolloy.co.uk/tutorial_html/index.html">Roll your own toy UNIX-clone OS</a> (Thanks Steve)</p></li> <li><p><a href="http://www.brokenthorn.com/Resources/OSDevIndex.html">Broken Thorn OS Development Series</a></p></li> </ul> <p>Other resources:</p> <p>I found a nice resource named <a href="http://mikeos.berlios.de/">MikeOS</a>, "MikeOS is a learning tool to demonstrate how simple OSes work. It uses 16-bit real mode for BIOS access, so that it doesn't need complex drivers"</p> <p><em>Updated 11/14/08</em> </p> <p>I found some resources at <a href="http://www.freebyte.com/operatingsystems/#osprojects">Freebyte's Guide to...Free and non-free Operating Systems</a> that links to kits such as OSKit and ExOS library. These seem super useful in getting started in OS development.</p> <p><em>Updated 2/23/09</em></p> <p><a href="http://stackoverflow.com/users/42019/ric-tokyo">Ric Tokyo</a> recommended <a href="http://code.google.com/p/nanoos/">nanoos</a> in this <a href="http://stackoverflow.com/questions/580308/making-an-os-in-c/580362#580362">question</a>. Nanoos is an OS written in C++.</p> <p><em>Updated 3/9/09</em></p> <p>Dinah provided some useful Stack Overflow discussion of aspiring OS developers: <a href="http://stackoverflow.com/questions/340674/roadblocks-in-creating-a-custom-operating-system">Roadblocks in creating a custom operating system</a> discusses what pitfalls you might encounter while developing an OS and <a href="http://stackoverflow.com/questions/130065/os-development">OS Development</a> is a more general discussion.</p> <p><em>Updated 7/9/09</em></p> <p>LB provided a link to the <a href="http://www.scs.stanford.edu/07au-cs140/pintos/pintos.html">Pintos Project</a>, an education OS designed for students learning OS development.</p> <p><em>Updated 7/27/09 (Still going strong!)</em></p> <p>I stumbled upon an <a href="http://academicearth.org/courses/operating-systems-and-system-programming">online OS course</a> from Berkley featuring 23 lectures.</p> <p><a href="http://tomos.sourceforge.net/">TomOS</a> is a fork of <a href="http://mikeos.berlios.de/">MikeOS</a> that includes a little memory manager and mouse support. As MikeOS, it is designed to be an educational project. It is written in NASM assembler.</p> <p><em>Updated 8/4/09</em></p> <p>I found the <a href="http://www.cs.berkeley.edu/~kubitron/courses/cs162-F08/">slides and other materials</a> to go along with the online Berkeley lectures listed above. </p> <p><em>Updated 8/23/09</em></p> <p>All <a href="http://stackoverflow.com/questions/tagged/osdev">questions tagged osdev</a> on stackoverflow</p> <p><a href="http://www.eecs.harvard.edu/syrah/os161/">OS/161</a> is an academic OS written in c that runs on a simulated hardware. This OS is similar in Nachos. Thanks Novelocrat!</p> <p>tangurena recommends <a href="http://en.wikipedia.org/wiki/MicroC/OS-II">http://en.wikipedia.org/wiki/MicroC/OS-II</a>, an OS designed for embedded systems. There is a <a href="http://rads.stackoverflow.com/amzn/click/1578201039">companion book</a> as well.</p> <p><a href="http://rads.stackoverflow.com/amzn/click/0672327201">Linux Kernel Development</a> by Robert Love is suggested by Anders. It is a "widely acclaimed insider's look at the Linux kernel."</p> <p><em>Updated 9/18/2009</em></p> <p>Thanks Tim S. Van Haren for telling us about <a href="http://www.gocosmos.org/index.en.aspx">Cosmos</a>, an OS written entirely in c#.</p> <p>tgiphil tells us about <a href="http://www.codeplex.com/mosa">Managed Operating System Alliance (MOSA) Framework</a>, "a set of tools, specifications and source code to foster development of managed operating systems based on the Common Intermediate Language."</p> <p><em>Update 9/24/2009</em></p> <p>Steve found a couple resources for development on windows using Visual Studio, check out <a href="http://www.brokenthorn.com/Resources/OSDevMSVC.html">BrokenThorn's guide setup with VS 2005</a> or <a href="http://wiki.osdev.org/Visual%5FStudio">OSDev's VS Section</a>.</p> <p><em>Update 1/20/2012</em></p> <p>A set of tutorials aims to take you through programming a simple UNIX-clone operating system for the x86 architecture. <a href="http://www.jamesmolloy.co.uk/tutorial_html/">JamesM's kernel development tutorials</a></p> <p><em>Updated 9/5/2012</em></p> <p>kerneltrap.org is no longer available. The linux kernel v0.01 is available from <a href="http://www.kernel.org/pub/linux/kernel/Historic/linux-0.01.tar.gz">kernel.org</a></p> <p><em>Updated 12/21/2012</em> A basic OS development <a href="http://nw08.american.edu/~mblack/teaching.html#OSPROJECT">tutorial</a> designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related <a href="http://nw08.american.edu/~mblack/papers/sigcse09.pdf">paper</a>. Thanks Srujan!</p> <p><em>Updated 11/15/2013</em></p> <p><a href="http://www.cs.bham.ac.uk/~exr/lectures/opsys/10_11/lectures/os-dev.pdf">Writing a Simple Operating System From Scratch</a>. Thanks James Moore!</p> <p><em>Updated 12/8/2013</em></p> <p><a href="https://github.com/SamyPesse/How-to-Make-a-Computer-Operating-System">How to make a computer operating system</a> Thanks ddtoni!</p> <p><em>Updated 3/18/2014</em></p> <p><a href="https://github.com/klange/toaruos">ToAruOS an OS built mostly from scratch, including GUI</a></p> <p><em>Updated Sept 12 2016</em></p> <p><a href="http://www.independent-software.com/writing-your-own-toy-operating-system/">Writing your own Toy Operating System</a></p>
<p>There are a lot of links after this <a href="http://www.osix.net/modules/article/?id=359" rel="nofollow">brief overview</a> of what is involved in writing an OS for the X86 platform.</p> <p>The link that appears to be most promising (www.nondot.org/sabre/os/articles) is no longer available, so you'll need to poke through the <a href="http://web.archive.org/web/20021207220335/http://www.nondot.org/sabre/os/articles" rel="nofollow">Archive.org version</a> to read it.</p> <p>At the end of the day the bootloader takes the machine code of the kernel, puts it in memory, and jumps to it. You can put any machine code in the kernel that you want, but most C programs expect an OS so you'll need to tell your compiler that it won't have all that, or the bootloader has to create some of it.</p> <p>The kernel then does all the heavy lifting, and I suspect it's the example kernel you want. But there's a long way to go between having a kernel that says, "Hello world" to having a kernel that loads a command interpretor, provides disk services, and loads and manages programs.</p> <p>You might want to consider subscribing to ACM to get access to their older literature - there are lots of articles in the late 80's and early 90's in early computing magazines about how to <a href="http://portal.acm.org/citation.cfm?id=87073.87079" rel="nofollow">create alternative OSs</a>. There are likely books that are out of print from this era as well. You might be able to get the same information for free by looking up the indexes of those magazines (which are available on that site - click "index" near the magazine name) and then asking around for people with a copy.</p> <p>Lastly, I know that usenet is dead (for so sayeth the prophets of internet doom) but you'll find that many of the craggy old experts from that era still live there. You should search google groups (they have dejanews's old repository) and I expect you'll find many people asking the same questions a decade or 1.5 ago that you're asking now. You may even run across Linus Torvalds' many queries for help as he was developing linux originally. If searches don't bring anything up, ask in the appropriate newsgroup (probably starts with comp.arch, but search for ones with OS in the name).</p>
How to generate urls in django <p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p> <pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None) </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>
NHibernate ISession Flush: Where and when to use it, and why? <p>One of the things that get me thoroughly confused is the use of <code>session.Flush</code>,in conjunction with <code>session.Commit</code>, and <code>session.Close</code>.</p> <p>Sometimes <code>session.Close</code> works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.</p> <p>But sometimes I really get stymied by the logic behind <code>session.Flush</code>. I have seen examples where you have a <code>session.SaveOrUpdate()</code> followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.</p> <p>Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.</p>
<p>Briefly:</p> <ol> <li>Always use transactions</li> <li>Don't use <code>Close()</code>, instead wrap your calls on an <code>ISession</code> inside a <code>using</code> statement or <strong>manage the lifecycle of your ISession somewhere else</strong>.</li> </ol> <p>From <a href="http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing">the documentation</a>:</p> <blockquote> <p>From time to time the <code>ISession</code> will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points</p> <ul> <li>from some invocations of <code>Find()</code> or <code>Enumerable()</code></li> <li>from <code>NHibernate.ITransaction.Commit()</code></li> <li>from <code>ISession.Flush()</code> </li> </ul> <p>The SQL statements are issued in the following order</p> <ol> <li>all entity insertions, in the same order the corresponding objects were saved using <code>ISession.Save()</code></li> <li>all entity updates</li> <li>all collection deletions</li> <li>all collection element deletions, updates and insertions</li> <li>all collection insertions</li> <li>all entity deletions, in the same order the corresponding objects were deleted using <code>ISession.Delete()</code></li> </ol> <p>(An exception is that objects using native ID generation are inserted when they are saved.)</p> <p><strong>Except when you explicity <code>Flush()</code>, there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed</strong>. However, NHibernate does guarantee that the <code>ISession.Find(..)</code> methods will never return stale data; nor will they return the wrong data.</p> <p>It is possible to change the default behavior so that flush occurs less frequently. The <code>FlushMode</code> class defines three different modes: only flush at commit time (and only when the NHibernate <code>ITransaction</code> API is used), flush automatically using the explained routine, or never flush unless <code>Flush()</code> is called explicitly. The last mode is useful for long running units of work, where an <code>ISession</code> is kept open and disconnected for a long time.</p> </blockquote> <p>...</p> <p>Also refer to <a href="http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-endingsession">this section</a>:</p> <blockquote> <p>Ending a session involves four distinct phases:</p> <ul> <li>flush the session</li> <li>commit the transaction</li> <li>close the session</li> <li>handle exceptions </li> </ul> <h2>Flushing the Session</h2> <p>If you happen to be using the <code>ITransaction</code> API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call <code>ISession.Flush()</code> to ensure that all changes are synchronized with the database.</p> <h2>Committing the database transaction</h2> <p>If you are using the NHibernate ITransaction API, this looks like:</p> <pre><code>tx.Commit(); // flush the session and commit the transaction </code></pre> <p>If you are managing ADO.NET transactions yourself you should manually <code>Commit()</code> the ADO.NET transaction.</p> <pre><code>sess.Flush(); currentTransaction.Commit(); </code></pre> <p>If you decide not to commit your changes:</p> <pre><code>tx.Rollback(); // rollback the transaction </code></pre> <p>or:</p> <pre><code>currentTransaction.Rollback(); </code></pre> <p>If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent.</p> <h2>Closing the ISession</h2> <p>A call to <code>ISession.Close()</code> marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session.</p> <pre><code>tx.Commit(); sess.Close(); sess.Flush(); currentTransaction.Commit(); sess.Close(); </code></pre> <p>If you provided your own connection, <code>Close()</code> returns a reference to it, so you can manually close it or return it to the pool. Otherwise <code>Close()</code> returns it to the pool. </p> </blockquote>
Is there a standard HTML layout with multiple CSS styles available? <p>When it comes to web-design, I am horrible at producing anything remotely good looking. Thankfully there are a lot of free <a href="http://www.mantisatemplates.com/web-templates.php">sources</a> for <a href="http://www.freecsstemplates.org/">design</a> <a href="http://www.oswd.org/">templates</a>. However, a problem with these designs is that they just cover a single page, and not many use cases. If you take a look at <a href="http://www.csszengarden.com/">CSS Zen Gardens</a>, they have 1 single HTML file, and can radically style it differently by just changing the CSS file.</p> <p>Now I am wondering if there is a standard HTML layout (tags and ids), that covers alot of use cases, and can be generically themed with different CSS files like Zen Garden. What I am imagining is a set of rules off how you write your html, and what boxes, lists, menus and styles you are supposed to use. A set of standard test pages covering the various uses can be created, and a new CSS file while have to support all the different pages in a nice view.</p> <p>Is there any projects that covers anything similar to what I am describing?</p>
<p>Check out the <a href="http://developer.yahoo.com/yui/grids/" rel="nofollow">Grids framework</a> from YUI. Particularly awesome is the <a href="http://developer.yahoo.com/yui/grids/builder/" rel="nofollow">Grid Builder</a>. Also, they have a set of reset, base, and font CSS files that will give you a good baseline to build on.</p>
When is Control.DestroyHandle called? <p>When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during <code>wm_close</code> - is <code>DestroyHandle</code> the .net equivalent?</p> <hr> <p>I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:</p> <pre><code>void Dispose(bool disposing) { otherObject.Event -= myEventHandler; } </code></pre>
<p>Normally <code>DestroyHandle</code> is being called in <code>Dispose</code> method. So you need to make sure that all controls are disposed to avoid resource leaks.</p>
Is there a built-in method to compare collections in C#? <p>I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this?</p> <p>Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb342073.aspx"><code>Enumerable.SequenceEqual</code></a></p> <blockquote> <p>Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T).</p> </blockquote> <p>You can't directly compare the list &amp; the dictionary, but you could compare the list of values from the Dictionary with the list</p>
How to find the mime type of a file in python? <p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
<p>The python-magic method suggested by toivotuo is outdated. <a href="http://github.com/ahupp/python-magic">Python-magic's</a> current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.</p> <pre><code># For MIME types &gt;&gt;&gt; import magic &gt;&gt;&gt; mime = magic.Magic(mime=True) &gt;&gt;&gt; mime.from_file("testdata/test.pdf") 'application/pdf' &gt;&gt;&gt; </code></pre>
How to concatenate strings of a string field in a PostgreSQL 'group by' query? <p>I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:</p> <pre><code>ID COMPANY_ID EMPLOYEE 1 1 Anna 2 1 Bill 3 2 Carol 4 2 Dave </code></pre> <p>and I wanted to group by company_id to get something like:</p> <pre><code>COMPANY_ID EMPLOYEE 1 Anna, Bill 2 Carol, Dave </code></pre> <p>There is a built-in function in mySQL to do this <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat">group_concat</a></p>
<h3>Update as of PostgreSQL 9.0:</h3> <p>Recent versions of Postgres (since late 2010) have the <a href="http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE"><code>string_agg(expression, delimiter)</code></a> function that will do exactly what the question asked for, even letting you specify the delimiter string:</p> <pre><code>SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; </code></pre> <h3>Update as of PostgreSQL 8.4:</h3> <p>PostgreSQL 8.4 (in 2009) introduced <a href="http://www.postgresql.org/docs/8.4/interactive/functions-aggregate.html">the aggregate function <code>array_agg(expression)</code></a> which concatenates the values into an array. Then <code>array_to_string()</code> can be used to give the desired result:</p> <pre><code>SELECT company_id, array_to_string(array_agg(employee), ', ') FROM mytable GROUP BY company_id; </code></pre> <h3>Original Answer (for pre-8.4 PostgreSQL):</h3> <p>There is no built-in aggregate function to concatenate strings. It seems like this would be needed, but it's not part of the default set. A web search however reveals some manual implementations <a href="http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php">the same example</a>:</p> <pre><code>CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = '' ); </code></pre> <p><a href="http://www.postgresql.org/docs/8.3/static/sql-createaggregate.html">Here is the <code>CREATE AGGREGATE</code> documentation.</a></p> <p>In order to get the ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together but haven't tested (<strong><em>update:</strong> tested on 8.3.12 and working fine</em>):</p> <pre><code>CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; </code></pre> <p><strong><em>Note:</strong> The function above will output a comma even if the value in the row is null/empty, which outputs:</em></p> <pre><code>a, b, c, , e, , g </code></pre> <p><em>If you would prefer to remove extra commas to output:</em></p> <pre><code>a, b, c, e, g </code></pre> <p><em>just add an <code>ELSIF</code> check to the function:</em></p> <pre><code>CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSIF instr IS NULL OR instr = '' THEN RETURN acc; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; </code></pre>
Crop MP3 to first 30 seconds <p><strong>Original Question</strong></p> <p>I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first <em>n</em> seconds of the track.</p> <p>Now, I know I could just "chop the stream" at <em>n</em> seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.</p> <p>Anyone any ideas?</p> <p><strong>Answers</strong></p> <p>Both mp3split and ffmpeg are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also <a href="http://sourceforge.net/project/showfiles.php?group_id=205275&amp;package_id=248632">easily available for windows</a>. Here's some more good command line parameters for generating previews with ffmpeg</p> <ul> <li><strong><code>-t &lt;seconds&gt;</code></strong> chop after specified number of seconds</li> <li><strong><code>-y</code></strong> force file overwrite</li> <li><strong><code>-ab &lt;bitrate&gt;</code></strong> set bitrate e.g. <em>-ab 96k</em></li> <li><strong><code>-ar &lt;rate Hz&gt;</code></strong> set sampling rate e.g. <em>-ar 22050</em> for 22.05kHz</li> <li><strong><code>-map_meta_data &lt;outfile&gt;:&lt;infile&gt;</code></strong> copy track metadata from infile to outfile</li> </ul> <p>instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:</p> <ul> <li><strong><code>-acodec copy</code></strong></li> </ul>
<p>I also recommend ffmpeg, but the command line suggested by John Boker has an unintended side effect: it re-encodes the file to the default bitrate (which is 64 kb/s in the version I have here at least). This might give your customers a false impression of the quality of your sound files, and it also takes longer to do.</p> <p>Here's a command line that will slice to 30 seconds without transcoding:</p> <pre><code>ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3 </code></pre> <p>The -acodec switch tells ffmpeg to use the special "copy" codec which does not transcode. It is lightning fast.</p> <p>NOTE: the command was updated based on comment from Oben Sonne</p>
What software to use for a multistage development environment? <p>For me a multistage environment contains environments for development, testing, quality assurance, maybe a client review stage and finally production. It should allow easy collaboration between developers, project status tracking and easy deployment of the application to any stage for a specific version. </p> <p>You can propose specific tools for specific application types but I think the question is general enough. Is there any software package ready to use out of the box?</p>
<p>We use CruiseControl.NET to automatically push source control checkins out to a dev server. This allows people to regression test their changes in real time.</p> <p>We then use a series of scripts to robocopy the build to other environments. </p> <p>For Example:</p> <ul> <li>Developer completes a change and checks into source control</li> <li>CruiseControl detects the change and builds the new code and drops into Dev.</li> <li>Developer is able to test the change in a enviroment that mirrors production.</li> <li>This repeats until all changes are done and tested. </li> <li>A script is ran that copies Dev to Test.</li> <li>Dev is now frozen while business owners UAT on the Test enviroment. If a defect is found, it is fixed in dev and then promoted back to Test.</li> <li>Once UAT passes, a script is ran that copies the build to the final production farm.</li> <li>At this point, developers are free to push code back to Dev for the next round of work.</li> </ul>
Custom Aggregate Functions in MS SQL Server? <p>How can I create a custom aggregate function in MS SQL Server? An example would help a lot.</p>
<p>SQL Server 2000 doesn't officially support custom aggregate functions. However, I recently needed that functionality as well, and I found this article enlightening:<br /> <a href="http://weblogs.sqlteam.com/jeffs/articles/1490.aspx" rel="nofollow">http://weblogs.sqlteam.com/jeffs/articles/1490.aspx</a></p> <p>It's a bit hack-ish, though: it requires access to the <code>sp_OA___</code> extended procedures.</p> <p>The summary is that you can <em>simulate</em> an aggregate function with a series of four wrapper functions, each of which performs one of the following tasks:</p> <ol> <li>Create an ActiveX object that can hold state within the query. Call this <em>before</em> running the query.</li> <li>Do the actual aggregation using the ActiveX object.</li> <li>Clear the ActiveX object state on GROUP BY boundries</li> <li>Destroy the object. Call this <em>after</em> running the query and during error handling.</li> </ol> <p>You then include items 2 <em>and</em> 3 in the select list for your query, and item 2 must also be wrapped in an existing no-effect aggregate function like MAX() or MIN(). You can also use this technique for cumulative functions to do things like row numbers.</p> <p>Some of the comments suggest that the optimizer may try to negate the aggregation effects by optimizing away the calls in some circumstances, though I expect that would be a very rare case indeed. However, I found this question because I took those warnings seriously enough to continue searching for something better. </p>
COTS Workshop Registration System <p>Does anyone have any experience with any COTS systems for managing workshops and the associated registrations, courses, communications, etc.?</p> <p>We have a home-built Perl system that is about 8 years old and is currently embedded as an iframe in a SharePoint portal site (externally facing). Needless to say, it isn't integrated into our site well, looks like crap, needs an overhaul, lacks features, etc. It would be nice to find either a product we can install or a service that provides those features.</p> <p>Thanks!</p>
<p>You might also look into Moodle - it's a platform developed to supplement classroom teaching (or implement online learning courses) but should have all the major features you listed, and would support your needs reasonably well, as well as enhancing your event with an online component such as slide/presentation distribution only to registered users or users that took a particular class, etc)</p>
Configuring sendmail behind a firewall <p>I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.</p> <p>So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.</p>
<p>@<a href="#44014">eli</a>: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler. </p> <p>Edit /etc/mail/sendmail.mc to include the line:</p> <pre><code> define(`SMART_HOST',`mailrelay.example.com')dnl </code></pre> <p>After changing the sendmail.mc macro configuration file, it must be recompiled to produce the sendmail configuration file.</p> <pre><code> # m4 /etc/mail/sendmail.mc &gt; /etc/sendmail.cf </code></pre> <p>And restart the sendmail service (Linux):</p> <pre><code> # /etc/init.d/sendmail restart </code></pre> <p>As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode.</p> <h1>Disable Name Resolution</h1> <p>Servers that are within fire-walled networks or using Network Address Translation (NAT) may not have DNS or NIS services available. This creates a problem for sendmail, since it will use DNS by default, and if it is not available you will see messages like this in mailq:</p> <pre><code> host map: lookup (mydomain.com): deferred) </code></pre> <p>Unless you are prepared to setup an appropriate DNS or NIS service that sendmail can use, in this situation you will typically configure name resolution to be done using the /etc/hosts file. This is done by enabling a 'service.switch' file and specifying resolution by file, as follows:</p> <p>1: Enable service.switch for sendmail Edit /etc/mail/sendmail.mc to include the lines:</p> <pre><code> define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl </code></pre> <p>2: Configure service.switch for files Create or modify /etc/mail/service.switch to refer only to /etc/hosts for name resolution:</p> <pre><code> # cat /etc/mail/service.switch hosts files </code></pre> <p>3: Recompile sendmail.mc and restart sendmail for this setting to take effect.</p> <h1>Shift sendmail to non-standard port, or disable daemon mode</h1> <p>By default, sendmail will listen on port 25. You may want to change this port or disable the sendmail daemon mode altogether for various reasons: - if there is a security policy prohibiting the use of well-known ports - if another SMTP product/process is to be running on the same host on the standard port - if you don't want to accept mail via smtp at all, just send it using sendmail</p> <p>1: To shift sendmail to use non-standard port. Edit /etc/mail/sendmail.mc and modify the "Port" setting in the line:</p> <pre><code> DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA') </code></pre> <p>For example, to get sendmail to use port 125:</p> <pre><code> DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA') </code></pre> <p>This will require sendmail.mc to be recompiled and sendmail to be restarted.</p> <p>2: Alternatively, to disable sendmail daemon mode altogether (Linux) Edit /etc/sysconfig/sendmail and modify the "DAEMON" setting to:</p> <pre><code> DAEMON=no </code></pre> <p>This change will require sendmail to be restarted.</p>
Does Microsoft ASP.NET Ajax Cause DOM Object Leaks? <p>We've been using "Drip" to try and identify why pages with UpdatePanels in them tend to use a lot of client-side memory. With a page with a regular postback, we are seeing 0 leaks detected by Drip. However, when we add an update panel to the mix, every single DOM object that is inside of the update panel appears to leak (according to Drip).</p> <p>I am not certain is Drip is reliable enough to report these kinds of things - the reported leaks do seem to indicate Drip is modifying the page slightly. </p> <p>Does anyone have any experience with this? Should I panic and stop using Microsoft Ajax? I'm not above doubting Microsoft, but it seems fishy to me that it could be <em>this</em> bad.</p> <p>Also, if you know of a tool that is better than Drip, that would be helpful as well.</p>
<p>According to <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FASP-NET-AJAX-Action-Alessandro-Gallo%2Fdp%2F1933988142&amp;tag=diaryofamadma-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325" rel="nofollow">ASP.NET AJAX in Action</a>, p. 257</p> <blockquote> <p>Just before the old markup is replaced with the updated HTML, all the DOM elements in the panel are examined for Microsoft Ajax behaviours or controls attached to them. To avoid memory leaks, the components associated with DOM elements are disposed, and then destroyed when the HTMl is replaced.</p> </blockquote> <p>So as far as I know, any asp.net ajax components within the update panel are disposed to prevent memory leaks, but anything else in there will just be replaced with the html received.</p> <p>So if you don't have any asp.net ajax components in the target container for the response, it would be basically the same as an inner html replacement with any other js framework / ajax request, so i would say that it's just the how the browser handles this, rather than asp.net ajax causing this.</p> <p>Also, while it may be "leaking", it may be by design, meaning that the browser might not have reclaimed the dom elements yet and released them. Also, drip might be causing those to leak, as it is attaching to those dom elements.</p>
Best way to use a property to reference a Key-Value pair in a dictionary <p>This is a fairly trivial matter, but I'm curious to hear people's opinions on it.</p> <p>If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?</p> <pre><code>/// &lt;summary&gt; /// This class's FirstProperty property /// &lt;/summary&gt; [DefaultValue("myValue")] public string FirstProperty { get { return Dictionary["myKey"]; } set { Dictionary["myKey"] = value; } </code></pre> <p>This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:</p> <pre><code>/// &lt;summary&gt; /// This class's SecondProperty property /// &lt;/summary&gt; [DefaultValue("myValue")] private const string DICT_MYKEY = "myKey" public string SecondProperty { get { return Dictionary[DICT_MYKEY]; } set { Dictionary[DICT_MYKEY] = value; } </code></pre> <p>Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.</p> <p>So which do you like better, and why? Does anybody have any better ideas?</p>
<p>I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant </p>
Looking for a simple JavaScript example that updates DOM <p>I am looking for a simple JavaScript example that updates DOM.<br> Any suggestions?</p>
<p>Here is a short pure-javascript example. Assume you have a div with the id "maincontent".</p> <pre><code>var newnode = document.createTextNode('Here is some text.'); document.getElementById('maincontent').appendChild(newnode); </code></pre> <p>Of course, things are a lot easier (especially when you want to do more complicated things) with jQuery.</p>
Difference between foreach and for loops over an IEnumerable class in C# <p>I have been told that there is a performance difference between the following code blocks.</p> <pre><code>foreach (Entity e in entityList) { .... } </code></pre> <p>and </p> <pre><code>for (int i=0; i&lt;entityList.Count; i++) { Entity e = (Entity)entityList[i]; ... } </code></pre> <p>where</p> <pre><code>List&lt;Entity&gt; entityList; </code></pre> <p>I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other?</p>
<p>foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.</p> <p>They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator.</p>
Can .NET check other running programs command line parameters? <p>We've got an interesting case where we are trying to determine how different instances of our app were launched. Is there any way for .NET to be able to query another running instance and get the command line parameters passed to that instance? I've not been able to find any way to do it in .NET so far, so I thought I'd check here to see if anyone had done anything like this before.</p>
<p>You can retrieve this information through WMI.</p> <p>See the <a href="http://msdn.microsoft.com/en-us/library/aa394372.aspx" rel="nofollow">Win32_Process</a> class, in particular its command line property. This <a href="http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx" rel="nofollow">Code Project article</a> provides pointers on how to do this,</p>
Order an Array like another Array in C# <p>I'm looking for the best algorithm to take array A {0,1,2,3} and make order it like array B {3,1,0,2}. Any ideas?</p>
<p>So if you have two arrays and they hold the same data just in different order then just do this:</p> <p>A = B</p> <p>I suspect that is not your situation so I think we need more info.</p>
What are the best keyboard macros for programming in windows? <p>I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.</p> <p>My eight or so most frequent applications go there.</p> <p>I also make links to my solution files I am always opening "x - Popular Project.lnk"</p> <p>Are there any better ways to automate opening frequently used applications?</p>
<p><a href="http://www.autohotkey.com/" rel="nofollow">AutoHotkey</a> is a reasonably good program for implementing windows key shortcuts. You might instead define WIN + G to be "open browser to google" which gives you a better response time (don't have to wait for start menu to popup, etc)</p> <p>There are macro programs that change the macros used based on the window that's in focus. I've never needed that much control, but you might want to look into that.</p> <p>-Adam</p>
How do I get the ClickOnce Publish version to match the AssemblyInfo.cs File version? <p>Every time I publish the application in <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow">ClickOnce</a> I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?</p>
<p>We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's <code>AfterCompile</code> target to trigger the ClickOnce publish with our preferred version number:</p> <pre class="lang-xml prettyprint-override"><code>&lt;MSBuild Projects="$(SolutionRoot)\MyProject\Myproject.csproj" Properties="PublishDir=$(OutDir)\myProjectPublish\; ApplicationVersion=$(PublishApplicationVersion); Configuration=$(Configuration);Platform=$(Platform)" Targets="Publish" /&gt; </code></pre> <p>The <code>PublishApplicationVersion</code> variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use <a href="http://msdn.microsoft.com/en-us/library/t9883dzc.aspx" rel="nofollow">your own custom task</a> or an <a href="http://msbuildtasks.tigris.org/" rel="nofollow">existing solution</a> to get the version number from the AssemblyInfo file.</p> <p>This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine.</p> <p>I'm sure other <a href="http://en.wikipedia.org/wiki/Continuous_integration" rel="nofollow">continuous integration</a> (CI) solutions can handle this similarly.</p> <hr> <p><strong>Edit:</strong> Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML.</p> <p>However, you may also consider changing your error reporting to include the ClickOnce publish version too:</p> <pre class="lang-cs prettyprint-override"><code>if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) { Debug.WriteLine(System.Deployment.Application.ApplicationDeployment. CurrentDeployment.CurrentVersion); } </code></pre>
version control practice <p>In my current job the supervisor's practice is to only check in production ready code. Most recently the project I was on involved work by 3 different developers with some file overlap. This meant manually integrating changes despite the fact that some changes took a day and then it was done. I wanted to see if this was a common practice and get suggestions on how to change this practice with the knowledge that many times my opinion means little in the grand scheme of things.</p>
<p>You can use various ways to handle this situation, depending on your source control system. </p> <p>Private branches: Allow you to check in and work on code while you go, merging back and forth at appropriate times.</p> <p>Shelvesets/pacakaged changesets: Allow you to store changesets and send them around for review - ensuring they're production ready before check in.</p> <p>As to whether this is an appropriate way to work, we don't allow check-in to main branches without prior review. To pass review your code must pass various automated tools, and then must be acceptable to your peer reviewer. For some definitions of "production ready" - this is it. Therefore, we do something like what you do. However, we use private branches to ensure that check-ins can still be made while this is in progress, and that other check-ins don't have to interfere. </p> <p>If production ready means tested in an integration environment, then it sounds like you may need staging branches or something similar.</p>
Regex in VB6? <p>I need to write a program that can sift through specially-formatted text files (essentially CSV files with a fixed set of column types that have different delimiters for some columns ... comma in most places, colons in others) to search for formatting errors. I figure regular expressions will be the way to go.</p> <p>The question: Is there a good regex library for VB6?</p> <p>Thank you!</p> <p>Edit: Holy crap, 3 responses in under an hour. Thanks a ton, folks! I've heard such good things about Regex Buddy from Jeff's postings / podcasting, that I will have to take a look.</p>
<p>Use the Regex COM component built into Windows. You can find a step by step on referencing and using it in your project at: <a href="http://www.regular-expressions.info/vb.html" rel="nofollow">http://www.regular-expressions.info/vb.html</a></p>
Eclipse "Share Project" by hand? <p>What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion? All the .svn folders are already in place. I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN Repository browser.</p>
<p>Dunno exactly what happens within eclipse, I presume it does some funky stuff in the .metadata directory of the workspace. That said, I would recommend the following to get eclipse to learn about the svn settings of the project:</p> <ul> <li>Delete the project from the workspace (keep "Delete project contents on disk" unchecked)</li> <li>File > Import... > General > Existing Projects into Workspace</li> <li>Browse to the folder containing the original project(s) of interest</li> <li>Import the projects into your workspace</li> </ul> <p>This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace.</p>