instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>how can one know that each process or a thread is consuming how much memory in MYSQL?</p>
<p>Assuming you just want just the memory usage of the mysql server program.</p> <p>On windows you can use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">Process Explorer</a> </p> <p>On linux you can use the top command.</p> <ol> <li>Use "ps -e" to find the pid of the mysql process</li> <li>Then use "top -p {pid}" where {pid} is the pid of the mysql process. </li> </ol>
<p>on linux you can also use top|grep mysql to get a running report of the stats of the mysql process, 1 row per top refresh period.</p>
12,369
<p>8 bits representing the number 7 look like this:</p> <pre><code>00000111 </code></pre> <p>Three bits are set.</p> <p>What are the algorithms to determine the number of set bits in a 32-bit integer?</p>
<p>This is known as the '<a href="https://en.wikipedia.org/wiki/Hamming_weight" rel="nofollow noreferrer">Hamming Weight</a>', 'popcount' or 'sideways addition'.</p> <p>Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. Instructions like x86's <a href="https://www.felixcloutier.com/x86/popcnt" rel="nofollow noreferrer"><code>popcnt</code></a> (on CPUs where it's supported) will almost certainly be fastest for a single integer. Some other architectures may have a slow instruction implemented with a microcoded loop that tests a bit per cycle (<em>citation needed</em> - hardware popcount is normally fast if it exists at all.).</p> <p>The 'best' algorithm really depends on which CPU you are on and what your usage pattern is.</p> <p>Your compiler may know how to do something that's good for the specific CPU you're compiling for, e.g. <a href="https://en.cppreference.com/w/cpp/numeric/popcount" rel="nofollow noreferrer">C++20 <code>std::popcount()</code></a>, or C++ <a href="https://en.cppreference.com/w/cpp/utility/bitset/count" rel="nofollow noreferrer"><code>std::bitset&lt;32&gt;::count()</code></a>, as a portable way to access builtin / intrinsic functions (see <a href="https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109069#109069">another answer</a> on this question). But your compiler's choice of fallback for target CPUs that don't have hardware popcnt might not be optimal for your use-case. Or your language (e.g. C) might not expose any portable function that could use a CPU-specific popcount when there is one.</p> <hr /> <h3>Portable algorithms that don't need (or benefit from) any HW support</h3> <p>A pre-populated table lookup method can be very fast if your CPU has a large cache and you are doing lots of these operations in a tight loop. However it can suffer because of the expense of a 'cache miss', where the CPU has to fetch some of the table from main memory. (Look up each byte separately to keep the table small.) If you want popcount for a contiguous range of numbers, only the low byte is changing for groups of 256 numbers, <a href="https://stackoverflow.com/questions/66520106/count-integers-in-1-n-with-k-zero-bits-below-the-leading-1-popcount-for-a-c/66532113#66532113">making this very good</a>.</p> <p>If you know that your bytes will be mostly 0's or mostly 1's then there are efficient algorithms for these scenarios, e.g. clearing the lowest set with a bithack in a loop until it becomes zero.</p> <p>I believe a very good general purpose algorithm is the following, known as 'parallel' or 'variable-precision SWAR algorithm'. I have expressed this in a C-like pseudo language, you may need to adjust it to work for a particular language (e.g. using uint32_t for C++ and &gt;&gt;&gt; in Java):</p> <p>GCC10 and clang 10.0 can recognize this pattern / idiom and compile it to a hardware popcnt or equivalent instruction when available, giving you the best of both worlds. (<a href="https://godbolt.org/z/qGdh1dvKK" rel="nofollow noreferrer">https://godbolt.org/z/qGdh1dvKK</a>)</p> <pre class="lang-c prettyprint-override"><code>int numberOfSetBits(uint32_t i) { // Java: use int, and use &gt;&gt;&gt; instead of &gt;&gt;. Or use Integer.bitCount() // C or C++: use uint32_t i = i - ((i &gt;&gt; 1) &amp; 0x55555555); // add pairs of bits i = (i &amp; 0x33333333) + ((i &gt;&gt; 2) &amp; 0x33333333); // quads i = (i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F; // groups of 8 return (i * 0x01010101) &gt;&gt; 24; // horizontal sum of bytes } </code></pre> <p>For JavaScript: <a href="https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#comment103845611_109025">coerce to integer</a> with <code>|0</code> for performance: change the first line to <code>i = (i|0) - ((i &gt;&gt; 1) &amp; 0x55555555);</code></p> <p>This has the best worst-case behaviour of any of the algorithms discussed, so will efficiently deal with any usage pattern or values you throw at it. (Its performance is not data-dependent on normal CPUs where all integer operations including multiply are constant-time. It doesn't get any faster with &quot;simple&quot; inputs, but it's still pretty decent.)</p> <p>References:</p> <ul> <li><a href="https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel" rel="nofollow noreferrer">https://graphics.stanford.edu/~seander/bithacks.html</a></li> <li><a href="https://catonmat.net/low-level-bit-hacks" rel="nofollow noreferrer">https://catonmat.net/low-level-bit-hacks</a> for bithack basics, like how subtracting 1 flips contiguous zeros.</li> <li><a href="https://en.wikipedia.org/wiki/Hamming_weight" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Hamming_weight</a></li> <li><a href="http://gurmeet.net/puzzles/fast-bit-counting-routines/" rel="nofollow noreferrer">http://gurmeet.net/puzzles/fast-bit-counting-routines/</a></li> <li><a href="http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)" rel="nofollow noreferrer">http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)</a></li> </ul> <hr /> <h3>How this SWAR bithack works:</h3> <pre><code>i = i - ((i &gt;&gt; 1) &amp; 0x55555555); </code></pre> <p>The first step is an optimized version of masking to isolate the odd / even bits, shifting to line them up, and adding. This effectively does 16 separate additions in 2-bit accumulators (<a href="https://en.wikipedia.org/wiki/SWAR" rel="nofollow noreferrer">SWAR = SIMD Within A Register</a>). Like <code>(i &amp; 0x55555555) + ((i&gt;&gt;1) &amp; 0x55555555)</code>.</p> <p>The next step takes the odd/even eight of those 16x 2-bit accumulators and adds again, producing 8x 4-bit sums. The <code>i - ...</code> optimization isn't possible this time so it does just mask before / after shifting. Using the same <code>0x33...</code> constant both times instead of <code>0xccc...</code> before shifting is a good thing when compiling for ISAs that need to construct 32-bit constants in registers separately.</p> <p>The final shift-and-add step of <code>(i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F</code> widens to 4x 8-bit accumulators. It masks <em>after</em> adding instead of before, because the maximum value in any 4-bit accumulator is <code>4</code>, if all 4 bits of the corresponding input bits were set. 4+4 = 8 which still fits in 4 bits, so carry between nibble elements is impossible in <code>i + (i &gt;&gt; 4)</code>.</p> <p>So far this is just fairly normal SIMD using SWAR techniques with a few clever optimizations. Continuing on with the same pattern for 2 more steps can widen to 2x 16-bit then 1x 32-bit counts. But there is a more efficient way on machines with fast hardware multiply:</p> <p>Once we have few enough &quot;elements&quot;, <strong>a multiply with a magic constant can sum all the elements into the top element</strong>. In this case byte elements. Multiply is done by left-shifting and adding, so <strong>a multiply of <code>x * 0x01010101</code> results in <code>x + (x&lt;&lt;8) + (x&lt;&lt;16) + (x&lt;&lt;24)</code>.</strong> Our 8-bit elements are wide enough (and holding small enough counts) that this doesn't produce carry <em>into</em> that top 8 bits.</p> <p><strong>A 64-bit version of this</strong> can do 8x 8-bit elements in a 64-bit integer with a 0x0101010101010101 multiplier, and extract the high byte with <code>&gt;&gt;56</code>. So it doesn't take any extra steps, just wider constants. This is what GCC uses for <code>__builtin_popcountll</code> on x86 systems when the hardware <code>popcnt</code> instruction isn't enabled. If you can use builtins or intrinsics for this, do so to give the compiler a chance to do target-specific optimizations.</p> <hr /> <h3>With full SIMD for wider vectors (e.g. counting a whole array)</h3> <p>This bitwise-SWAR algorithm could parallelize to be done in multiple vector elements at once, instead of in a single integer register, for a speedup on CPUs with SIMD but no usable popcount instruction. (e.g. x86-64 code that has to run on any CPU, not just Nehalem or later.)</p> <p>However, the best way to use vector instructions for popcount is usually by using a variable-shuffle to do a table-lookup for 4 bits at a time of each byte in parallel. (The 4 bits index a 16 entry table held in a vector register).</p> <p>On Intel CPUs, the hardware 64bit popcnt instruction can outperform an <a href="http://wm.ite.pl/articles/sse-popcount.html" rel="nofollow noreferrer">SSSE3 <code>PSHUFB</code> bit-parallel implementation</a> by about a factor of 2, but only <a href="http://danluu.com/assembly-intrinsics/" rel="nofollow noreferrer">if your compiler gets it just right</a>. Otherwise SSE can come out significantly ahead. Newer compiler versions are aware of the <a href="https://stackoverflow.com/a/25089720/224132">popcnt false dependency</a> <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011" rel="nofollow noreferrer">problem on Intel</a>.</p> <ul> <li><a href="https://github.com/WojciechMula/sse-popcount" rel="nofollow noreferrer">https://github.com/WojciechMula/sse-popcount</a> state-of-the-art x86 SIMD popcount for SSSE3, AVX2, AVX512BW, AVX512VBMI, or AVX512 VPOPCNT. Using Harley-Seal across vectors to defer popcount within an element. (Also ARM NEON)</li> <li><a href="https://stackoverflow.com/questions/50081465/counting-1-bits-population-count-on-large-data-using-avx-512-or-avx-2">Counting 1 bits (population count) on large data using AVX-512 or AVX-2</a></li> <li>related: <a href="https://github.com/mklarqvist/positional-popcount" rel="nofollow noreferrer">https://github.com/mklarqvist/positional-popcount</a> - separate counts for each bit-position of multiple 8, 16, 32, or 64-bit integers. (Again, x86 SIMD including AVX-512 which is really good at this, with <code>vpternlogd</code> making Harley-Seal <em>very</em> good.)</li> </ul>
<pre><code>// How about the following: public int CountBits(int value) { int count = 0; while (value &gt; 0) { if (value &amp; 1) count++; value &lt;&lt;= 1; } return count; } </code></pre>
13,428
<p>Now this is .NET but I am sure the principal should apply to all OOP language, to simplify I take .NET as an example:</p> <p>R# usually creator constructor and passing incoming variable to private field, which for me mi tend to pass it to Property. </p> <p>Any opinion on how the different and what is the best practice for that?</p>
<p>Using properties is OK as long as they are not virtual/overridden. Properties are essentially methods, and you should not call virtual methods from within the constructor because the appropriate type may not be constructed yet. Microsoft has listed their own <a href="http://msdn.microsoft.com/en-us/library/ms229060.aspx" rel="nofollow noreferrer">set of guidelines</a>, just scroll down to the bottom to see the relevant guidance and code snippet illustrating the problem (they illustrate it using methods, but as I mentioned .NET properties are essentially special methods). </p>
<p>I manipulate fields inside the constructor. Fields really represent the inherent state of your object, and the constructor job is to initialize this internal state. Properties are just here for encapsulation purpose, and are a part of the public interface to the object state.</p> <p>The transformation logic you apply to the constructor arguments or to the properties input values before setting the internal state of the object could be very different. Anyway, if it is the case, I used to use an explicit transformation method called from the property setter and from the constructor, instead of directly chaining constructor on the property setter.</p> <p>If there is no logic at all, I can't see why you would like to use property setter inside constructor.</p>
15,960
<p>A link that stands out is <a href="http://www.devdaily.com/blog/post/jfc-swing/handling-main-mac-menu-in-swing-application/" rel="noreferrer">http://www.devdaily.com/blog/post/jfc-swing/handling-main-mac-menu-in-swing-application/</a> however the menu bar under Mac OS X displays as the package name as opposed to the application name. I'm using the code in the above link without any luck, so I'm unsure if anything's changed in recent Mac OS versions.</p> <p>Here's an extract:</p> <blockquote> <pre><code>public RootGUI() { super("Hello"); JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); JMenuItem item = new JMenuItem("Woah"); file.add(item); menuBar.add(file); setJMenuBar(menuBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(100, 100); pack(); setVisible(true); } </code></pre> </blockquote> <pre><code>public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { try { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); new RootGUI(); } catch(ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e.getMessage()); } catch(InstantiationException e) { System.out.println("InstantiationException: " + e.getMessage()); } catch(IllegalAccessException e) { System.out.println("IllegalAccessException: " + e.getMessage()); } catch(UnsupportedLookAndFeelException e) { System.out.println("UnsupportedLookAndFeelException: " + e.getMessage()); } } }); } </code></pre> <p>The first menu item on the menu bar should display as "test", unfortunately this isn't the case. The file menu works fine, on the other hand. Any ideas?</p>
<p>@Kezzer</p> <p>I think I see what's going on. If you put the main() method in a <em>different class</em>, then everything works. So you need something like:</p> <pre><code>public class RootGUILauncher { public static void main(String[] args) { try { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e.getMessage()); } catch(InstantiationException e) { System.out.println("InstantiationException: " + e.getMessage()); } catch(IllegalAccessException e) { System.out.println("IllegalAccessException: " + e.getMessage()); } catch(UnsupportedLookAndFeelException e) { System.out.println("UnsupportedLookAndFeelException: " + e.getMessage()); } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new RootGUI(); } }); } </code></pre> <p>And then put your RootGUI class in a different file.</p>
<p>If you want to deliver an application that looks native on Mac OS X, one important part is to deliver an appplication bundle. Within the application bundle, you will be able to provide a property list file in order to solve this problems.</p> <p>Some official info: <a href="http://developer.apple.com/documentation/Java/Conceptual/Java14Development/07-NativePlatformIntegration/NativePlatformIntegration.html#//apple_ref/doc/uid/TP40001909-SW1" rel="nofollow noreferrer">Java Development Guide for Mac OS X</a></p>
39,505
<p>If I have a source.c file with a struct:</p> <pre><code>struct a { int i; struct b { int j; } }; </code></pre> <p>How can this struct be used in another file (i.e. <code>func.c</code>)?</p> <p>Should I create a new header file, declare the struct there and include that header in <code>func.c</code>?</p> <p>Or should I define the whole struct in a header file and include that in both <code>source.c</code> and <code>func.c</code>? How can the struct be declared <code>extern</code> in both files?</p> <p>Should I <code>typedef</code> it? If so, how?</p>
<h3>if this structure is to be used by some other file func.c how to do it?</h3> <p>When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.</p> <p>The right way is putting it in an header file, and include this header file whenever needed.</p> <h3>shall we open a new header file and declare the structure there and include that header in the func.c?</h3> <p>This is the solution I like more, because it makes the code highly modular. I would code your struct as:</p> <pre><code>#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME #define SOME_HEADER_GUARD_WITH_UNIQUE_NAME struct a { int i; struct b { int j; } }; #endif </code></pre> <p>I would put functions using this structure in the same header (the function that are &quot;semantically&quot; part of its &quot;interface&quot;).</p> <p>And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.</p> <p>If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:</p> <pre><code>struct a ; </code></pre> <p>Will be enough, and it decreases coupling.</p> <h3>or can we define the total structure in header file and include that in both source.c and func.c?</h3> <p>This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.</p> <p>In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.</p> <h3>then how to declare that structure as extern in both the files. ?</h3> <p>I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post <a href="https://stackoverflow.com/questions/228684/how-to-declare-a-structure-in-a-header-that-is-to-be-used-by-multiple-files-in-c#228691">How to declare a structure in a header that is to be used by multiple files in c?</a>.</p> <h3>shall we typedef it then how?</h3> <ul> <li>If you are using C++, don't.</li> <li>If you are using C, you should.</li> </ul> <p>The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:</p> <pre><code>struct MyStruct ; /* Forward declaration */ struct MyStruct { /* etc. */ } ; void doSomething(struct MyStruct * p) /* parameter */ { struct MyStruct a ; /* variable */ /* etc */ } </code></pre> <p>While a typedef will enable you to write it without the struct keyword.</p> <pre><code>struct MyStructTag ; /* Forward declaration */ typedef struct MyStructTag { /* etc. */ } MyStruct ; void doSomething(MyStruct * p) /* parameter */ { MyStruct a ; /* variable */ /* etc */ } </code></pre> <p>It is <strong>important</strong> you still keep a name for the struct. Writing:</p> <pre><code>typedef struct { /* etc. */ } MyStruct ; </code></pre> <p>will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:</p> <pre><code>typedef struct MyStructTag { /* etc. */ } MyStruct ; </code></pre> <p>Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)</p> <h3>Edit:</h3> <p>Corrected wrong assumption about C99 struct declaration, as rightfully remarked by <a href="https://stackoverflow.com/users/15168/jonathan-leffler">Jonathan Leffler</a>.</p> <h3>Edit 2018-06-01:</h3> <p><a href="https://stackoverflow.com/users/1471119/craig-barnes">Craig Barnes</a> reminds us in his comment that you don't need to keep separate names for the struct &quot;tag&quot; name and its &quot;typedef&quot; name, like I did above for the sake of clarity.</p> <p>Indeed, the code above could well be written as:</p> <pre><code>typedef struct MyStruct { /* etc. */ } MyStruct ; </code></pre> <p>IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:</p> <pre><code>// C++ explicit declaration by the user struct MyStruct { /* etc. */ } ; // C++ standard then implicitly adds the following line typedef MyStruct MyStruct; </code></pre> <p>Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use <a href="https://stackoverflow.com/questions/3793952/">C separate &quot;namespaces&quot; for structs and other symbols</a>.</p>
<p>a.h:</p> <pre><code>#ifndef A_H #define A_H struct a { int i; struct b { int j; } }; #endif </code></pre> <p>there you go, now you just need to include a.h to the files where you want to use this structure.</p>
28,301
<p>I have problems with Boost.Spirit parsing a string. </p> <p>The string looks like </p> <pre><code>name1 has this and that.\n name 2 has this and that.\n na me has this and that.\n </code></pre> <p>and I have to extract the names. The text "has this and that" is always the same but the name can consist of spaces therefore I can't use graph_p. </p> <p>1) How do I parse such a string?</p> <p>Since the string has several lines of that format I have to store the names in a vector. </p> <p>I used something like </p> <pre><code>std::string name; rule&lt;&gt; r = *graph_p[append(name)]; </code></pre> <p>for saving one name but </p> <p>2) what's the best way to save several names in a vector?</p> <p>Thanks in advance</p> <p>Konrad</p>
<p>I think this will do the trick:</p> <pre><code>vector&lt;string&gt; names; string name; parse(str, *( (*(anychar_p - "has this and that.")) [assign_a(name)] &gt;&gt; "has this and that.\n") [push_back_a(names, name)] )) </code></pre>
<p>I presume there is a reason why you are using <a href="http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/index.html" rel="nofollow noreferrer">Boost.Spirit</a> and not <a href="http://www.sgi.com/tech/stl/table_of_contents.html" rel="nofollow noreferrer">STL</a>'s <a href="http://www.cplusplus.com/reference/string/string/" rel="nofollow noreferrer">string</a>'s <a href="http://www.cplusplus.com/reference/string/string/find.html" rel="nofollow noreferrer">find</a> method? E.g:</p> <pre><code>string s = "na me has this and that.\n"; myVector . push_back( s.substr( 0, s.find( "has this and that" ) ) ); </code></pre>
47,710
<p>I've recently used our company's spare laptop (that has a general user set up) while mine was being repaired. I've checked the "Remember password" option in SQL Server Management Studio when logging in to the database. </p> <p>I need to clear the login and password information that I have used to prevent the next person that will use the laptop from using my login names and passwords. How can I do this?</p>
<p>Another answer here also mentions since 2012 you can remove Remove cached login via <a href="https://stackoverflow.com/questions/10993861/how-to-remove-cached-server-names-from-the-connect-to-server-dialog">How to remove cached server names from the Connect to Server dialog?</a>. Just confirmed this delete in MRU list works fine in 2016 and 2017.</p> <p>SQL Server Management Studio <strong>2017</strong> delete the file <code>C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin</code></p> <p>SQL Server Management Studio <strong>2016</strong> delete the file <code>C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin</code></p> <p>SQL Server Management Studio <strong>2014</strong> delete the file <code>C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin</code></p> <p>SQL Server Management Studio <strong>2012</strong> delete the file <code>C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin</code></p> <p>SQL Server Management Studio <strong>2008</strong> delete the file <code>C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin</code></p> <p>SQL Server Management Studio <strong>2005</strong> delete the file – same as above answer but the Vista path. <code>C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat</code></p> <p>These are profile paths for Vista / 7 / 8.</p> <p>EDIT:</p> <p>Note, <code>AppData</code> is a hidden folder. You need to show hidden folders in explorer.</p> <p>EDIT: You can simply press delete from the Server / User name drop down (confirmed to be working for SSMS v18.0). Original source from <a href="https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/" rel="noreferrer">https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/</a> which mentioned that this feature is available since 2012!</p>
<p>Select the Login drop down arrow. Delete the users from the list</p>
45,496
<p>I'm a CompSci student, and fairly new at C#, and I was doing a "Josephus Problem" program for a class, and I created an Exit button that calls Application.Exit() to exit at anytime, but if C# is still working on painting and the button is pressed it throws an ObjectDisposedExeception for the Graphics object. Is there any way to prevent this?. I was thinking of try{}catch or change a boolean to tell the painting process to stop before exiting, but I want to know if there's another solution.</p>
<p>You should be called the Close() method of the Form that contains the button in order to close down the form in an orderly manner. Closing the main form will cause the application to exit for you anyway.</p>
<p>You should be called the Close() method of the Form that contains the button in order to close down the form in an orderly manner. Closing the main form will cause the application to exit for you anyway.</p>
11,599
<p>How do I make an array shorter in Perl? I read some webpages indicating that I can assign:</p> <pre><code>$#ARRAY = 42; </code></pre> <p>I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work:</p> <pre><code>$#$ARRAY[$i] = 42; </code></pre>
<p>I'm not aware of assigning <code>$#ARRAY</code> being deprecated; <code>perldoc perldata</code> from 5.10.0 certainly says nothing about it. It is the fastest way to truncate an array.</p> <p>If you want something a little more readable, use <code>splice</code>:</p> <pre><code>splice @ARRAY, 43; </code></pre> <p>(Note <code>43</code> instead of <code>42</code> - <code>$#ARRAY</code> gets you the last index of the array, whereas <code>splice</code> taks the <em>length</em> of the array instead).</p> <p>As for working on arrays of arrays, I assume you mean being able to truncate a nested array via a reference? In that case, you want:</p> <pre><code>$#{$ARRAY-&gt;[7]} = 42; </code></pre> <p>or</p> <pre><code>splice @{$ARRAY-&gt;[7]}, 43; </code></pre>
<p>$#{$ARRAY[$i]} = 42;</p>
11,835
<p>How to represent the start and end times for one day?</p> <p>Using October 23, 2008 as an example, is it start 2008-10-23 12:00:00 AM and end 2008-10-23 11:59:59 PM?</p>
<p>I would like to cite a site, <a href="http://www.cl.cam.ac.uk/~mgk25/iso-time.html" rel="noreferrer">http://www.cl.cam.ac.uk/~mgk25/iso-time.html</a></p> <p>The international standard notation for the time of day is</p> <pre><code>hh:mm:ss </code></pre> <p>where hh is the number of complete hours that have passed since midnight (00-24), mm is the number of complete minutes that have passed since the start of the hour (00-59), and ss is the number of complete seconds since the start of the minute (00-60). If the hour value is 24, then the minute and second values must be zero.</p> <p>Note: The value 60 for ss might sometimes be needed during an inserted leap second in an atomic time scale like Coordinated Universal Time (UTC). A single leap second 23:59:60 is inserted into the UTC time scale every few years as announced by the International Earth Rotation Service in Paris, to keep UTC from wandering away more than 0.9 s from the less constant astronomical time scale UT1, which is defined by the actual rotation of the earth. In practice you are not very likely to see a clock showing 23:59:60. Most synchronized clocks resynchronize again to UTC some time after a leap second has happened, or they temporarily slow down near the time of a leap seconds, to avoid any disruption that an out-of-range timestamp might otherwise cause.</p> <p>An example time is</p> <pre><code>23:59:59 </code></pre> <p>which represents the time one second before midnight.</p> <p>As with the date notation, the separating colons can also be omitted as in</p> <pre><code>235959 </code></pre> <p>and the precision can be reduced by omitting the seconds or both the seconds and minutes as in</p> <pre><code>23:59, 2359, or 23 </code></pre> <p>It is also possible to add fractions of a second after a decimal dot or comma, for instance the time 5.8 ms before midnight can be written as</p> <pre><code>23:59:59.9942 or 235959.9942 </code></pre> <p>As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time:</p> <pre><code>1995-02-04 24:00 = 1995-02-05 00:00 </code></pre> <p>In case an unambiguous representation of time is required, 00:00 is usually the preferred notation for midnight and not 24:00. Digital clocks display 00:00 and not 24:00.</p> <p>ISO 8601 does not specify, whether its notations specify a point in time or a time period. This means for example that ISO 8601 does not define whether 09:00 refers to the exact end of the ninth hour of the day or the period from 09:00 to 09:01 or anything else. The users of the standard must somehow agree on the exact interpretation of the time notation if this should be of any concern.</p> <p>If a date and a time are displayed on the same line, then always write the date in front of the time. If a date and a time value are stored together in a single data field, then ISO 8601 suggests that they should be separated by a latin capital letter T, as in 19951231T235959.</p> <p>A remark for readers from the U.S.:</p> <p>The 24h time notation specified here has already been the de-facto standard all over the world in written language for decades. The only exception are a few English speaking countries, where still notations with hours between 1 and 12 and additions like “a.m.” and “p.m.” are in wide use. The common 24h international standard notation is widely used now even in England (e.g. at airports, cinemas, bus/train timetables, etc.). Most other languages do not even have abbreviations like “a.m.” and “p.m.” and the 12h notation is certainly hardly ever used on Continental Europe to write or display a time. Even in the U.S., the military and computer programmers have been using the 24h notation for a long time.</p> <p>The old English 12h notation has many disadvantages like:</p> <ul> <li>It is longer than the normal 24h notation.</li> <li>It takes somewhat more time for humans to compare two times in 12h notation.</li> <li>It is not clear, how 00:00, 12:00 and 24:00 are represented. Even encyclopedias and style manuals contain contradicting descriptions and a common quick fix seems to be to avoid “12:00 a.m./p.m.” altogether and write “noon”, “midnight”, or “12:01 a.m./p.m.” instead, although the word “midnight” still does not distinguish between 00:00 and 24:00 (midnight at the start or end of a given day).</li> <li>It makes people often believe that the next day starts at the overflow from “12:59 a.m.” to “1:00 a.m.”, which is a common problem not only when people try to program the timer of VCRs shortly after midnight.</li> <li>It is not easily comparable with a string compare operation.</li> <li>It is not immediately clear for the unaware, whether the time between “12:00 a.m./p.m.” and “1:00 a.m./p.m.” starts at 00:00 or at 12:00, i.e. the English 12h notation is more difficult to understand.</li> </ul> <p>Please consider the 12h time to be a relic from the dark ages when Roman numerals were used, the number zero had not yet been invented and analog clocks were the only known form of displaying a time. Please avoid using it today, especially in technical applications! Even in the U.S., the widely respected Chicago Manual of Style now recommends using the international standard time notation in publications.</p>
<p>The definition of the day you mention in the question is any time that is >= 2008-10-23 00:00:00 and &lt; 2008-10-24 00:00:00 .</p>
26,781
<p>What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.</p> <p>3.5 would return 4 for power of 2 and 1 for power of 10</p> <p>123 would return 128 for power of 2 and 100 for power of 10</p> <p>0.24 would return 0.25 for power of 2 and 0.1 for power of 10</p> <p>I'm just looking for the algorithm and don't mind the language.</p>
<pre><code>n^round(log_n(x)) </code></pre> <p>where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".</p> <p>Note that <code>log_n(x)</code> can be implemented as:</p> <pre><code>log_n(x) = log(x) / log(n) </code></pre> <p>where <code>log</code> is a logarithm to any convenient base.</p>
<p>I think that I might approach the problem, but using log base 2 and log base 10.</p> <p>log10 of (123) is 2.something. take the floor of that then raise 10 to that power, and that ought to get you close.</p> <p>the same thing ought to work with log base 2.</p> <p>log2 of (9) is 3.something take the floor of that then raise to to that power</p> <p>you might play with rounding of the log.</p>
33,074
<p>I committed a bunch of files (dozens of files in different folders) by accident. What is the easiest, cleanest (and safest!) way to 'undo' that commit without having to delete the files from my working directory?</p>
<p>Go to <strong>Show Log</strong> Screen, select the revision that you want to undo, right click it and select <strong>Revert changes from this revision</strong>, this will do a <a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo" rel="noreferrer">reverse-merge</a>.</p>
<p>You can revert your working copy to the revision prior to the commit. Once you have reverted your working copy, then simply commit the changes and you will effectively rolled back the accidental commit.</p> <p>In a case like yours specifically, I would probably check out the revision that I wanted to roll back into a new working copy and then commit the working copy to the head revision.</p>
30,923
<p>How to implement a website with a recommendation system similar to stackoverflow/digg/reddit? I.e., users submit content and the website needs to calculate some sort of "hotness" according to how popular the item is. The flow is as follows:</p> <ul> <li>Users submit content</li> <li>Other users view and vote on the content (assume 90% of the users only views content and 10% actively votes up or down on content)</li> <li>New content is continuously submitted</li> </ul> <p>How do I implement an algorithm that calculates the "hotness" of a submitted item, preferably in real-time? Are there any best-practices or design patterns?</p> <p>I would assume that the algorithm takes the following into consideration:</p> <ul> <li>When an item was submitted</li> <li>When each vote was cast</li> <li>When the item was viewed</li> </ul> <p>E.g. an item that gets a constant trickle of votes would stay somewhat "hot" constantly while an item that receives a burst of votes when it is first submitted will jump to the top of the "hotness"-list but then fall down as the votes stop coming in.</p> <p>(I am using a MySQL+PHP but I am interested in general design patterns).</p>
<p>You could use something similar to the <a href="http://redflavor.com/reddit.cf.algorithm.png" rel="noreferrer">Reddit algorithm</a> - the basic principle of which is you compute a value for a post based on the time it was posted and the score. What's neat about the Reddit algorithm is that you only need recompute the value when the score of a post changes. When you want to display your front page, you just get the top n posts from your database based on that score. As time goes on the scores will naturally increase, so you don't have to do any special processing to remove items from the front page.</p>
<p>I developed an social bookmarking site, <a href="http://www.sites-favoritos.com" rel="nofollow noreferrer">Sites Favoritos</a>, and used a complex algoritm:</p> <ol> <li>First, the votes are finite, an user only have a limited number of votes, and the number of votes depends on the user points. To earn points each user must add links that get positive votes.</li> <li>Then, users can vote -3,-2,-1,1,2 or 3 votes for each link. As the votes are limited, each user will vote only on those links that they like.</li> <li>To prevent user to vote only on links for the same user, creating support groups, the points each vote adds to the link depends on a racio between total votes and votes to links of the owner of the voted link. If you always vote on the same users links, your votes will lose value.</li> <li>Votes lose value with time.</li> <li>New links from users who don't have points (new users) will have a starting 0 points. New links from older users will have points depending on their points. Ranging from +3 to -infinite. Links from users with negative points will have negative starting points, links from users with positive points will have positive starting points.</li> </ol> <p>Users will get random points when their links are voted. Positive votes give positive points, negative votes for negative points.</p>
9,747
<p>I'm going to be implementing a <code>PHP/mySQL</code> setup to store credit card information.</p> <p>It seems like <code>AES_ENCRYPT/AES_DECRYPT</code> is the way to go,</p> <p><strong>but I'm still confused on one point:</strong></p> <p><strong>How do I keep the encryption key secure?</strong></p> <p>Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole.</p> <p><strong>What's the &quot;best practice&quot; solution here?</strong></p>
<p>You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears. After that, delete it.</p> <p>As far as securing the server, the best course of action is to secure the hardware and use the internal system socket to MySQL, and make sure to block any network access to the MySQL server. Make sure you're using both your system permissions and the MySQL permissions to allow as little access as needed. For some scripts, you might consider write-only authentication. There's really no encryption method that will be foolproof (as you will always need to decrypt, and thus must store the key). This is not to say you shouldn't - you can store your key in one location and if you detect system compromise you can destroy the file and render the data useless.</p>
<p>I agree, but don't the cc if you don't need too. But if you really have too, make sure the file that have it is not accessible on the web. You can write a binary that would return the key. This way it's not store in clear text. But if your server is compromise it's still easy to get it. </p>
7,947
<p>I have created a custom dialog for Visual Studio Setup Project using the steps described <a href="http://www.codeproject.com/KB/install/vsSetupCustomDialogs.aspx?fid=419622&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2640482&amp;fr=26" rel="nofollow noreferrer">here</a></p> <p>Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list ... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner :).</p>
<p>I've always found the custom dialogs in visual studio setup projects to be woefully limited and barely functional.</p> <p>By contrast, I normally create custom actions that display winforms gui's for any remotely difficult tasks during setup. Works really well and you can do just about anything you want by creating a custom action and passing a few parameters across.</p> <p>In the dayjob we built a collection of common custom actions for tasks like application config and database creation / script execution to get around custom dialog limitations.</p>
<p>I guess you'll have to go beyond the out-of-the-box setup and deployment package and try a third party app.</p> <p>You may want to look at:</p> <ul> <li><a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">Wix</a></li> <li><a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow noreferrer">Nullsoft Scriptable Install System</a></li> </ul> <p>Both are free; they might give you the customization that you need.</p>
3,256
<ol> <li>Specifically getting on Windows the "..\Documents &amp; Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. <strong>(Now I need the answer to this)</strong></li> <li>the current users My Documents dirctory <strong>(okay this has been answered)</strong> and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.</li> </ol>
<p>My docs would probably best be handled by accessing:</p> <pre><code>System.getProperty("user.home"); </code></pre> <p>Look up the docs on <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html" rel="noreferrer">System.getProperty</a>.</p>
<blockquote> <p>Specifically getting on Windows the "..\Documents &amp; Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)</p> </blockquote> <p>The folders below the All Users dir are variable directories in windows. Details can be found in the document about <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457%28v=vs.85%29.aspx" rel="nofollow">KNOWNFOLDERIDs</a> (<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx" rel="nofollow">CSIDL</a> in older versions). Because this values are system dependent Java does not provide a way to access the values.</p> <p>I think there is in general no equivalent on other operating systems to this windows specific folder. In addition the folder Documents &amp; Settings\All Users is only present in latest windows versions and things are handled differently for e.g Windows 2000 or XP I think.</p> <p>If you really need this information you should read the microsoft docs and impement a native library or some script invoked by Runtime.exec to provide the information to your java application.</p>
5,788
<p>Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper.</p> <p>I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome.</p> <p>(Yes I know Mr. Joel is on the stackoverflow team... I still want good answers :)</p>
<p>I use it, especially since the hosted Version of FugBugz <a href="https://stackoverflow.com/questions/3180/anyone-soloing-using-fogbugz#3581">is free for up to 2 people</a>. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all...</p> <p>Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it.</p> <p>But that is just the point of view from someone who is not really good at staying organized :-) If you are a really tidy and organized person, paper may work better for you than it does for me.</p> <p>Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.</p>
<p>Yea FogBugz is great for process-light, quick and easy task management. It seems especially well suited for soloing, where you don't need or want a lot of complexity in that area. </p> <p>By the way, if you want to keep track of what you're doing at the computer all day, check out TimeSprite, which integrates with FogBugz. It's a Windows app that logs your active window and then categorizes your activity based on the window title / activity type mappings you define as you go. (You can also just tell it what you're working on.) And if you're a FogBugz user, you can associate your work with a FogBugz case, and it will upload your time intervals for that case. This makes accurate recording of elapsed time pretty painless and about as accurate as you can get, which in turn improves FogBugz predictive powers in its evidence-based scheduling. Also, when soloing, I find that such specific logging of my time keeps me on task, in the way a meandering manager otherwise might. (I'm not affiliated with TimeSprite in any way.)</p>
2,536
<p>How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? </p> <p>I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question. </p>
<p>You're almost certainly missing something. A lot of things, probably. Don't worry, it's ok. Even if you remembered everything and covered all the bases stakeholders aren't going to be able to give you very good, clear requirements without any point of reference. The best way to do this sort of thing is to get what you can from them now, then take that and give them something to react to. It can be a paper prototype, a mockup, version 0.1 of the software, whatever. Then they can start telling you what they really want. </p>
<p>I recently started using the concepts, standards and templates defined by the <a href="http://www.theiiba.org" rel="nofollow noreferrer">International Institute of Business Analysts</a> organization (<a href="http://www.theiiba.org" rel="nofollow noreferrer">IIBA</a>). </p> <p>They have a pretty good BOK (Book of Knowledge) that can be downloaded from their website. They do also have a certificate.</p>
4,878
<p>I have a table with a 'filename' column. I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.</p> <p>How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?</p>
<p>The solution is:</p> <pre><code>UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id &gt; 50 </code></pre> <p>RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.</p>
<p>If the original data came from a char column or variable (before being inserted into this table), then the original data had the spaces appended before becoming a varchar.</p> <pre><code>DECLARE @Name char(10), @Name2 varchar(10) SELECT @Name = 'Bob', @Name2 = 'Bob' SELECT CASE WHEN @Name2 = @Name THEN 1 ELSE 0 END as Equal, CASE WHEN @Name2 like @Name THEN 1 ELSE 0 END as Similiar </code></pre> <p>Life Lesson : never use char.</p>
3,822
<p>I've been programming for 10+ years now for the same employer and only source code control we've ever used is VSS. (Sorry - That's what they had when I started). There's only ever been a few of us; two right now and we usually work alone, so VSS has worked ok for us. So, I have two questions: 1) Should we switch to something else like subversion, git, TFS, etc what exactly and why (please)? 2) Am I beyond all hope and destined to eternal damnation because VSS has corrupted me (as Jeff says) ?</p> <p>Wow - thanks for all the great responses! </p> <p>It sounds like I should clearify a few things. We are a MS shop (Gold parntner) and we mostly do VB, ASP.NET, SQL Server, sharepoint &amp; Biztalk work. I have CS degree so I've done x86 assembly C, C++ on DEC Unix and Slackware Linux in a "time out of mind" ... </p> <p>My concern with VSS is that now I'm working over a VPN a lot more and VSS's performance sux and I'm afraid that our 10+ y/o version 5 VSS database is going to get hoosed... There's the LAN service that's supposed to speed things up, but Ive never used it and I'm not sure it helps with corruption - has anyone used the VSS LAN service? (new with VSS 2005) </p>
<p>I'd probably go with Subversion, if I were you. I'm a total Git fanatic at this point, but Subversion certainly has some advantages: </p> <ul> <li>simplicity</li> <li>abundance of interoperable tools</li> <li>active and supportive community</li> <li>portable</li> <li>Has really nice Windows shell integration</li> <li>integrates with visual studio (I think - but surely through a third party)</li> </ul> <p>Git has many, many other advantages, but the above tend to be the ones people care about when asking general questions like the above.</p> <p><strong>Edit</strong>: the company I now work for is using VisualSVN server, which is free. It makes setting up a Subversion repository on a Windows server stupid simple, and on the client we're using TortoiseSVN (for shell integration) and AnkhSVN for Visual Studio support. It's quite good, and should be fairly easy for even VSS users to pick up.</p> <p><strong>Latter-day Edit</strong>: So....nearly eight years later, I would never recommend Subversion to anyone for any reason. I don't really recant, <em>per se</em>, because I think my advice was valid at the time. However, in 2016, Subversion retains almost none of the advantages it used to have over Git. The tooling for Git is superior to (and much more diverse) what it once was, and in particular, there's GitHub and other good Git hosting providers (BitBucket, Beanstalk, Visual Studio Online, just off the top of my head). Visual Studio now has Git support out-of-the-box, and it's actually pretty good. There are even PowerShell modules to give a more native Windows experience to denizens of the console. Git is even easier to set up and use than Subversion and doesn't require a server component. Git has become as ubiquitous as any single tool can be, and you really would only be cheating yourself to not use it (unless you just really want to use something not-Git). Don't misunderstand - this isn't me hating on Subversion, but rather me recognizing that it's a tool from another time, rather like a straight razor for shaving. </p>
<p>I'd say stick with what works for you. Unless you are having issues with VSS, why switch? Subversion is swell, though a little sticky to begin using it. TFS is far better than VSS, though it is fairly expensive for such a small team. I have not used git so I can't really speak to it.</p>
5,158
<p>Is there a way to step through a .bat script? The thing is, I have a build script , which calls a lot of other scripts, and I would like to see what is the order in which they are called, so that I may know where exactly I have to go about and add my modifications.</p>
<p>I don't know of anyway to step through the execution of a .bat file but you can use <code>echo</code> and <code>pause</code> to help with debugging.</p> <blockquote> <p><strong>ECHO</strong><br> Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.</p> <p><strong>PAUSE</strong><br> Prompt the user to press any key to continue.</p> </blockquote> <p>Source: <a href="http://www.computerhope.com/batch.htm" rel="noreferrer">Batch File Help</a></p> <p>@workmad3: answer has more good tips for working with the <code>echo</code> command.</p> <p>Another helpful resource... <a href="http://www.chebucto.ns.ca/~ak621/DOS/Bat-Tips.html" rel="noreferrer">DDB: DOS Batch File Tips</a></p>
<p>or, open a cmd window, then call the batch from there, the output will be on the screen.</p>
20,038
<p>Our company is looking to integrate invoices into a new system we are developing.</p> <p>We require a solution to create a layout of the invoice and then convert to pdf.</p> <p>We have considered just laying out the invoice in html/css then converting to pdf. We have also considered using SVG->PDf conversion.</p> <p>Both of these solutions integrate well into our existing templating language used for our web application.</p> <p>Historically we have been a Microsoft based business and used Crystal Reports for such a task but we are looking for an open source Linux solution for this project.</p> <p>Does any one have any suggestions of an approach or technology we could use for such a task?</p>
<p>Try this... create a blank invoice with Word (or whatever you want) and save it as a PDF.</p> <p>Then use a PDF library to modify the PDF (insert the text at particular coordinates). We do this in the Microsoft world and it is extremely easy.</p> <p>The biggest benefit is that we can use our own tools to create and modify the template. If we want to add some static text, we just crank open Word, make the change and save it to a PDF file (that is being used as a template).</p> <p>For Microsoft, we use <a href="http://sourceforge.net/projects/itextsharp/" rel="noreferrer">iTextSharp</a> which is actually a C# port of the original <a href="http://www.lowagie.com/iText/docs.html" rel="noreferrer">Java version of iText</a></p> <hr> <p>Additionally...</p> <p>You can use Adobe Acrobat to insert fields in the PDF (address, phone, invoice number, line item 1, line item 2, etc...) and then use iText/iTextSharp to populate these fields at run time. </p> <p>This is, in more detail, what we do... and it is extremely easy.</p>
<p>This html-2-pdf site may be a helpful starting point: <a href="http://maarten.lippmann.us/?p=101" rel="nofollow noreferrer">http://maarten.lippmann.us/?p=101</a></p> <p>A site a friend of mine built uses a script to churn HTML pages into printable PDFs, too - <a href="http://philambdaupsilon.org" rel="nofollow noreferrer">http://philambdaupsilon.org</a>. Not sure on the exact details of it, but he is an SO user, and I'll send this question to him, too.</p>
34,033
<p>For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="noreferrer">Builder pattern</a> in <em>Effective Java</em> that is kinda the same).</p> <p>Basically, all setter methods return the object itself so then you can use code like this:</p> <pre><code>myClass .setInt(1) .setString(&quot;test&quot;) .setBoolean(true); </code></pre> <p>Setters simply return this in the end:</p> <pre><code>public MyClass setInt(int anInt) { // [snip] return this; } </code></pre> <p>What is your opinion? What are the pros and cons? Does this have any impact on performance?</p> <p>Also referred to as the <a href="http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-parameter-idiom.html" rel="noreferrer">named parameter idiom</a> in c++.</p>
<p>@pek<br/> Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return <strong>this</strong>. If you're interested in this topic, there is a bunch of links and a simple example on <a href="http://tech.puredanger.com/java7#chained" rel="noreferrer">Alex Miller's Java 7 page</a>.</p>
<p>I agree with @Bernard that method chaining like this muddles the purpose of the setters. Instead I would suggest that if you are always creating chains of setters like this that you create a custom Constructor for your class so instead of</p> <pre><code> MyClass .setInt(1) .setString("test") .setBoolean(true) ; </code></pre> <p>You do</p> <pre><code>new MyClass(1,"test",true); </code></pre> <p>This makes it more readable and you can use this to make your class immutable if you chose to.</p>
5,155
<p>After reading E-myth Revisited, I realize that I can do a better job at making my company less reliant upon me... I spend a tremendous amount of time answering silly questions (silly to me, but necessary for my developers to get the job done).</p> <p>I need to write a set of operating manuals for what to do in certain situations...</p> For instance: <ul> <li>How to make a build</li> <li>How to write test cases</li> <li>How to report status</li> <li>How to fix a bug</li> <li>How to handle support question A, B, C, etc...</li> <li>What to do when you are stalled</li> <li>What to do when the power goes out (really, I need to do this)</li> <li>etc...</li> </ul> <p>What are some useful, generic operating manuals that you can think of, for a software development company?And please, if you have some good, short, online versions that you know of, please post them. I would much rather use a starter manual and modify it for my needs, than start from scratch.</p>
<p>What about a wiki - at least then other people can start to contribute.<br> Otherwise they are just going to rely on you for the manuals</p>
<p>I disagree with the wiki. As the owner of the company -- it is your responsibility to write the manuals, or delegate it in a very controlled fashion. People <em>should</em> rely on you for the manuals.</p> <p>Really though, back to the question. The obvious standards, coding, SQL, etc for your platform and programming languages. You'll be able to find examples of these anywhere on the internet. As for customer support, you should probably write that yourself, you know how you want your customers treated. As for test cases, again, you'd have expect your developers or testers to have a professional understanding of what needs to be done, you might indicate the acceptable minimums however. </p> <p>What to do when you are stalled. That's what managers are for :-)</p> <p>I think it boils down to writing the manuals that are unique to your business, and trying to steal or borrow manuals for the generic processes.</p>
20,482
<p>I need a solution to catalog a number of applications in our company (more than 100 less than 1000). </p> <p>Right now we are using a spreadsheet and for each app we fill in name, short description, contact person and maintainer (internal or vendor). The puspose is to use this list for IT planning and incident management (impact estimation, etc.) In order to do this, as a minimum we need to start adding relations like 'depends on', 'part of' or 'supersedes'. It would be also useful if a future solution would allow tagging, adding indexed key-value pairs, comments and attachments to each entry.</p> <p>We will NOT want to discover all deployed instances of the applications, manage configuration settings, integrate monitoring have complex security settings and get burried in meta-meta-schemata. Anything that requires a dedicated administrator is already too heavy. </p> <p>We have the following non-functional requirements:</p> <ul> <li>Should allow multiple users to work concurrently on it</li> <li>Every change should be versioned</li> <li>Easy export to XML or some other easy to parse format</li> </ul> <p>So far we have considered the following:</p> <ul> <li>Put the spreadsheet on a Confluence wiki, where we can edit it via WebDav (and get locking and versioning)</li> <li>Use the Confluence wiki since it provides tagging, hierarchy, metadata and links. The only concern is that a wiki is too freeform and it may be difficult to extract the information should we decide to migrate to another system.</li> <li>DabbleDB.com - has everything we need, but unfortunately the data should not leave the firewall.</li> <li>OneCMDB.org - I am not sure how easy it is to capture ad-hock information and evolve the schema. Would appreciate experiences.</li> <li>Zenoss.com - haven't checked it yet. Looks too focused on network management.</li> <li>Lightweight registry (Mule Galaxy, WSO2 Registry) - not sure if this is the right tool for the job, though they offer a lot of the facilities we need (attributes, labels, versions, lifecycles).</li> <li>BMC Atrium - complex, corporate politics would require a number of unnecesarry procedures. Unless it offers some huge benefit, we'd rather stick with opensource.</li> </ul> <p>I'm interested on feedback/ideas from people that have successfully gone through a similar endeavor or have experience with some of the approaches above. Also, I would appreciate advice about common pitfalls and recommendations.</p>
<p>This is tailor-made for a nice, simple web-app framework. Pick your favorite framework. Define your simple data model for applications. Migrate your spreadsheet. Add your other relationships (depends-on, supersedes, part-of) and evolve your application.</p> <p>Any good web-app framework will have pleasant data mapping for this simple set of data.</p> <p>It's a good skill-builder. It can be a good Proof of Concept for introducing a new web application framework into an organization.</p> <hr> <p>It's hard to avoid "infrastructure" issues. A purpose-built asset management tool is -- generally -- large and complex. Even <a href="http://eam.calemeam.com/eam/" rel="nofollow noreferrer">CalemEAM</a> is rather complex.</p> <p>Since you have a lot of applications, I was guessing that you already had a web application framework and some skills in using it. From your comment, however, you make it sound like there is no preferred web app. framework. </p> <p>That causes me to guess that perhaps your 100's to 1000's of apps are a mixture of desktop software and web apps built with no consistent easy-to-live-with framework.</p> <p>I'm a python bigot, so I'm not familiar with any of the web frameworks you've suggested. The most important source of technical direction should be the folks that built these 100's to 1000's of apps -- what web framework are they using? Which one do they wish they were using? If they were starting a new project (like yours), which one would they use? </p> <p>You don't want to be the shoemaker's child -- the only one in the village with bare feet. You want your simple little asset management app (it only has 3 tables) to be built with the set of tools preferred by your organization.</p> <hr> <p>Okay, with 10% java and 50% vendor systems, there's no "preferred" web app framework. </p> <p>Choice 1: Pick a Java-based reasonably complete framework. Try using Struts and iBatis as a jumping-off point. Build the minimal tables, the minimlal iBatis mappings from POJO's to the tables. Define the minimal default forms -- one list, one detail for each table. Create the minimal administrative front-end for the minimal set of forms over the minimal set of tables. Write a minimal loader from your spreadsheet to your tables. </p> <p>Then delete the spreadsheet and never look back.</p> <p>Choice 2: Learn Python. Use Django. You define the minimal model and use the Django admin interface. You're pretty much done in about 20 minutes. Seriously. Then write the minimal loader from your spreadsheet to your tables. This is a hard sell, so don't sell it, just do it. </p> <p>Either way, delete the spreadsheet and never look back.</p> <p>Now, everything has to be done through the web-based database. No excuses. Add <strong>all</strong> reports to this interface. Do not permit a download to a spreadsheet. Make the app easy to add, change and modify. </p> <p>Once you can manage the chaos, you get seek forgiveness. </p> <p>You can never justify this -- you can't prove any ROI on being organized.</p>
<p>You can maybe take a look at <a href="http://www.eclipse.org/cosmos/" rel="nofollow noreferrer">COSMOS</a>, an implementation of the <a href="http://www.cmdbf.org/" rel="nofollow noreferrer">CMDBf</a> specifications</p>
25,550
<p>What code generation tools are built-in to vs.net 2008 or are officially available via Microsoft?</p> <p>I know of:</p> <ul> <li>Entity Framework</li> <li>sqlmetal</li> </ul> <p>What else is there?</p> <p>Ideally i'm looking for something that will generate from an existing database schema.</p>
<p>I'm not sure the platform you're internationalizing in. I've written an answer before on the best way to il8n an application. See <a href="https://stackoverflow.com/questions/59130/what-do-i-need-to-know-to-globalize-an-asp-net-application/59184#59184">What do I need to know to globalize an asp.net application?</a></p> <p>That said - managing the translations themselves is hard. The problem is that you'll be using the same piece of text across multiple pages. Your framework may not, however, support only having that piece of text in one file (resource files in asp.net, for instance, encourage you to have one resource file per language).</p> <p>The way that we found to work with things was to have a central database repository of translations. We created a small .net application to import translations from resource files into that database and to export translations from that database to resource files. There is, thus, an additional step in the build process to build the resource files.</p> <p>The other issue you're going to have is passing translations to your translation vendor and back. There are a couple ways for this - see if your translation vendor is willing to accept XML files and return properly formatted XML files. This is, really, one of the best ways, since it allows you to automate your import and export of translation files. Another alternative, if your vendor allows it, is to create a website to allow them to edit the translations.</p> <p>In the end, your answer for translations will be the same for any other process that requires repetition and manual work. Automate, automate, automate. Automate every single thing that you can. Copy and paste is <em>not</em> your friend in this scenario.</p>
<p>In Java, internationalization is accomplished by moving the strings to resource bundles ... the translation process is still long and arduous, but at least it's separated from the process of producing the software, releasing service packs etc. One thing that helps is to have a CI system that repackages everything any time changes are made. We can have a new version tested and out in a matter of minutes whether it's a code change, new language pack or both.</p>
23,200
<p><code>temp2</code>, <code>temp1</code> are pointers to some struct x:</p> <pre><code>struct FunkyStruct x; struct FunkyStruct *temp1 = &amp;x, *temp2 = &amp;x; </code></pre> <p>Now, after execution of following lines:</p> <pre><code>temp2=temp1; temp1=temp1-&gt;nxt; </code></pre> <p>...Will <code>temp2</code> and <code>temp1</code> still point to the same memory location? If not, please explain why they would be different. </p>
<p>Initially, <code>temp1</code> and <code>temp2</code> both contain the memory address of <code>x</code>.</p> <p><code>temp2 = temp1</code> means "assign the value of <code>temp1</code> to <code>temp2</code>". Since they have the same value to start with, this command does nothing.</p> <p>The expression <code>temp1-&gt;next</code> means "Look inside the data structure that <code>temp1</code> points to, and return the value of the field <code>next</code>." So <code>temp1 = temp1-&gt;next</code> assigns the value of <code>temp1-&gt;next</code> to <code>temp1</code>. (Of course, the lookup happen <em>before</em> the assignment.) <code>temp1</code> will now contain whatever value the <code>next</code> field happened to contain. It could be the same as the old value, or it could be different.</p>
<p>x (and therefore x.nxt) will be initialised to an unspecified value, depending on the combination of compiler, compiler options and the runtime environment. temp1 and temp2 will both point to x (before and after temp1=temp2). Then temp1 will be assigned whatever value x.nxt has.</p> <p>Final answer: 0 &lt; Pr(temp1 == temp2) &lt;&lt; 1, because temp1 == temp2 iff x.nxt == &amp;x.</p>
13,488
<p>Our logging class, when initialised, truncates the log file to 500,000 bytes. From then on, log statements are appended to the file.</p> <p>We do this to keep disk usage low, we're a commodity end-user product.</p> <p>Obviously keeping the first 500,000 bytes is not useful, so we keep the last 500,000 bytes.</p> <p>Our solution has some serious performance problem. What is an efficient way to do this?</p>
<blockquote> <p>"I would probably create a new file, seek in the old file, do a buffered read/write from old file to new file, rename the new file over the old one."</p> </blockquote> <p>I think you'd be better off simply:</p> <pre><code>#include &lt;fstream&gt; std::ifstream ifs("logfile"); //One call to start it all. . . ifs.seekg(-512000, std::ios_base::end); // One call to find it. . . char tmpBuffer[512000]; ifs.read(tmpBuffer, 512000); //One call to read it all. . . ifs.close(); std::ofstream ofs("logfile", ios::trunc); ofs.write(tmpBuffer, 512000); //And to the FS bind it. </code></pre> <p>This avoids the file rename stuff by simply copying the last 512K to a buffer, opening your logfile in truncate mode (clears the contents of the logfile), and spitting that same 512K back into the beginning of the file.</p> <p>Note that the above code hasn't been tested, but I think the idea should be sound.</p> <p>You could load the 512K into a buffer in memory, close the input stream, then open the output stream; in this way, you wouldn't need two files since you'd input, close, open, output the 512 bytes, then go. You avoid the rename / file relocation magic this way.</p> <p>If you don't have an aversion to mixing C with C++ to some extent, you could also perhaps:</p> <p>(Note: pseudocode; I don't remember the mmap call off the top of my head)</p> <pre><code>int myfd = open("mylog", O_RDONLY); // Grab a file descriptor (char *) myptr = mmap(mylog, myfd, filesize - 512000) // mmap the last 512K std::string mystr(myptr, 512000) // pull 512K from our mmap'd buffer and load it directly into the std::string munmap(mylog, 512000); //Unmap the file close(myfd); // Close the file descriptor </code></pre> <p>Depending on many things, mmap <em>could be</em> faster than seeking. Googling 'fseek vs mmap' yields some interesting reading about it, if you're curious.</p> <p>HTH</p>
<p>I don't think it is anything computer related, but how you guys have written your logging class. It sounds strange to me that you read the last 500k into a string, why would you do that?</p> <p>Just append to the logfile.</p> <pre><code> fstream myfile; myfile.open("test.txt",ios::app); </code></pre>
44,969
<p>Lucene has quite poor support for Russian language.</p> <p>RussianAnalyzer (part of lucene-contrib) is of very low quality.</p> <p>RussianStemmer module for Snowball is even worse. It does not recognize Russian text in Unicode strings, apparently assuming that some bizarre mix of Unicode and KOI8-R must be used instead.</p> <p>Do you know any better solutions?</p>
<p>If all else fails, use <a href="http://www.sphinxsearch.com/" rel="nofollow noreferrer">Sphinx</a></p>
<p>That's the beauty of open source. You have the source code, so if the current implementations don't work for you, you can always create your own or even better, extend the existing ones. A good start would be the "Lucene in Action" book.</p>
8,934
<p>I am curious on how others manage code promotion from DEV to TEST to PROD within an enterprise.</p> <p>What tools or processes do you use to manage the "red tape", entry/exit criteria side of things?</p> <p>My current organisation is half stuck between some custom online forms type functionality and paper based dependencies to submit documents, gather approvals and reviews.</p> <p>All this is left in the project managers hands to track what has been submitted, passed review, approved and advise management if there are any roadblocks that may need approval to be "overlooked" before an application can be promoted to the next environment.</p> <p>A browser based application would be ideal... so whats out there? please show me that you googlefu is better than mine.</p>
<p>It's hard to find one that's good via google. There is a vast array of tools out there for issue management so I'll mention what we use and what we woudl like to use.</p> <p>We currently use serena products. They have worked well for us in the past. Team Track is our issue management and handles the life cycle of any issue we work on. Version Manager is our source control and has the feature of implementing promotional groups like DEV TEST And PROD. We use DEV, TSTAGE, TEST, PSTAGE and PROD to signify the movement from one to the other, but it's much the same. The two products integrate nicely so that the source associated with the issues is linked, but we have no build process setup in this environment. It's expensive, but it works well.</p> <p>We are looking ot move to a more common system using Jira for issue management, Subversion for source control, Fisheye to link the two together and Cruise Control for build management. This is less expensive, totaling a few thousand for an enterprise lisence and provides all the same features but with the added bonus of SVN which is a very nice code version mangager.</p> <p>I hope that helps.</p>
<p>There are a few different scenarios that I've experienced over the years:</p> <p>Dev -> Test : There is usually a code freeze date that stops work on new features and gets a test environment the code that has been tagged/labelled/archived that gets built. This then gets copied onto the machines and the tests go fine. This is also usually the least detailed of any push.</p> <p>Test->Prod : This requires the minor change that production has to go down which can mean that a "gone fishing" page goes up or IIS doesn'thave any sites running and the code is copied over again. There are special cases to this where a load balancer can act as a switch so that the promotion happens and none of the customers experience any down time as the ones on the older server will move once their session ends.</p> <p>To elaborate on that switch idea, the set up is to have 2 potentially live servers with just one server taking requests that the load balancer just sends all the traffic to one machine that can be switched when the other server has the updated code to go live.</p> <p>There can also be a staging environment which is between test and production where the process is similar in terms of there is a set date when the promotion happens.</p> <p>Where I used to work there would be merge days where a developer spent most of a day in Perforce merging code so that it could be promoted from one environment to another.</p> <p>Now there are a couple of cases where this isn't used:</p> <p>"Hotfixes" or "Hot patches" would occur where I used to work and in this case the specific files were copied up into the staging and production environments on its own since the code change had to get into Production ASAP since something broke in production or some new thing that had to get done that takes 2 minutes gets done. In this case, the code change getting pushed in had to be reviewed and approved before going out.</p> <p>Those are the different approaches I've seen used where generally there are schedules and timelines potentially have to be changed or additional resources brought in to make a hard date like if a conference is on a particular weekend that such and such is ready for that.</p> <p>Of course in a few places there has been the, "Oh, was that broken? Let me see..." and a few minutes later, "No, see it isn't broken for me," where someone changed things without asking permission or anything where a company still has what they call "cowboy programming."</p> <p>Another point is the scale of the release: 1) Tiny - This is the case where one web page goes up so that user X can do Y.</p> <p>2) Small - A handful or so of files that isn't really complicated but isn't exactly trivial.</p> <p>3) Medium - Where going from one environment to another requires changing a bunch of files and usually has scripts to move.</p> <p>4) Big - Where there are scheduled promotions and various developers are asked for who is taking which shifts when the live push is done. I had this in a case where there was a data migration to do in addition to a release of some new e-commerce sites.</p> <p>5) Mammoth - Where everything is brand new including how this would be used. I don't think I've ever seen one of this size but I'd imagine Microsoft or Google would have releases of this size.</p> <p>Somewhere in that spectrum most releases fall and so how much planning and preparation can vary quite a bit and let's not forget that regulatory compliance can be its own pain in getting some things done.</p>
22,956
<p>I have a web application that has many faces and so far I've implemented this through creating themes. A theme is a set of html, css and images to be used with the common back end.</p> <p>Things are laid out like so:</p> <pre><code>code/ themes/theme1 themes/theme2 </code></pre> <p>And each instance of the web application has a configuration file that states which theme should be used. Example:</p> <pre><code>theme="theme1" </code></pre> <p>Now new business rules are asking me to make changes to certain themes that can't be achieved through simply change the html/css/images and require changing the backend. In some cases these changes need to be applied to a group of themes.</p> <p>I'm wondering how to best lay this out on disk, and also how to handle it in code. I'm sure someone else must have come up against this.</p> <p>One idea is to have:</p> <pre><code>code/common code/theme1 code/theme2 themes/theme1 themes/theme2 </code></pre> <p>Then have my common code set the <code>include_path</code> such that <code>code/theme1</code> is searched first, then <code>code/common</code>.</p> <p>Then if I want to specialize say the <code>LogoutPage</code> class for <code>theme2</code>, I can simply copy the page from <code>code/common</code> to the same path under <code>code/theme2</code> and it will pick up the specialized version.</p> <p>One problem with this idea is that there'll be multiple classes with the same name. Although in theory they would never be included in the same execution, I wouldn't be able to extend the original base class.</p> <p>So what if I was to make a unique name for the base class? e.g. <code>Theme1LogoutPage extends LogoutPage</code>. One problem I can foresee with that is when some common code (say the Dispatcher) references <code>LogoutPage</code>. I can add conditions to the dispatcher, but I wonder if there's a more transparent way to handle this?</p> <p>Another option I can think of is to maintain separate branches for each theme, but I think this could be a lot of work.</p> <p>One final thing to consider is that features might originate in one theme and then require merging into the common codebase.</p> <p>Any input greatly appreciated. If it makes any difference, it's a LAMP environment.</p>
<p>I don't have a specific recommendation. However, I strongly suggest to <strong>NOT</strong> take shortcut... Use the solution that will you will find comfortable to add a third theme or to change something next year.<br> Duplication is the enemy of maintainability.</p>
<p>Are you using Master Pages? If you need different layout and UI stuff you could just have a different set of master pages for each of your instances. If you need custom behavior then you might want to look into Dependency Injection. Spring.NET, etc.</p>
30,459
<p>I want to print HTML from a C# web service. The web browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free <code>.NET</code> library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly.</p> <pre><code>public void PrintThing(string document) { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Thread thread = new Thread((ThreadStart) delegate { PrintDocument(document); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } else { PrintDocument(document); } } protected void PrintDocument(string document) { WebBrowser browser = new WebBrowser(); browser.DocumentText = document; while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } browser.Print(); } </code></pre> <p>This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing <code>Print()</code> to <code>ShowPrintPreviewDialog()</code> yields the following IE script error:</p> <blockquote> <p><strong>Error:</strong> <code>dialogArguments.___IE_PrintType</code> is null or not an object. </p> <p>URL: <code>res://ieframe.dll/preview.dlg</code></p> </blockquote> <p>And a small empty print preview dialog appears.</p>
<p>You can print from the command line using the following:</p> <blockquote> <p>rundll32.exe %WINDIR%\System32\mshtml.dll,PrintHTML "%1"</p> </blockquote> <p>Where %1 is the file path of the HTML file to be printed.</p> <p>If you don't need to print from memory (or can afford to write to the disk in a temp file) you can use:</p> <pre><code>using (Process printProcess = new Process()) { string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System); printProcess.StartInfo.FileName = systemPath + @"\rundll32.exe"; printProcess.StartInfo.Arguments = systemPath + @"\mshtml.dll,PrintHTML """ + fileToPrint + @""""; printProcess.Start(); } </code></pre> <p>N.B. This only works on Windows 2000 and above I think.</p>
<p>I don't know the specific tools, but there are some utilities that record / replay clicks. In other words, you could automate the "click" on the print dialog. (I know this is a hack, but when all else fails...)</p>
2,265
<p>Moments ago <a href="http://twitter.com/codinghorror/status/1051535711" rel="nofollow noreferrer">Jeff Atwood said the following on twitter</a>:</p> <blockquote> <p>Look, I love rapid new software releases, but the frequency of WordPress releases is just ridiculous.</p> </blockquote> <p>Which makes me think, <strong>how often should you release software updates?</strong></p> <ul> <li>Daily?</li> <li>Weekly?</li> <li>Monthly?</li> <li>Yearly?</li> </ul> <p>Whats the best release strategy?</p>
<p>I would say in WordPress' specific case, <strong>they conflate "security updates" and "functionality updates"</strong>. This is bad.</p> <p>This would be like having to do an in-place reinstall of Windows every time a security bug was found, instead of simply downloading a small patch every week.</p> <p>WordPress needs to have a security patch mechanism that's simple, fast, and easy for the security updates. A process that is separate from the normal upgrade flow of new versions.</p>
<p>Surely when you have new features/bug fixes worth releasing ?? Why have it on a schedule ?</p>
46,985
<p>I had the BLTouch (3.1) working with stock firmware on an Ender 3 v2 but wanted to get a 5x5 mesh instead of the 3x3 so I installed the TH3D firmware. With the stock firmware my Z-offset was -2.95 mm.</p> <p>After installing TH3D firmware, my Z-offset has to be in excess of -6 mm to reach the same nozzle-to-bed height. I've tried setting the Z-offset via LCD and through G-code, saving to EEPROM. I'm having 2 problems with this that I assume are connected:</p> <ol> <li>Z-offset seems to not be applied when setting Z axis position. When I autohome and then set Z axis to 0, even the extended probe from the BLTouch does not touch the bed (it's actually 1-2 mm away from touching). And this is with the Z-offset set to -6 mm.</li> <li>I tried running a print, which includes an ABL request (<code>G29</code>), the print head crashed into the bed immediately after finishing levelling. My hunch is that when starting to print the -6 mm Z-offset starts being correctly taken into account.</li> </ol> <p>Could this be the result of something I did in the Configuration.h when compiling the firmware?</p> <p>I made the following changes:</p> <p><a href="https://github.com/th3dstudio/UnifiedFirmware/blob/2.0.x/Board%20Configuration%20Files/CrealityV42X/Firmware/Marlin/Configuration.h" rel="nofollow noreferrer">CrealityV42X/Firmware/Marlin/Configuration.h</a></p> <ul> <li>Line 24: uncommented <code>#define ENDER3_V2_V422_BOARD</code></li> <li>Line 43: uncommented <code>#define CUSTOM_PROBE</code></li> <li>Line 66: changed <code>#define EZABL_POINTS</code> from 3 to 5</li> <li>Line 124: changed <code>#define NOZZLE_TO_PROBE_OFFSET</code> from <code>{ 10, 10, 0}</code> to <code>{ -44, -6, 0 }</code></li> <li>Line 233: uncommented <code>#define BLTOUCH</code></li> <li>Line 235: uncommented <code>#define SERVO0_PIN PB0</code></li> <li>Line 636: commented out <code>#define Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN</code></li> <li>Line 636: added <code>#define USE_PROBE_FOR_Z_HOMING</code></li> </ul> <p>In <a href="https://github.com/th3dstudio/UnifiedFirmware/blob/2.0.x/Firmware/Marlin/Configuration_backend.h" rel="nofollow noreferrer">Configuration_backend.h</a> the only change I made was increasing <code>Z_PROBE_OFFSET_RANGE_MIN</code> from -5 to -20.</p>
<p>I'm pretty sure something is wrong with the firmware I downloaded. I flashed the 3/5/21 version of Marlin firmware from <a href="https://marlin.crc.id.au/" rel="nofollow noreferrer">https://marlin.crc.id.au/</a> and it is somehow working better with the LCD firmware (which I got from TH3D), the Z offset is working as it should, and the leveling process has more points and goes faster.</p>
<p>Do you still have this issue? My Ender with a BLTouch won't respect the Z-off set setting in <strong>Motion</strong> &gt; <strong>Control</strong> &gt; <strong>ZOffset</strong>. You can change it to -10 and it will still start printing about 1 cm above the bed.</p> <p>All of this started to happen after I used <strong>Bed Leveling</strong> from the prepare menu. To work around the issue, I reset the settings <strong>Initialize EPROM</strong> in the control menu.</p> <ol> <li>Reset All settings <strong>Initialize EPROM</strong></li> <li>Set the Z-offset (In my case -3.3)</li> <li>Store settings in the control menu</li> <li>Switch off the printer (settings won't take effect even if you select to load settings)</li> </ol> <p>Then start printing. This doesn't solve the issue because it defeats the purpose of having a BLTouch in the first place. but at least I'm able to print again.</p> <p>In a nutshell, avoiding auto bed leveling does the trick (or at least in my case)</p> <p>Hope it helps.</p>
1,881
<p>I have migrated a couple of project from Subversion to git. It work really well but when I clone my repository, it's really long because I have all the history of a lot of .jar file included in the transfer.</p> <p>Is there a way to keep only the latest version of certain type of file in my main repository. I mainly want to delete old version on binary file.</p>
<p>You can remove old versions with either "git rebase" -i or "git filter-branch"</p> <p><a href="http://schacon.github.com/git/git-filter-branch.html" rel="nofollow noreferrer">http://schacon.github.com/git/git-filter-branch.html</a></p> <p><a href="http://schacon.github.com/git/git-rebase.html" rel="nofollow noreferrer">http://schacon.github.com/git/git-rebase.html</a></p> <p>Other docs and tutorials: <a href="http://git-scm.com/documentation" rel="nofollow noreferrer">http://git-scm.com/documentation</a></p> <p>Keeping only the current version from now forward is not supported. Your best bet is to instead keep in revision control a small script that downloads (or builds, or otherwise generates) the large .jar file.</p> <p>As this modifies history, it will make all previous clones or pulls from this repository invalid.</p>
<p>In short, this would involve rewriting the entire git commit tree to exclude the files. Have you tried using <code>git gc</code> and <code>git pack</code> to have git compress your repository?</p>
12,235
<p>I'm working on database designs for a project management system as personal project and I've hit a snag.</p> <p>I want to implement a ticket system and I want the tickets to look like the <a href="http://trac.edgewall.org/ticket/6436" rel="noreferrer">tickets in Trac</a>. What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)</p> <p>Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. </p> <p><strong>Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.</strong> </p>
<p>I have implemented pure record change data using a "thin" design:</p> <pre><code>RecordID Table Column OldValue NewValue -------- ----- ------ -------- -------- </code></pre> <p>You may not want to use "Table" and "Column", but rather "Object" and "Property", and so forth, depending on your design.</p> <p>This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the "Table" and "Column" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter.</p> <p><strong>EDIT</strong>: several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a "Transaction" table with a datetime, user and other info, and a "TransactionID" column, so the design would look like this:</p> <pre><code>CHANGE LOG TABLE: RecordID Table Column OldValue NewValue TransactionID -------- ----- ------ -------- -------- ------------- TRANSACTION LOG TABLE: TransactionID UserID TransactionDate ------------- ------ --------------- </code></pre>
<p>One possible solution is storing a copy of the ticket in a history table with the user that made the change. </p> <p>However, this will store alot of extra data and require alot of processing to create the view that Trac shows.</p>
17,115
<p>I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with:</p> <pre><code>&lt;urlopen error The read operation timed out&gt; </code></pre> <p>If I set the timeout (no matter how long), it dies even more immediately with:</p> <pre><code>&lt;urlopen error The connect operation timed out&gt; </code></pre> <p>The latter is reproducible with:</p> <pre><code>import socket socket.setdefaulttimeout(30000) sock = socket.socket() sock.connect(('www.google.com', 443)) ssl = socket.ssl(sock) </code></pre> <p>returning:</p> <pre><code>socket.sslerror: The connect operation timed out </code></pre> <p>but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this.</p>
<pre><code>import socket socket.setdefaulttimeout(30000) sock = socket.socket() sock.connect(('www.google.com', 443)) ssl = socket.ssl(sock) ssl.server() --&gt; '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com' </code></pre> <p>It works just fine. I can't reproduce your error.</p>
<p>www.google.com is not accessible by HTTPS. It redirects to insecure HTTP. To get to mail, you should be going go <a href="https://mail.google.com" rel="nofollow noreferrer">https://mail.google.com</a></p>
11,809
<p>I need to build a little webapp but I'm not sure what is the best thing to do.</p> <p>A person that subscribe the petition is signing an email sent to <em>X</em>. This will be also saved to a db in order to show online who subscribed.</p> <p>The idea is to have a standard text message, the user submit his name and that name goes into the message as signature.</p> <p>I could make php send the email with the address of the real sender, or let the user copy and paste the text and let him send the email on his own.</p> <p>I'm not sure of what is the best way to implement it. What will be more "effective", I mean as number of subscribers the solution where the app send the email is easier, but what about the authenticity of the emails? They could be considered not valid if sent all from the same place? </p>
<p>Regardless of the whole thing being a "good" idea or not, you want to keep yourself safe. If you spoof the from field, chances are most of your email (especially for domains with SPF records) will not make it through the first level of spam filtering.</p> <p>A SPF (Sender Policy Framework) record lists the only IPs that are allowed to send mails for a domain. If a domain has a SPF record and you poll it, you're supposed to treat anything that didn't originate from a listed server as hazardous waste.</p> <p>Depending on where you're sending these emails, you'll probably end up with your mail server on one or multiple blacklists. That means <em>any</em> email, SPF or not just won't get accepted.</p> <p>So in short:</p> <ul> <li>Get people to send their own email. Provide templates.</li> <li>Consider utilizing the full specs for <code>&lt;a href="mailto:...</code> -- you can put the subject and body in the link, allowing templates to be a one-click affair.</li> <li>You could use Javascript on your site to personalise the message (and therefore <code>mailto:</code> link) while still on your site.</li> </ul>
<p>Let me get this straight - so you want to add to the flood of armchair activism email that is already saturating the world to no good purpose, and you're asking how best to do it? I would read the following before going any further with this:</p> <p><a href="http://www.breakthechain.org/armchair.html" rel="nofollow noreferrer">http://www.breakthechain.org/armchair.html</a></p>
23,577
<p>I've been using the YUI Components and want to begin using the Loader Utility to specify my dependencies on my page. From your experience, is the YUI Loader Utility a reliable way to load Javascript dependencies in web pages?</p>
<p>Yes, YUI Loader is reliable on all A-grade browsers. For a list of which browsers Yahoo! considers A-grade, check out the <a href="http://developer.yahoo.com/yui/articles/gbs/" rel="nofollow noreferrer">Graded Browser Support Chart</a>.</p>
<p>I use the loader a lot. It's a great way to manage dependencies and build you library around.</p> <p>I've run into 3 problems with it:</p> <ol> <li>Debugging - it's difficult to debug. Is the bug in the module's loader definition or is it in the module (script file)?</li> <li>You have to add your own 'subscibeOnce' function to add any 'on module(s) loaded' handlers. This unsubscribes your handlers after the module has been loaded/inserted into the page. Otherwise, if you insert more modules later in the page's lifespan - they called each time.</li> <li>There's a limit to what dependencies it can figure out. Ordering within the requires:[] (in the module definition) seems to matter. I've seen it fail trying to work through this list.</li> </ol> <p>What i use is something like:</p> <pre><code>var TheBase = function(oConfig){ var thisBase = this; var EVENTS = { ON_SCRIPTS_LOADED : "onScriptsLoaded" , ON_SCRIPTS_PROGRESS : "onScriptsProgress" } for(var eventName in EVENTS){ thisBase.createEvent(EVENTS[eventName]); } var _loader = new YAHOO.util.YUILoader({ base: oConfig.yuiBasePath ,onSuccess:function(o){ thisBase.fireEvent(EVENTS.ON_SCRIPTS_LOADED); } ,onProgress:function(o){ thisBase.fireEvent(EVENTS.ON_SCRIPTS_PROGRESS,o.name); } }) //optional thisBase.loader = _loader; </code></pre> <p>}</p> <pre><code>TheBase.prototype = { subscribeOnce : function(eventName, fnc, context, args){ var that = this; var handler = function hander(){ fnc.apply(context, arguments); that.unsubscribe(eventName, handler); } this.subscribe(eventName, handler, args, false); } </code></pre> <p>}</p> <p>//augment with event provider</p> <pre><code>YAHOO.lang.augment(TheBase, YAHOO.util.EventProvider); </code></pre>
11,526
<p>In short - How do I translate a NETBIOS domain to a FQDN ?</p> <p>Details: Assuming I'm in domain A and I have user credentials for domain B which has a trust relationship with domain A (I can authenticate the credentials). How do I get domain B's FQDN when all I have are the credentials of some authenticated user from that domain, including the netbios domain name?</p> <p>I'm coding in C# but a COM/WMI/Win32 solution would be welcomed as well.</p>
<p>This probably isn't optimal, but it look like you could do a NetBIOS name query to get an IP address, and then do a reverse DNS lookup to get an FQDN from that...</p> <p><a href="http://www.protocolbase.net/protocols/protocol_NBNS.php" rel="nofollow noreferrer">http://www.protocolbase.net/protocols/protocol_NBNS.php</a></p> <p>(The reverse DNS step is easy to look up)</p>
<p>Bind to the domain using the WinNT provider and filter for all user accounts. Start enumerating the user accounts.</p> <p>If the user account sAMAccount name does not contain the string "duplicate" then exit from the loop and use the NameTranslate object to look up the LDAP name of the account.</p> <p>Part of the LDAP name is the domain FQDN.</p> <p>Hey, it's a fudge but it works like a charm.</p>
32,845
<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>
<p>I think your best bet is to remove the explicit constraint and add a <a href="http://msdn.microsoft.com/en-us/library/ms180169.aspx" rel="nofollow noreferrer">cursor</a> for inserts, so you can perform your checking there and raise an error if the constraint is violated.</p>
5,988
<p>How can I run background tasks on App Engine?</p>
<p>You may use the <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="noreferrer">Task Queue Python API</a>. </p>
<p>Use the Task Queue - <a href="http://code.google.com/appengine/docs/java/taskqueue/overview.html" rel="nofollow">http://code.google.com/appengine/docs/java/taskqueue/overview.html</a></p>
17,994
<p>Suppose that I have a form that contains three 10 fields: field1..field10. I store the form data in one or more database tables, probably using 10 database columns. </p> <p>Now suppose a few months later that I want to add 3 more fields. And in the future I may add/delete fields from this form based on changing requirements. If I have a database column per form field, then I would have to make the corresponding changes to the database each time I change the form. This seems like a maintenance headache. There must be a more sophisticated way.</p> <p>So my question is, how do I design a data model that is loosely coupled with my UI? A concrete use case is a CRM system that is extensible/customizable by users. </p>
<p>You could abstract fields to a separate table so that they are many-to-many to the Form table:</p> <h2>Form</h2> <p><strong>ID</strong><br/> Name<br/> etc.</p> <h2>Field</h2> <p><strong>ID</strong><br/> Label<br/> Value</p> <h2>FormField</h2> <p><strong>FormID</strong><br/> <strong>FieldID</strong></p>
<p>My team came up with a solution for this when I worked for Quest Computing on AIMS (www.totalaims.com). In summary we added maintenance screens that allowed the administrator to add metadata and also as a result add fields to the database in certain tables. The fields were also added to their own maintenance and search screens automatically. We built this on top of the OpenACS. You can find out more at www.openacs.org - search for "flexbase" or "dynfields" or look here www.project-open.org/doc/intranet-dynfield/ . This worked quite well - them main downside being a side effect of the main upside i.e. that addition of fields could be done by non-DBAs and as a result performance could easily be compromised. </p>
5,214
<p>I've just downloaded the ASP.MVC MSI package, but the installation fails with the "<strong>There is a problem with this Windows Installer Package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor.</strong>" message.</p> <p>I see that other people too have the same problem (<a href="http://forums.asp.net/p/1336453/2699267.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1336453/2699267.aspx</a>). Anybody else?</p> <p>I'm running VS 2008 Professional edition with SP1 on Vista.</p> <p>Some additional info: entries like <strong>Error in Template (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\VisualBasic\Workflow\1033\StateMachineWorkflowLibrary.zip), file (StateMachineWorkflowLibrary.vstemplate). Unregistered ProjectType (VisualBasic). This can be caused by an incorrect ProjectType or because the project type package is not installed.</strong> appear in the event log. </p> <p>BTW I don't have VisualBasic installed. I'm thinking about reinstalling VisualStudio ... :|</p>
<p>I removed all the bad templates and this didn't resolve the issue for me. I found that removing other Add-Ins I had installed let me install Beta 1. In my case the bad add-in preventing the install was <a href="http://www.codeplex.com/CloneDetectiveVS" rel="nofollow noreferrer">Clone Detective</a>.</p>
<p>I had this exact error message from a completely different MSI package - the DevExpress toolkit - turned out to be caused by one of the "defensive" packages installed on my machine.</p> <p>Check your anti-virus, anti-spyware, anti-intrusion, firewall, anti-xxx etc etc packages to see if any of them might be stopping scripts from running properly.</p> <p>Hope this helps.</p>
28,342
<p>So, I want to export all my contacts from Outlook as vcards. If I google that, I get a bunch of shareware programs, but I want something free that just works. </p> <p>If I'm to code it myself, I guess I should use the Microsoft.Office.Interop.Outlook assembly. Has anyone already code to convert ContactItems to vcards?</p> <p><strong>Edit:</strong> I solved it in a completely different way, see answer below, but I have marked dok1.myopenid.com's answer as accepted because it answers my original question. </p>
<p>I solved it in a non-programmatically way:</p> <ul> <li>Selected all contacts in Outlook</li> <li>Forwarded them as cards to myself</li> <li>Saved all the attachments (vcards) in a folder, <code>c:\temp</code></li> <li>Opened a command prompt and typed the command <code>copy /a *.vcf c:\allcards.vcf</code> which concatenates all vcards into one</li> </ul>
<p>Just purchased the X8 and was about to get really really mad when I couldn't easily transfer my contacts...until I started snooping around on the phone.</p> <p>First, export all your contacts in Outlook to vCards (I found emailing them to yourself is the easiest. If you get an error message "to many attachments..." you can save them from the email in your sent items folder) and copy the vCards to the memory card on your phone.</p> <p>Second, open your address book on the phone then press the left button on the phone (the button with 4 little squares above it. NOT THE 4 BOXES ON THE SCREEN...THE PHYSICAL BUTTON!).</p> <p>Third, select "Import/Export" and choose import from memory card. Import all vCard files and you should be golden.</p> <p>Best of luck...don't ask me any questions because I will not be back to look at any more posts...just passing by trying to figure it out on my own.</p>
25,627
<p>The <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton pattern</a> is a fully paid up member of the <a href="https://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">GoF</a>'s <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">patterns book</a>, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for <a href="https://en.wikipedia.org/wiki/Factory_method_pattern" rel="noreferrer">factory classes</a>, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.</p> <p>Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?</p> <p>Please support your answers with "<em>facts, references, or specific expertise</em>"</p>
<p>Paraphrased from Brian Button:</p> <ol> <li><p>They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a <a href="https://en.wikipedia.org/wiki/Code_smell" rel="noreferrer">code smell</a>.</p></li> <li><p>They violate the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">single responsibility principle</a>: by virtue of the fact that they control their own creation and lifecycle.</p></li> <li><p>They inherently cause code to be tightly <a href="https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29" rel="noreferrer">coupled</a>. This makes faking them out under test rather difficult in many cases.</p></li> <li><p>They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.</p></li> </ol>
<p>Off the top of my head:</p> <ol> <li>They enforce tight-coupling. If your singleton resides on a different assembly than its user, the using assembly cannot ever function without the assembly containing the singleton.</li> <li>They allow for circular dependencies, e.g., Assembly A can have a singleton with a dependency on Assembly B, and Assembly B can use Assembly A's singleton. All without breaking the compiler.</li> </ol>
16,688
<p>Below is my (simplified) schema (in MySQL ver. 5.0.51b) and my strategy for updating it. There has got to be a better way. Inserting a new item requires 4 trips to the database and editing/updating an item takes up to <strong>7</strong>!</p> <p><strong>items</strong>: itemId, itemName <br /><strong>categories</strong>: catId, catName <br /><strong>map</strong>: mapId*, itemId, catId <br />* mapId (varchar) is concat of itemId + | + catId</p> <p>1) If inserting: insert item. Get itemId via MySQL API. <br />Else updating: just update the item table. We already have the itemId.</p> <p>2) Conditionally batch insert into <code>categories</code>.</p> <pre><code>INSERT IGNORE INTO categories (catName) VALUES ('each'), ('category'), ('name'); </code></pre> <p>3) Select IDs from <code>categories</code>.</p> <pre><code>SELECT catId FROM categories WHERE catName = 'each' OR catName = 'category' OR catName = 'name'; </code></pre> <p>4) Conditionally batch insert into <code>map</code>.</p> <pre><code>INSERT IGNORE INTO map (mapId, itemId, catId) VALUES ('1|1', 1, 1), ('1|2', 1, 2), ('1|3', 1, 3); </code></pre> <p>If inserting: we're done. Else updating: continue.</p> <p>5) It's possible that we no longer associate a category with this item that we did prior to the update. Delete old categories for this itemId.</p> <pre><code>DELETE FROM MAP WHERE itemId = 2 AND catID &lt;&gt; 2 AND catID &lt;&gt; 3 AND catID &lt;&gt; 5; </code></pre> <p>6) If we have disassociated ourselves from a category, it's possible that we left it orphaned. We do not want categories with no items. Therefore, if <code>affected rows &gt; 0</code>, kill orphaned categories. I haven't found a way to combine these in MySQL, so this is #6 &amp; #7.</p> <pre><code>SELECT categories.catId FROM categories LEFT JOIN map USING (catId) GROUP BY categories.catId HAVING COUNT(map.catId) &lt; 1; </code></pre> <p>7) Delete IDs found in step 6.</p> <pre><code>DELETE FROM categories WHERE catId = 9 AND catId = 10; </code></pre> <p>Please tell me there's a better way that I'm not seeing.</p>
<p>Steps 6 &amp; 7 can be combined easily enough:</p> <pre><code>DELETE categories.* FROM categories LEFT JOIN map USING (catId) WHERE map.catID IS NULL; </code></pre> <p>Steps 3 &amp; 4 can also be combined:</p> <pre><code>INSERT IGNORE INTO map (mapId, itemId, catId) SELECT CONCAT('1|', c.catId), 1, c.catID FROM categories AS c WHERE c.catName IN('each','category','name'); </code></pre> <p>Otherwise, your solution is pretty standard, unless you want to use triggers to maintain the map table.</p>
<p>Steps 6 &amp; 7 can be combined easily enough:</p> <pre><code>DELETE categories.* FROM categories LEFT JOIN map USING (catId) WHERE map.catID IS NULL; </code></pre> <p>Steps 3 &amp; 4 can also be combined:</p> <pre><code>INSERT IGNORE INTO map (mapId, itemId, catId) SELECT CONCAT('1|', c.catId), 1, c.catID FROM categories AS c WHERE c.catName IN('each','category','name'); </code></pre> <p>Otherwise, your solution is pretty standard, unless you want to use triggers to maintain the map table.</p>
36,824
<p>I am trying to <strong>synchronize</strong> the horizontal <strong>scroll position</strong> of 2 <strong>WPF DataGrid</strong> controls.</p> <p>I am subscribing to the <strong>ScrollChanged</strong> event of the first DataGrid:</p> <pre><code>&lt;toolkit:DataGrid x:Name="SourceGrid" ScrollViewer.ScrollChanged="SourceGrid_ScrollChanged"&gt; </code></pre> <p>I have a second DataGrid:</p> <pre><code>&lt;toolkit:DataGrid x:Name="TargetGrid"&gt; </code></pre> <p>In the event handler I was attempting to use the <strong><code>IScrollInfo.SetHorizontalOffset</code></strong>, but alas, DataGrid doesn't expose <code>IScrollInfo</code>:</p> <pre><code>private void SourceGrid_ScrollChanged(object sender, ScrollChangedEventArgs e) { ((IScrollInfo)TargetGrid).SetHorizontalOffset(e.HorizontalOffset); // cast to IScrollInfo fails } </code></pre> <p>Is there another way to accomplish this? Or is there another element on TargetGrid that exposes the necessary <code>IScrollInfo</code> to achieve the synchronization of the scroll positions?</p> <p>BTW, I am <strong>using frozen columns</strong>, so I cannot wrap both DataGrid controls with ScrollViewers.</p>
<p>According to the Microsoft product group, traversing the visual tree to find the ScrollViewer is the recommended method, as <a href="http://wpf.codeplex.com/discussions/40161" rel="nofollow noreferrer">explained in their answer on Codeplex</a>.</p>
<p>We had this same problem when using the Infragistics grid because it <em>didn't</em> (still doesn't) support frozen columns. So we had two grids side-by-side that were made to look as one. The grid on the left didn't scroll horizontally but the grid on the right did. Poor man's frozen columns.</p> <p>Anyway, we ended up just reaching into the visual tree and pulling out the <code>ScrollViewer</code> ourselves. Afterall, we knew it was there - it just wasn't exposed by the object model. You could use a similar approach if the WPF grid does not expose the ScrollViewer. Or you could subclass the grid and add the functionality you require to make this work.</p> <p>Interested in hearing why you need to do this.</p>
37,428
<p>We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using <code>mod_proxy_jk</code> as the connector.</p> <p>Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).</p> <p>Relevant server.xml portions:</p> <pre><code>&lt;Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3" emptySessionPath="true" enableLookups="false" redirectPort="8443" maxThreads="320" connectionTimeout="45000" /&gt; </code></pre> <p>Relevant httpd.conf portions: </p> <pre><code>&lt;IfModule prefork.c&gt; StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 0 &lt;/IfModule&gt; </code></pre>
<p>You should consider the workload the servers might get.</p> <p>The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where:</p> <ul> <li>there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads when the server is heavily loaded</li> <li>there are not way more processing threads in the servers than needed as they would waste resources.</li> </ul> <p>With this kind of setup you can minimize the internal maintenance overhead of the servers, that could help a lot, especially when your load is sporadic.</p> <p>For example consider an application where you have ~300 new requests/second. Each request requires on average 2.5 seconds to serve. It means that at any given time you have ~750 requests that need to be handled simultaneously. In this situation you probably want to tune your servers so that they have ~750 processing threads at startup and you might want to add something like ~1000 processing threads at maximum to handle extremely high loads.</p> <p>Also consider for exactly what do you require a thread for. In the previous example each request was independent from the others, there was no session tracking used. In a more "web-ish" scenario you might have users logged in to your website, and depending on your software used, Apache and/or Tomcat might need to use the same thread to serve the requests that come in one session. In this case, you might need more threads. However as I know Tomcat at least, you won't really need to consider this as it works with thread pools internally anyways.</p>
<p>The default settings are generally decent starting points to see what your applications is really going to need. I don't know how much traffic you're expecting, so guessing at the MaxThreads, MaxClients, and MaxServers is a bit difficult. I can tell you that most of the customers I deal with (work for a linux web host, that deals mainly with customers running Java apps in Tomcat) use the default settings for quite some time without too many tweaks needed.</p> <p>If you're not expecting much traffic, then these settings being "too high" really shouldn't effect you too much either. Apache's not going to allocate resources for the whole 256 potential clients unless it becomes necessary. The same goes for Tomcat as well. </p>
13,128
<p>In a Swing app a method should continue only after user enters a correct answer. The correct answer is stored in a <code>String</code> with user answer being set by a listener to another <code>String</code>. So, the code is</p> <pre><code>while (!correctAnswer.equals(currentAnswer)) { // wait for user to click the button with the correct answer typed into the textfield } // and then continue </code></pre> <p>Is everything fine with this approach or would you somehow refactor it? Doesn't it impose extra penalty on CPU? Here's a somewhat <a href="https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop" title="Best refactoring for the dreaded While (True) loop">similar question</a>.</p>
<p>Are you new to UI programming? The reason I ask is that your answer is predicated on a procedural style of coding, which isn't what UIs are about. It tends to be event-driven.</p> <p>In this case the solution is pretty easy: add an event listener (<code>ActionListener</code>) to the submit button and check the result there. If its OK, go on. If not, say so and let them try again.</p>
<p>If your strings are coming from a human user at GUI rates, there's very little point in optimizing for performance. The human won't be able to enter more than perhaps one to three strings per second, and that's nothing for the machine.</p> <p>In this particular case, where you need to do stuff to get an input to test, I would suggest using a <code><a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html" rel="nofollow noreferrer">do-while</a></code> loop.</p>
43,305
<p>I'm using a <code>RichTextBox</code> (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys.... For example, I don't want <kbd>Ctrl</kbd>+<kbd>I</kbd> to make the text italic via the RichText method, but to instead run my own method for processing the text.</p> <p>Any ideas?</p>
<p><kbd>Ctrl</kbd>+<kbd>I</kbd> isn't one of the default shortcuts affected by the ShortcutsEnabled property.</p> <p>The following code intercepts the <kbd>Ctrl</kbd>+<kbd>I</kbd> in the KeyDown event so you can do anything you want inside the if block, just make sure to suppress the key press like I've shown.</p> <pre><code>private void YourRichTextBox_KeyDown(object sender, KeyEventArgs e) { if ((Control.ModifierKeys &amp; Keys.Control) == Keys.Control &amp;&amp; e.KeyCode == Keys.I) { // do whatever you want to do here... e.SuppressKeyPress = true; } } </code></pre>
<p>Set the RichtTextBox.ShortcutsEnabled property to true and then handle the shortcuts yourself, using the KeyUp event. E.G.</p> <pre><code>using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.textBox1.ShortcutsEnabled = false; this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp); } void textBox1_KeyUp(object sender, KeyEventArgs e) { if (e.Control == true &amp;&amp; e.KeyCode == Keys.X) MessageBox.Show("Overriding ctrl+x"); } } } </code></pre>
32,599
<p>I have rules set to move some email messages into different folders. I would like this to still show the envelope in the notification area but there is no option in the rules wizard to do this. It looks like I would either have to have the rule "run a script" or "perform a custom action" allowing either vba or c/c++ respectively.</p> <p>Anyone else have a better solution?</p>
<p>It sounds like you could use a Rails non active-record model. There's a good Railscast about that : </p> <p><a href="http://railscasts.com/episodes/121-non-active-record-model" rel="noreferrer">http://railscasts.com/episodes/121-non-active-record-model</a></p> <p>Hope that helps, </p>
<p>This is an area that's not well documented at present, probably because the ActiveRecord stuff is sexier?</p> <p>I went through the same process, finding my controller actions were becoming uncomfortably large and full of logic as I strove to construct my derived data from ActiveRecord-based models, which in turn started to acquire additional responsibilities that they didn't really want or need.</p> <p>Once I got <a href="https://stackoverflow.com/questions/26834/how-to-represent-cross-model-information-in-mvc">the same advice you're getting now</a> the whole thing simplified magnificently.</p>
44,324
<p>I'm running into a problem setting up my development environment. I've been working on ColdFusion and .NET applications up until recently I haven't needed to touch IIS. Now, I have to set up a classic ASP application for some one-off work.</p> <p>I added a virtual directory in IIS and pointed it at the actual codebase on my local machine. I then set the security to low (for ISAPI extensions, i.e. ASP) and allowed for script execution. For some reason though, if I hit any .asp page it says the page cannot be found. However, HTML and static files load up just fine.</p> <p>EDIT: URLScan fix seems to have done it. Fired up the app in another browser (i.e. not IE6), and I'm getting better error reporting. Looks like we're missing some includes, but it is executing the scripts. Thanks!</p>
<p>Take a look at your URL scan settings and see if .asp is an allowed file extension</p> <p>On my XP machine the relevant file is located at C:\WINDOWS\system32\inetsrv\urlscan\urlscan.ini</p>
<p>Take a look at your URL scan settings and see if .asp is an allowed file extension</p> <p>On my XP machine the relevant file is located at C:\WINDOWS\system32\inetsrv\urlscan\urlscan.ini</p>
22,259
<p>How can I dock a CControlBar derived window to the middle of a splitter window (CSplitterWnd)? I would like the bar to be repositioned whenever the splitter is moved.</p> <p>To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.</p>
<p>Alf,</p> <p>In case of VS, there's no splitter used: The resource view is a resizable ControlBar (It looks and feels like a splitter but it isn't a CSplitterWnd). The rest is a child frame (either tabbed or MDI. Go to Tools/Options/Environment/General and choose Multiple Documents to convince yourself). The ruler is part (controlbar?) of the child frame.</p> <p>In your case, I think you don't want a 3 panes splitter. You need a 2 pane splitter and the control bar should be part of your view (it wouldn't be a CControlBar per se). Unless you use MDI in which case you can make it a true ControlBar in your child frame.</p> <p>HTH</p>
<p>Serge, I apologize, I wasn't very clear. The splitter would be between the resource view and the ruler bar. It would looke like this:</p> <p>Resource View | Vertical ruler | View</p> <p>In any case, I found the (now obvious) answer: split the main frame into three windows:</p> <pre><code>m_wndSplitter.CreateStatic(this, 1, 3); m_wndLeftPane.Create(&amp;m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 0)); m_ruler.Create(&amp;m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 1)); m_wndSplitter.CreateView(0, 2, pContext-&gt;m_pNewViewClass, CSize(300, 0), pContext); SetActiveView((CScrollView*)m_wndSplitter.GetDlgItem(m_wndSplitter.IdFromRowCol(0, 2))); </code></pre>
19,828
<p>I need to use XmlRpc in C++ on a Windows platform. Despite the fact that my friends assure me that XmlRpc is a "widely available standard technology", there are not many libraries available for it. In fact I only found one library to do this on Windows, (plus another one that claims "you'll have to do a lot of work to get this to compile on Windows). The library I found was Chris Morley's "XmlRpc++". However, it doesn't have support for SSL.</p> <p>My question therefore is: what library should I be using? </p>
<p>I've written my own C++ library. It's available at sourceforge: <a href="http://sourceforge.net/projects/xmlrpcc4win/" rel="noreferrer">xmlrpcc4win</a></p> <p>The reason I wrote it rather than using Chris Morley's was that:</p> <ul> <li>The Windows "wininet.lib" library gives you all the functionality for handling Http requests, so I'd rather use that. As a result, I only needed 1700 LOC.</li> <li>"wininet.lib", and therefore my implementation, supports HTTPS</li> <li>Chris Morley's use of STL containers was quite inefficient (Chris, mail me if you read this).</li> </ul>
<p>There are dozens of implementations of the XML-RPC <a href="http://www.xmlrpc.com/directory/1568/implementations" rel="nofollow noreferrer">implementations</a>, some in C++, but most in other languages. For example, besides XmlRpc++ there is also <a href="http://xmlrpc-c.sourceforge.net/" rel="nofollow noreferrer">XML-RPC for C and C++</a>. Here is a <a href="http://tldp.org/HOWTO/XML-RPC-HOWTO/xmlrpc-howto-c.html" rel="nofollow noreferrer">HOWTO</a> on how the XML-RPC for C and C++ library can be used.</p> <p>The XML-RPC specification is somewhat simple and it would not be difficult to implement your own XML-RPC client. Not to mention, it would also be possible to take an existing XML-RPC implementation in C and bring into your C++ project.</p> <p>The XML-RPC <a href="http://www.xmlrpc.com/" rel="nofollow noreferrer">home page</a> also provides a lot of useful information.</p>
9,364
<p>If you have a project, that releases a library and an application, how you handle version-numbers between the two.</p> <p>Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.</p> <p>New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way?</p>
<p>Completely independent version numbers, but the command line (or any other dependent) app should say which version of the library it was compiled against in the help section or a banner. </p> <p>That way you will be able to tell which functionality will the apps have and reduce potential confusion, especially given that somebody could compile a newer app version against an old library for any reason. Also, you decouple them and can add features on the library without depending on release of a new app version and so on. </p> <p>If you are sure you will always want all the apps and library to go in lockstep then you could use same numbers, but that's adding a constraint for not a strong reason.</p>
<p>We built an application that uses a framework. We keep separate version numbers for both.</p> <p>This works well, especially that now the framework and application have grown large enough to be developed by different teams.</p> <p>So my opinion... keep the version numbers separate.</p>
17,295
<p>Is there a tool to automatically search through my site and test all the links? I hate running across bad urls.</p>
<p><a href="http://home.snafu.de/tilman/xenulink.html" rel="nofollow noreferrer">Xenu link sleuth</a> is excellent (and free)</p>
<p>Something like this should work: <a href="http://www.dead-links.com/" rel="nofollow noreferrer">http://www.dead-links.com/</a></p> <p>Do google searches for "404 checker" or "broken link checker"</p>
12,196
<p>MySQL 5.0.45</p> <p>What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this:</p> <pre><code>ALTER mytable MODIFY mycolumn varchar(255) null; </code></pre> <p>I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.</p>
<p>You want the following:</p> <pre><code>ALTER TABLE mytable MODIFY mycolumn VARCHAR(255); </code></pre> <p>Columns are nullable by default. As long as the column is not declared <code>UNIQUE</code> or <code>NOT NULL</code>, there shouldn't be any problems.</p>
<p>Use: <code>ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);</code></p>
26,170
<p>I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?</p> <p>To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.</p>
<p><a href="http://www.ibm.com/developerworks/library/tiptidy.html" rel="nofollow noreferrer"><strong>Convert from HTML to XML with HTML Tidy</strong></a></p> <p><a href="http://tidy.sourceforge.net/#binaries" rel="nofollow noreferrer"><strong>Downloadable Binaries</strong></a></p> <p>JRoppert, For your need, i guess you might want to look at the <a href="http://sourceforge.net/cvs/?group_id=27659" rel="nofollow noreferrer">Sources</a></p> <pre><code>c:\temp&gt;tidy -help tidy [option...] [file...] [option...] [file...] Utility to clean up and pretty print HTML/XHTML/XML see http://tidy.sourceforge.net/ Options for HTML Tidy for Windows released on 14 February 2006: File manipulation ----------------- -output &lt;file&gt;, -o write output to the specified &lt;file&gt; &lt;file&gt; -config &lt;file&gt; set configuration options from the specified &lt;file&gt; -file &lt;file&gt;, -f write errors to the specified &lt;file&gt; &lt;file&gt; -modify, -m modify the original input files Processing directives --------------------- -indent, -i indent element content -wrap &lt;column&gt;, -w wrap text at the specified &lt;column&gt;. 0 is assumed if &lt;column&gt; &lt;column&gt; is missing. When this option is omitted, the default of the configuration option "wrap" applies. -upper, -u force tags to upper case -clean, -c replace FONT, NOBR and CENTER tags by CSS -bare, -b strip out smart quotes and em dashes, etc. -numeric, -n output numeric rather than named entities -errors, -e only show errors -quiet, -q suppress nonessential output -omit omit optional end tags -xml specify the input is well formed XML -asxml, -asxhtml convert HTML to well formed XHTML -ashtml force XHTML to well formed HTML -access &lt;level&gt; do additional accessibility checks (&lt;level&gt; = 0, 1, 2, 3). 0 is assumed if &lt;level&gt; is missing. Character encodings ------------------- -raw output values above 127 without conversion to entities -ascii use ISO-8859-1 for input, US-ASCII for output -latin0 use ISO-8859-15 for input, US-ASCII for output -latin1 use ISO-8859-1 for both input and output -iso2022 use ISO-2022 for both input and output -utf8 use UTF-8 for both input and output -mac use MacRoman for input, US-ASCII for output -win1252 use Windows-1252 for input, US-ASCII for output -ibm858 use IBM-858 (CP850+Euro) for input, US-ASCII for output -utf16le use UTF-16LE for both input and output -utf16be use UTF-16BE for both input and output -utf16 use UTF-16 for both input and output -big5 use Big5 for both input and output -shiftjis use Shift_JIS for both input and output -language &lt;lang&gt; set the two-letter language code &lt;lang&gt; (for future use) Miscellaneous ------------- -version, -v show the version of Tidy -help, -h, -? list the command line options -xml-help list the command line options in XML format -help-config list all configuration options -xml-config list all configuration options in XML format -show-config list the current configuration settings Use --blah blarg for any configuration option "blah" with argument "blarg" Input/Output default to stdin/stdout respectively Single letter options apart from -f may be combined as in: tidy -f errs.txt -imu foo.html For further info on HTML see http://www.w3.org/MarkUp </code></pre>
<p>The easiest way is to set your Visual Studio IDE to identify the changes you need to make. You can do this in Visual Studio 2008 by going to: Tools, Options, Text Editor, HTML, Validation and choosing the appropriate target. Possibly XHTML 1.1 or XHTML 1.0 Transitional.</p> <p>For some information on the different types, read: <a href="http://msdn.microsoft.com/en-us/library/aa479043.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa479043.aspx</a></p> <p>Then you need to work through the points highlighted on your page.</p>
16,780
<p>When using Slic3r I noticed that <code>Slice now</code> and <code>Export G-Code</code> do different things. While <code>Slice now</code> is nice, it does not show any tool paths etc. </p> <p>Is there an actual way to generate and visualize the G-code in Slic3r without saving the exported G-Code first? When aligning seams etc., it is quite annoying to always save the file to see a difference because <code>Slice now</code> seems to make little difference.</p>
<p>Using Repetier Host V2.1.2 and slicing with Slic3r (or with CuraEngine), there is an "edit Gcode" button under the Print Preview tab. It is located at the top right of the screen. With that button you can access, examine and change the Gcode of the project you are working on.</p>
<p>After you use the Slice Now button (and the slicing progress bar shows completed), select the preview tab. To the right of the window you will see a pair of vertical sliders. Each slider changes the start and finish locations for the filament layers.</p> <p>You can slide the left one to the bottom, which will "empty" the virtual print bed. Each movement upward will display a succeeding layer, showing the placement of the filament. This ostensibly will present to you alignment information as well as unexpected holes or other failure points.</p> <p>I don't know of any slicer that lacks a preview. That doesn't mean one does not exist, but why would such a useful feature be omitted?</p>
943
<p>I'm trying to build an assembly with one larger part (about 50&nbsp;mm&nbsp;x&nbsp;50&nbsp;mm), two small parts (about 10&nbsp;mm&nbsp;x&nbsp;5&nbsp;mm) each, and one part that starts with two 2&nbsp;mm&nbsp;x&nbsp;2&nbsp;mm squares that eventually bridge into a sort of flap. The larger part has decent adhesion for a couple of layers, but the small parts are slipping off the table right away and the nozzle drags them onto the large part since it's the last part being printed in the group, resulting in some stringing.</p> <p>My bed is adequately leveled and can print larger models well so my suspicion is that the small parts are too small for good bed adhesion and need a brim or a raft to increase the surface area. Is this correct? If so, is there a way in Cura to add a brim or raft to the small parts and not the large part? Ideally I would print all pieces at once instead of the large part separate since I will be doing batches of these assemblies in the future.</p> <p>I'm using Ultimaker Cura 3.6, printing with PLA filament set to 200&nbsp;&deg;C at nozzle and 60&nbsp;&deg;C on the bed.</p>
<p><em>This is a &quot;No&quot; and &quot;Yes&quot; answer, it depends on the version of Cura you are using!</em></p> <hr /> <p><strong>No</strong>, there are no options available to set the brim to some of the parts in Ultimaker Cura (at the time of writing this answer, pre Cura 4.5.0). You could however change the smaller model to include the brim in your design, or add so-called &quot;Mouse Ears&quot;.</p> <p>At the time of writing this answer, the image below shows the Ultimaker Cura interface for &quot;per model&quot; settings, basically different settings with respect to the other models. As can be seen, you cannot expand the <code>Build Plate Adhesion</code> (it already shows the arrow downwards, so expanded):</p> <p><a href="https://i.stack.imgur.com/5YXXp.png" rel="nofollow noreferrer" title="Pre Cura 4.5.0 per model settings example"><img src="https://i.stack.imgur.com/5YXXp.png" alt="Ultimaker Cura with per model settings" title="Pre Cura 4.5.0 per model settings example" /></a></p> <p>But, <strong>yes</strong> as of Cura 4.5.0 (see <a href="/a/13293/">this answer</a>) the &quot;per model&quot; settings have changed and the <code>Build Plate Adhesion</code> is added with the option to add a <code>Brim Distance</code> to trick Cura into de-attaching the brim (it will print a brim, but it is not attached to the part):</p> <p><a href="https://i.stack.imgur.com/wzGPZ.png" rel="nofollow noreferrer" title="Cura 4.8.0 per model settings example"><img src="https://i.stack.imgur.com/wzGPZ.png" alt="Cura 4.8.0 per model settings example" title="Cura 4.8.0 per model settings example" /></a></p> <p>When applied to several models this could result in models with a brim attached and others without the brim attached:</p> <p><a href="https://i.stack.imgur.com/euEhG.jpg" rel="nofollow noreferrer" title="Example showing brim attached and detached"><img src="https://i.stack.imgur.com/euEhG.jpg" alt="Example showing brim attached and detached" title="Example showing brim attached and detached" /></a></p>
<p>This post is quite old, but I describe how I solved this for anyone has the same problem I had: areas moved by the nozzle as the base of some appendices are too thin and tall.</p> <p>In Cura 4.8 (I don't know since which version this feature is available) it is possible to add some custom shapes (cubes or cylinders) to your model. You can find this tool after move, resize, etc,, in the prepare page (left side icons).</p> <p>So you can add some custom supports to protect from falling/moving some areas of a single model that need to be kept in place. These added parts can be moved and resized as you would do with the any other imported model.</p> <p>I found this very useful to avoid that the nozzle moves parts with a small base area that are connected to the rest of the model on a higher level and the lower part is not stable enough. Especially when printing TPU or other flexible filaments.</p>
1,169
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
<p>I found it quite easy to write an IMAP server in twisted last time I tried. It comes with support for writing IMAP servers and you have a huge amount of flexibility.</p>
<p>I never tried but, if I had to, I would start with the existing SMTP server.</p>
45,790
<p>What is the best way to construct a bit mask in C with <code>m</code> set bits preceded by <code>k</code> unset bits, and followed by <code>n</code> unset bits:</p> <pre><code>00..0 11..1 00..0 k m n </code></pre> <p>For example, k=1, m=4, n=3 would result in the bit mask:</p> <pre><code>01111000 </code></pre>
<p>You can do:</p> <pre><code>~(~0 &lt;&lt; m) &lt;&lt; n </code></pre>
<p>Whilst the top answers are simple and effective they don't set the MSB for the case when <code>n=0</code> and <code>m=31</code>:</p> <p><code>~(~0 &lt;&lt; 31) &lt;&lt; 0</code> = ‭<code>0111 1111 1111 1111 1111 1111 1111 1111‬</code></p> <p><code>((1 &lt;&lt; 31)-1) &lt;&lt; 0</code> = ‭<code>0111 1111 1111 1111 1111 1111 1111 1111‬</code></p> <p>My suggestion for a 32-bit unsigned word looks like this:</p> <pre><code>unsigned int create_mask(unsigned int n,unsigned int m) { // 0 &lt;= start_bit, end_bit &lt;= 31 assert(n &gt;=0 &amp;&amp; m&lt;=31); return (m - n == 31 ? ~0: ((1 &lt;&lt; (m-n)+1)-1) &lt;&lt; n); } </code></pre> <p>This actually gets the bits in the range <code>[m,n]</code> (closed interval) so <code>create_mask(0,0)</code> will return a mask for the first bit (bit 0) and <code>create_mask(4,6)</code> returns a mask for bits 4 to 6 i.e <code>... 00111 0000</code>.</p>
40,868
<p>I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.</p> <pre><code>StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter writer = new HtmlTextWriter(sw); Control uc = LoadControl("~/includes/HomepageNews.ascx"); uc.RenderControl(writer); return sb.ToString(); </code></pre> <p><strong>That code renders the control but none of the events called in the Page_Load of the control are firing. There's a Repeater in the control needs to fire.</strong></p>
<p>I've been using the following code provided by Scott Guthrie in his blog for quite some time:</p> <pre><code>public class ViewManager { public static string RenderView(string path, object data) { Page pageHolder = new Page(); UserControl viewControl = (UserControl) pageHolder.LoadControl(path); if (data != null) { Type viewControlType = viewControl.GetType(); FieldInfo field = viewControlType.GetField("Data"); if (field != null) { field.SetValue(viewControl, data); } else { throw new Exception("ViewFile: " + path + "has no data property"); } } pageHolder.Controls.Add(viewControl); StringWriter result = new StringWriter(); HttpContext.Current.Server.Execute(pageHolder, result, false); return result.ToString(); } } </code></pre> <p>The <code>object data</code> parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.</p> <p>This code will fire all the normal events in the control.</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx" rel="noreferrer">You can read more about it here</a> </p> <p>Regards Jesper Hauge</p>
<p>I took Hauge's/ Scott Guthrie's method above and tweaked it so that you don't need to use reflection, or modify a UserControl to implement any special interface. The key was I added a strongly typed callback that the RenderView method above calls, instead of doing reflection.</p> <p>I blogged the helper method and usage <a href="http://www.jonkragh.com/index.php/rendering-an-asp-net-usercontrol-to-a-string/" rel="nofollow noreferrer">here</a></p> <p>HTH, Jon</p>
32,325
<p>I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here.</p>
<p>Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any &quot;clever tricks&quot;.</p> <pre class="lang-java prettyprint-override"><code>//The main function public static Node merge_sort(Node head) { if(head == null || head.next == null) return head; Node middle = getMiddle(head); //get the middle of the list Node left_head = head; Node right_head = middle.next; middle.next = null; //split the list into two halfs return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that } //Merge subroutine to merge two sorted lists public static Node merge(Node a, Node b) { Node dummyHead = new Node(); for(Node current = dummyHead; a != null &amp;&amp; b != null; current = current.next;) { if(a.data &lt;= b.data) { current.next = a; a = a.next; } else { current.next = b; b = b.next; } } dummyHead.next = (a == null) ? b : a; return dummyHead.next; } //Finding the middle element of the list for splitting public static Node getMiddle(Node head) { if(head == null) return head; Node slow = head, fast = head; while(fast.next != null &amp;&amp; fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } </code></pre>
<pre class="lang-java prettyprint-override"><code>public int[] msort(int[] a) { if (a.Length &gt; 1) { int min = a.Length / 2; int max = min; int[] b = new int[min]; int[] c = new int[max]; // dividing main array into two half arrays for (int i = 0; i &lt; min; i++) { b[i] = a[i]; } for (int i = min; i &lt; min + max; i++) { c[i - min] = a[i]; } b = msort(b); c = msort(c); int x = 0; int y = 0; int z = 0; while (b.Length != y &amp;&amp; c.Length != z) { if (b[y] &lt; c[z]) { a[x] = b[y]; //r-- x++; y++; } else { a[x] = c[z]; x++; z++; } } while (b.Length != y) { a[x] = b[y]; x++; y++; } while (c.Length != z) { a[x] = c[z]; x++; z++; } } return a; } </code></pre>
2,929
<p>So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.</p> <p>I would like to use generics to create a general class for this scenario. Something like:</p> <pre><code> Adder&lt;Double&gt; adder = new Adder&lt;Double&gt;(); adder.add(10.0d, 10.0d); // = 20.0d </code></pre> <p>But, I cannot instantiate the generic type I pass in to my Adder class! So -- what to do?</p>
<p>Uh oh---generics are not C++ templates. Because of type erasure, the <code>Double</code> in your example won't even show through to the runtime system.</p> <p>In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., <code>double add(double, double)</code>, <code>float add(float, fload)</code>, <code>BigDecimal add(BigDecimal, BigDecimal)</code>, etc.</p>
<p>If you don't know what kinds of numbers you'll be operating on, then you probably won't be using instance variables of your own. In that case, you can write static methods and never need to instantiate your class.</p> <p>If you really need your own intermediate variables, then you will likely need to define them differently for each class of user variables you're working with. For instance, if someone tries to use your class to operate on <strong>BigDecimal</strong> variables, you probably won't be using <strong>int</strong> variables for intermediate results.</p>
36,295
<p>So I'm been pounding on this problem all day. I've got a LinqDataSource that points to my model and a GridView that consumes it. When I attempt to do an update on the GridView, it does not update the underlying data source. I thought it might have to do with the LinqDataSource, so I added a SqlDataSource and the same thing happens. The aspx is as follows (the code-behind page is empty):</p> <pre><code> &lt;asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=devsql32;Initial Catalog=Steam;Persist Security Info=True;" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [LangID], [Code], [Name] FROM [Languages]" UpdateCommand="UPDATE [Languages] SET [Code]=@Code WHERE [LangID]=@LangId"&gt; &lt;/asp:SqlDataSource&gt; &lt;asp:GridView ID="_languageGridView" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="LangId" DataSourceID="SqlDataSource1"&gt; &lt;Columns&gt; &lt;asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /&gt; &lt;asp:BoundField DataField="LangId" HeaderText="Id" ReadOnly="True" /&gt; &lt;asp:BoundField DataField="Code" HeaderText="Code" /&gt; &lt;asp:BoundField DataField="Name" HeaderText="Name" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:LinqDataSource ID="_languageDataSource" ContextTypeName="GeneseeSurvey.SteamDatabaseDataContext" runat="server" TableName="Languages" EnableInsert="True" EnableUpdate="true" EnableDelete="true"&gt; &lt;/asp:LinqDataSource&gt; </code></pre> <p>What in the world am I missing here? This problem is driving me insane.</p>
<p>You are missing the &lt;UpdateParameters&gt; sections of your DataSources.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.updateparameters.aspx" rel="nofollow noreferrer">LinqDataSource.UpdateParameters</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.updateparameters.aspx" rel="nofollow noreferrer">SqlDataSource.UpdateParameters</a></p>
<p>This is a total shot in the dark since I haven't used ASP at all.</p> <p>I've been just learning XAML and WPF, which appears to be very similar to what you've posted above and I know that for some UI controls you need to specify the binding mode to two-way in order to get updates in both directions.</p>
7,587
<p>Has anyone successfully built an Adobe Air application with Maven? If so, what are the steps to get it working?</p> <p>I have been trying to use <a href="http://code.google.com/p/flex-mojos/" rel="noreferrer">flex-mojos</a> to build an Air applications. When I set the packaging type to "aswf", as suggested in the <a href="http://code.google.com/p/flex-mojos/wiki/DashboardSamplePom" rel="noreferrer">DashboardSamplePom</a>, Maven complains that aswf is an unknown packaging type. I also found their <a href="http://svn.sonatype.org/flexmojos/repository/info/flex-mojos/air-super-pom/2.0-alpha4/air-super-pom-2.0-alpha4.pom" rel="noreferrer">air-super-pom</a>, but could not figure out how to reference it as the parent of my POM.</p>
<p>There is an article called <a href="https://docs.sonatype.org/display/FLEXMOJOS/Building+an+AIR+Application" rel="nofollow noreferrer">Building an AIR Application</a> on the mojos website wiki. It should be able to help you. </p>
<p>In my case I simply created a new maven project using the org.graniteds.archetypes graniteds-tide-seam-jpa-hibernate archetype and got this error. I don't know anything about flex, but simply wanted a sample project using Seam. This seemed like a good candidate. But I get </p> <p>unknown packaging type:swf</p> <p>even though the &lt;extensions&gt;true&lt;extensions&gt; is present in the plugin definintion of the generated POM file.</p> <p>I read somewhere else that this reqires a beta version of maven. Why the heck is sonatype allowing archetypes that depend on beta versions of maven in their repository?</p>
17,657
<p>I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need.</p> <p>Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas.</p> <ol> <li><p><a href="http://code.google.com/apis/ajaxfeeds/" rel="nofollow noreferrer">Google AJAX Feed API</a> - will limit you to 250 items</p></li> <li><p><a href="http://www.niallkennedy.com/blog/2005/12/google-reader-api.html" rel="nofollow noreferrer">Unofficial Google Reader API</a> - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky.</p></li> <li><p><a href="http://spinn3r.com/" rel="nofollow noreferrer">Spinn3r</a> - Costs a lot of money</p></li> <li><p>Spidering the <a href="http://www.archive.org" rel="nofollow noreferrer">internet archive</a> at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort</p></li> <li><p><a href="http://www.niallkennedy.com/blog/2005/12/my-yahoo-feed-a.html" rel="nofollow noreferrer">Yahoo! Feed API</a> or <a href="http://developer.yahoo.com/search/boss/" rel="nofollow noreferrer">Yahoo! Search BOSS</a> - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds.</p></li> <li><p>(thanks to Lou Franco) <a href="http://www.bloglines.com/services/api/sync" rel="nofollow noreferrer">Bloglines Sync API</a> - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first.</p></li> <li><p>Other search engines/blog search/whatever?</p></li> </ol> <p>This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness?</p>
<p>For queries like this it is always best to use an <code>INFORMATION_SCHEMA</code> view. These views are (mostly) standard across many different databases and rarely change from version to version.</p> <p>To check if a table exists use:</p> <pre><code>IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable')) BEGIN --Do Stuff END </code></pre>
<p>consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following:</p> <p>Right click on t1, then Script table as, then DROP and Create To, then New Query Editor </p> <p>you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one. </p> <p>Thanks</p>
20,241
<p>What are all the common undefined behaviours that a C++ programmer should know about?</p> <p>Say, like:</p> <pre><code>a[i] = i++; </code></pre> <p></p>
<h3>Pointer</h3> <ul> <li>Dereferencing a <code>NULL</code> pointer</li> <li>Dereferencing a pointer returned by a &quot;new&quot; allocation of size zero</li> <li>Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects)</li> <li>Dereferencing a pointer that has not yet been definitely initialized</li> <li>Performing pointer arithmetic that yields a result outside the boundaries (either above or below) of an array.</li> <li>Dereferencing the pointer at a location beyond the end of an array.</li> <li>Converting pointers to objects of incompatible types</li> <li><a href="https://stackoverflow.com/a/11211519/241536">Using <code>memcpy</code> to copy overlapping buffers</a>.</li> </ul> <h3>Buffer overflows</h3> <ul> <li>Reading or writing to an object or array at an offset that is negative, or beyond the size of that object (stack/heap overflow)</li> </ul> <h3>Integer Overflows</h3> <ul> <li>Signed integer overflow</li> <li>Evaluating an expression that is not mathematically defined</li> <li>Left-shifting values by a negative amount (right shifts by negative amounts are implementation defined)</li> <li>Shifting values by an amount greater than or equal to the number of bits in the number (e.g. <code>int64_t i = 1; i &lt;&lt;= 72</code> is undefined)</li> </ul> <h3>Types, Cast and Const</h3> <ul> <li>Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast)</li> <li>Using an automatic variable before it has been definitely assigned (e.g., <code>int i; i++; cout &lt;&lt; i;</code>)</li> <li>Using the value of any object of type other than <code>volatile</code> or <code>sig_atomic_t</code> at the receipt of a signal</li> <li>Attempting to modify a string literal or any other const object during its lifetime</li> <li>Concatenating a narrow with a wide string literal during preprocessing</li> </ul> <h3>Function and Template</h3> <ul> <li>Not returning a value from a value-returning function (directly or by flowing off from a try-block)</li> <li>Multiple different definitions for the same entity (class, template, enumeration, inline function, static member function, etc.)</li> <li>Infinite recursion in the instantiation of templates</li> <li>Calling a function using different parameters or linkage to the parameters and linkage that the function is defined as using.</li> </ul> <h3>OOP</h3> <ul> <li>Cascading destructions of objects with static storage duration</li> <li>The result of assigning to partially overlapping objects</li> <li>Recursively re-entering a function during the initialization of its static objects</li> <li>Making virtual function calls to pure virtual functions of an object from its constructor or destructor</li> <li>Referring to nonstatic members of objects that have not been constructed or have already been destructed</li> </ul> <h3>Source file and Preprocessing</h3> <ul> <li>A non-empty source file that doesn't end with a newline, or ends with a backslash (prior to C++11)</li> <li>A backslash followed by a character that is not part of the specified escape codes in a character or string constant (this is implementation-defined in C++11).</li> <li>Exceeding implementation limits (number of nested blocks, number of functions in a program, available stack space ...)</li> <li>Preprocessor numeric values that can't be represented by a <code>long int</code></li> <li>Preprocessing directive on the left side of a function-like macro definition</li> <li>Dynamically generating the defined token in a <code>#if</code> expression</li> </ul> <h3>To be classified</h3> <ul> <li>Calling exit during the destruction of a program with static storage duration</li> </ul>
<p>The only type for which C++ guarantees a size is <code>char</code>. And the size is 1. The size of all other types is platform dependent.</p>
47,982
<p>If I press <kbd>Ctrl</kbd>+<kbd>B</kbd> that ought to give me ASCII code 2, but <kbd>Ctrl</kbd>+<kbd>C</kbd> is going to be interpreted as a Break.</p> <p>So I figure I've got to redirect a file in. How do I get these characters into a file?</p>
<p><kbd>Ctrl</kbd>-<kbd>V</kbd> escapes the next keystoke. That's how you can get a <kbd>Ctrl</kbd>-<kbd>C</kbd> out: <kbd>Ctrl</kbd>-<kbd>V</kbd> <kbd>Ctrl</kbd>-<kbd>C</kbd></p>
<pre><code>perl -e 'print "\xFF"' </code></pre> <p>where <code>FF</code> is the hex code of the ACSII code you want to print. So for ACSII code 2, it would be \x02. </p>
3,634
<p>What is the best way to multi-thread in the C language? I want something that is very efficient and not a CPU hog. Thanks.</p>
<p>The correct (standard) way to do this on C and Windows is with <a href="http://msdn.microsoft.com/en-us/library/kdzttdcb.aspx" rel="nofollow noreferrer">__beginthreadex</a>.</p> <p>This is usually preferred to calling <a href="http://msdn.microsoft.com/en-us/library/kdzttdcb.aspx" rel="nofollow noreferrer">CreateThread</a> directly as CreateThread doesn't init C runtime support for the thread. So if you create a thread using CreateThread, and call a CRT function, bad stuff can/will happen.</p> <p>Note that __beginthreadex calls CreateThread internally, but performs some other work behind the scenes.</p>
<p>Your question is a bit general to answer effectively. You might look into such things as:</p> <p>CreateThread in the windows SDK</p> <p>boost::thread</p>
6,469
<p>Is there any way to create an array-like object in JavaScript, without using the built-in array? I'm specifically concerned with behavior like this:</p> <pre><code>var sup = new Array(5); //sup.length here is 0 sup[0] = 'z3ero'; //sup.length here is 1 sup[1] = 'o3ne'; //sup.length here is 2 sup[4] = 'f3our'; //sup.length here is 5 </code></pre> <p><strong>The particular behavior I'm looking at here is that sup.length changes without any methods being called.</strong> I understand from <a href="https://stackoverflow.com/questions/365975/how-are-javascript-arrays-implemented">this question</a> that the [] operator is overloaded in the case of arrays, and this accounts for this behavior. Is there a pure-javascript way to duplicate this behavior, or is the language not flexible enough for that?</p> <p>According to the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array" rel="noreferrer">Mozilla docs</a>, values returned by regex also do funky things with this index. Is this possible with plain javascript?</p>
<p>[] operator is the native way to access to object properties. It is not available in the language to override in order to change its behaviour.</p> <p>If what you want is return computed values on the [] operator, you cannot do that in JavaScript since the language does not support the concept of computed property. The only solution is to use a method that will work the same as the [] operator.</p> <pre><code>MyClass.prototype.getItem = function(index) { return { name: 'Item' + index, value: 2 * index }; } </code></pre> <p>If what you want is have the same behaviour as a native Array in your class, it is always possible to use native Array methods directly on your class. Internally, your class will store data just like a native array does but will keep its class state. jQuery does that to make the jQuery class have an array behaviour while retaining its methods.</p> <pre><code>MyClass.prototype.addItem = function(item) { // Will add "item" in "this" as if it was a native array // it will then be accessible using the [] operator Array.prototype.push.call(this, item); } </code></pre>
<p>Sure, you can replicate almost any data structure in JavaScript, all the basic building blocks are there. What you'll end up will be slower and less intuitive however.</p> <p>But why not just use push/pop ?</p>
47,779
<p>im using httpclient and last-modified header in order to retrieve the last updated date of an html file however when i try this on a linux box it returns yesterdays date but when i use a windows machine it returns todays date. is anyone aware of issues using this header field in linux?</p>
<p>Perhaps, linux server has its clock set differently and this way "lives in the past"?</p>
<p>If you dualboot with Windows, you must make sure your Linux system is configured to <em>not</em> think the BIOS keeps the clock in GMT (or UTC), but in local time. Otherwise your Linux system's clock will keep being off when in Linux.</p> <p>Also make sure that the /etc/localtime file is a symlink to the correct time zone file under /usr/share/zoneinfo.</p> <p>After configuring those two things, verify your date and time is correct using the <code>date</code> command and set it correctly if it isn't, via:</p> <p><code>date MMDDhhmmCCYY.ss</code></p> <p>For example, for the current time at my end (19:41:27 on October 15th 2008) I would use:</p> <p><code>date 101519412008.27</code></p>
25,041
<p>I've used Excel PivotTable to analyze data from my database because it allows me to "slice and dice" very quickly. As we know what is in our database tables, we all can write SQL queries that do what PivotTable does. </p> <p>But I am wondering why PivotTable can construct the queries so fast while it knows <em>nothing</em> about the data and the meanings/relationship between the data fields we give it? </p> <p>Put the question in another way, how can we build <em>ad-hoc</em> SQL queries in such a fast and efficient way? ("Use PivotTable, of course!", yep, but what I want is a programmatic way).</p>
<p>Just manipulate your order and group clauses as necessary.</p> <p>Excel is fast because all the data is in memory, and it can be sorted fast and efficiently.</p>
<p>My intuitive feeling tells me that the answer would have something to do with a Pivot Table outline, which has a <em>fixed</em> number of zones, namely:</p> <pre><code>- the Page Fields zone - the Column Fields zone - the Row Fields zone and - the Data zone </code></pre> <p>In my wild guess: </p> <pre><code>- The Page zone builds the WHERE part of the ad-hoc query. - The Column zone will put whichever fields drag-dropped to it in the GROUP BY clause. - The Row zone will build a SELECT DISTINCT &lt;field names&gt; - The Data zone will apply an AGGREGATE function to the field drag-dropped to it. </code></pre> <p>What do you think would happen "behind the scene" when we drag fields to those zones?</p>
10,936
<p>We are re-platforming for a client, and they are concerned about SEO. Their current site supports SEO friendly URLs, and so does the new platform. So for those, we are just going to create the same URL mapping. However, they have a large number of other URLs that are not SEO friendly that they want to permanently redirect. These do not follow a similar pattern, so one regex in an .htaccess won't cut it. What is the best way to handle this on a LAMP stack? The application has a front controller too, so I need to make sure that works along with the hard redirects.</p>
<p>One approach (the one <a href="http://blog.kaeding.name/articles/2008/07/22/migrating-urls-with-apache" rel="nofollow noreferrer">I chose</a>) was to create a simple table of old urls and new ones, and then use <a href="http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html" rel="nofollow noreferrer">mod_rewrite</a> to read the table and perform redirects. The table can live in a file external to the Apache config.</p> <p>Alternatively, you could write a script to query a database if you wanted the table to live in a database.</p> <p>This means you either need to manually create the mapping, or write some script to output this mapping file.</p>
<p>You could use PHP to redirect old URLs to new ones.</p> <pre><code>header("Location: /new.html",TRUE,301); </code></pre> <p>You will still need to redirect requests to this PHP script, but you may find this more flexible and easier to debug than exclusively using mod_rewrite.</p>
30,371
<p>Has anyone come across an example of a non .Net consumer of an ADO.NET Data Service? I am on the second day of looking at what Astoria is and how it can be used. I am also trying to answer why would I use this instead of a web service?</p> <p>After getting my examples running, I kind get the RESTful approach to getting data out the system. And, plugging it into a .net client is incredibly easy. But, then I wondered how a non-.NET consumer would go about it.</p> <p>Any ideas (pointers) definitely appreciated...</p>
<p>Well since ADO.NET Data Services exposes itself as a RESTful service anything that can make RESTful calls to a URI can properly use the service. I think rather than looking for .NET related to X technology you should look up the technology you're using (Python, PHP, Whatever) on how to call RESTful services. Once ADO.NET hosts the data service... it's up and for anyone to use.</p>
<p>To consume an ADO.NET Data Service all that is needed is the ability to make HTTP requests using the GET, POST, PUT and DELETE verbs and to set the Accept header.</p> <p>Not all programming environments offer these, e.g. Silverlight 2 and J2ME can only do GET and POST, <em>not</em> PUT and DELETE. This means that it is not possible to do updates or deletes from a Java Micro Edition client to the latest version of ADO.NET Data Services (1.5 CTP).</p>
34,644
<p>I have some code that uses SMO to populate a list of available SQL Servers and databases. While we no longer support SQL Server 2000, it's possible that the code could get run on a machine that SQL Server 2000 and not have the SMO library installed. I would perfer to check for SMO first and degrade the functionality gracefully instead of blowing up in the user's face. What is best way to detect whether or not SMO is available on a machine?</p> <p>Every example that I have seen through a quick Google scan was a variation of "look for C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll". The problem with that approach is that it only works with SQL Server 2005. If SQL Server 2008 is the only SQL Server installed then the path will be different.</p>
<p>I had a look at the SharedManagementObjects.msi from the SQL2008 R2 feature pack and my Windows Registry (SQL2008 R2 Dev is installed on this machine) and I believe these are the reg keys one should use to detect SMO (All under HKLM):</p> <p>SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion - this is apparently the main key, indicating that some version of SMO is installed.</p> <p>SOFTWARE\Microsoft\Microsoft SQL Server 2008 Redist\SharedManagementObjects\1033\CurrentVersion - this one probably means 2008 English is installed. Probably just checking for the presence of SOFTWARE\Microsoft\Microsoft SQL Server 2008 Redist\SharedManagementObjects would suffice.</p> <p>Same applies to SQL2012: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2012 Redist\SharedManagementObjects\1033\CurrentVersion</p> <p>But NOT SQL2005! even though I do have 2005 installed on this machine as well.</p> <p>One more thing, You'd normally want Microsoft SQL Server System CLR Types as well, since SMO depends on them. The SQLSysClrTypes.msi has only one registry key: SOFTWARE\Microsoft\Microsoft SQL Server\RefCount\SQLSysClrTypes</p>
<p>Just a quick note: HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion\Version doesn't represent the current version that is installed, because there could be several versions installed.</p> <p>The registry key above is being updated when you install a version, so if you've installed SMO 2014 then you should see 12.x, but if afterwards you install SMO 2012, then this version would change to 11.x If you then decides to repair the 2014 installtion, then the version would be again 12.x</p> <p>You should better look at: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2012 Redist\SharedManagementObjects\1033\CurrentVersion</p> <p>or HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server 2014 Redist\SharedManagementObjects\1033\CurrentVersion</p> <p>Does someone knows if the 1033 is guaranteed? (Meaning only english version)</p>
6,391
<p>I am creating an application in java which will be the part of an external application. My application contains a viewport which shows some polygons and stuff like that. The external application needs to get the image of the viewport in gif format. For that it calls a method in an interface (implemented by my application) and my application returns the image. The external application needs to store the image in database (or something related to it which I dont need to worry about).</p> <p>My question is:- What should be the data container type of the image when my application send it to the external application? I mean what should be the return type of the method? Currently my gif encoder class returns a byte array. Is there any other 'better' option?</p>
<p>A byte array could be appropriate if you expect the GIFs to be small, but you might consider using an <code>OutputStream</code> so you can stream bits more efficiently.</p> <p>Even if today you just return a fully-populated <code>ByteArrayOutputStream</code>, this would allow you to change your implementation in future without affecting cilent code.</p>
<p>If your 'application' is actually calling a Java method then it should understand Java return types and you should return java.awt.image.</p> <p>If you are doing this through some kind of remote procedure that can't understand Java types I would return a byte array and let the receiving app decode it.</p>
27,371
<p>I'm using GDI+ in C++. (This issue might exist in C# too). </p> <p>I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.</p> <p>For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".</p> <p>My question is: is this intended or documented behaviour, and how do I disable this? </p> <pre><code>RectF Rect(0,0,32767,32767); RectF Bounds1, Bounds2; graphics-&gt;MeasureString(L"PP", 1, font, Rect, &amp;Bounds1); graphics-&gt;MeasureString(L"PP", 2, font, Rect, &amp;Bounds2); margin = Bounds1.Width * 2 - Bounds2.Width; </code></pre>
<p>It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.</p> <p><a href="http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx" rel="noreferrer">MSDN</a> suggests using a different method if you need more accuracy:</p> <blockquote> <p>To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurecharacterranges.aspx" rel="noreferrer">MeasureCharacterRanges</a> method or one of the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx" rel="noreferrer">MeasureString</a> methods that takes a <a href="http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.aspx" rel="noreferrer">StringFormat</a>, and pass <a href="http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.generictypographic.aspx" rel="noreferrer">GenericTypographic</a>. Also, ensure the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx" rel="noreferrer">TextRenderingHint</a> for the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx" rel="noreferrer">Graphics</a> is <a href="http://msdn.microsoft.com/en-us/library/ssazt6bs.aspx" rel="noreferrer">AntiAlias</a>.</p> </blockquote>
<p>TextRenderer was great for getting the size of the font. But in the drawing loop, using TextRenderer.DrawText was excruciatingly slow compared to graphics.DrawString().</p> <p>Since the width of a string is the problem, your much better off using a combination of TextRenderer.MeasureText and graphics.DrawString..</p>
14,451
<p>Background: At my company we are developing a bunch applications that are using the same core dll's. These dll's are using Spring.net's IoC-container to wire things up (auto-wiring). All applications are using the same spring configuration file, and this configuration file points to many classes in many different dll's. But not all application needs functionality from every dll. But because of the way IoC-containers works, all dll's is loaded for Spring.net to examine the types and check what interfaces they implement and so on.</p> <p>Core question: I understand that it's better to just load the dll's you really use. But is it really bad for memory usage just to load a managed dll? Or is it first then you are using classes in the dll and they are getting JIT'ed that the most memory are used?</p>
<p>If none of the code from the assembly is ever used, then eventually the pages from that assembly will be moved from memory into the page file in favour of actively used pages. In which case, the overall long-term effect is likely to be minor. Although, there will be a negative effect on startup time.</p>
<p>of course loading dll's w/o using them causes slower startup time due to reading the assembly from disk and evidence/security checks. But if memory is your concern you at least can be sure, you won't waste more memory than the size of your assemblies if you really don't use any types within. Of course if those types are specified in the spring configuration, at least those types get loaded into memory and their static initializer (if any) will be executed. In rare cases this might be an issue. JITing is done on by the CLR on a per-method basis, so methods you do not use won't waste cpu+memory.</p> <p>In any case you may split your configuration files into partitions e.g. by putting all object definitions of module A into file moduleA.config, all definitions of module B into file moduleB.config and specify only those modules for your particular application that are really needed.</p> <p>hth, Erich</p> <p>P.S.: I'd also like to suggest you post Spring for .NET relevant questions to our <a href="http://forum.springframework.net/" rel="nofollow noreferrer">community forums</a> - it is more likely to get your questions answered there.</p>
9,550
<p>We have a collection of commercial MFC/C++ applications which we sell using <a href="http://www.roguewave.com/products/stingray.php" rel="nofollow noreferrer">Stingray Objective Toolkit</a>, we have source code license and have ported it in the past to Solaris/IRIX/HP-UX/AIX using <a href="http://en.wikipedia.org/wiki/Bristol_Technology_Inc." rel="nofollow noreferrer">Bristol Technologies WindU</a> (Windows API on UNIX, including MFC). </p> <p>Any long story short recently about 18 months ago we ported Stingray to Win64, but a long a tedious task, during this time I did some research on commercial and open source alternative MFC extension libraries things like <a href="http://www.codeproject.com/KB/MFC/UltimateToolbox.aspx" rel="nofollow noreferrer">Ultimate Toolbox</a> and <a href="http://www.prof-uis.com/" rel="nofollow noreferrer">Prof-UIS</a>.</p> <ul> <li>Has anyone else used Stingray and moved to an alternative? </li> <li>If so which one would you suggest? </li> <li>What were the main perils of the move?</li> </ul>
<p>Yes, we haved moved away from Stingray. It depends on what Stingray components you are using. For the grid control, you can use the free MFC gridcontrol from www.codeproject.com or the commercial one from <a href="http://www.bcgsoft.com/" rel="nofollow noreferrer">http://www.bcgsoft.com/</a>. The free one is OK but development has stalled, so no modern UI rendering etc.</p> <p>The 'layout editor' Stingray component can be replaced by the one from bcgsoft.com, but I don't have experience with that - we rewrote the functionality we needed from that on our own (it was only a subset of what Stingray provided).</p> <p>As for alternative MFC toolboxes, I suggest bcgsoft because part of their toolbox is in the Visual Studio Feature Pack so it's free and fits very well with VS. I have looked at Ultimate Toolbox (stay away from it, stale code that isn't updated anymore) and Prof-UIs (OK but I found it not so easy to integrate).</p> <p>Now that BCG is part of the 'official' MFC I don't see a reason to choose something else than BCG (except for maybe the cost, if you need a free alternative you can look at codeproject).</p>
<p>I have been using Stingray for last eight years or so, and have looked at moving off it a couple of times. So far, I've decided against, principally because I have ported a version to Windows CE &amp; Mobile and don't see much else giving the same solution on this platform. While Stingray isn't perfect, they have now got a 64bit version, and it's a pretty stable product.</p> <p>What I am doing, is replacing the very weak areas of Stingray, such as the XML support, with alternatives. In this case I went with <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">Expat</a> for performance reasons. </p> <p>The perils of moving? You could go from something stable but old fashioned to pretty but flakey ;) In my case, I would also kill a fair number of my automated test scripts that work at GUI level.</p> <p><strong>Edit:</strong> Just to add a bit to the above, I moved from VS2003 to VS2008 this week and at the same time Objective Studio 2006 v2 to Objective Studio 10.1. The transition was pretty seamless, with one minor glitch that was promptly handled by RogueWave tech support. Even this would have gone unnoticed if we didn't have a very extensive GUI regression test suite. IMO, Stingray is a very mature, well supported, feature rich and most importantly stable product. I for won't be moving of it any time soon without very good reason.</p>
9,649
<p>What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.</p>
<p>I don't know of any I've personally used with a C API, but <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a> is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, <a href="http://www.wxpython.org/" rel="nofollow noreferrer">wxPython</a> is a Python wrapper around wxWidgets and it is pretty easy to use.</p>
<p>The easiest to write a new program in would be the one you're most familiar with.<br> The easiest to use, test or distribute would probably be the most cross-platform, most distributed or the most supported one, so GTK+/wx/Qt/Tk?</p> <p>Note that C itself isn't a particularly <em>easy</em> language, especially with the growing object-oriented approach to GUIs.</p> <p>The easiest one to cook up a prototype in a scripting language, then convert to a compiled one might be any toolkit with a scripting language binding (pyGTK, wxPython, etc.)</p> <p>That being said, of the "big" ones, only GTK+ and Tk have a C bindings. wxWidgets, Qt and FLTK were all written in C++ and don't have any C bindings as far as I know.</p> <p>I suggest you look into learning C++ and then comparing the available options. Coding in C++ might feel like coding in a scripting language with great conveniences such as automatic pointers, utility classes and overloaded operators, non-invasive garbage collectors and easy to inherit parent classes all brought to your fingertips by the language itself and your widget toolkit.</p> <p>Then my personal suggestion would be wxWidgets; quite easy to use, better documented than GTKmm and "freer" than Qt.</p>
11,700
<p>If I have two variables containing binary values, how do I append them together as one binary value? For example, if I used WMI to read the registry of two REG_BINARY value, I then want to be able to concatenate the values.</p> <p>VBScript complains of a type mismatch when you try to join with the '&amp;' operator.</p>
<p>REG_BINARY value will be returned as an array of bytes. VBScript may reference an array of bytes in a variable and it may pass this array of bytes either as a variant to another function or as a reference to array of bytes. However VBScript itself can do nothing with the array.</p> <p>You are going to need some other component to do some from of concatenation:-</p> <pre><code>Function ConcatByteArrays(ra, rb) Dim oStream : Set oStream = CreateObject("ADODB.Stream") oStream.Open oStream.Type = 1 'Binary' oStream.Write ra oStream.Write rb oStream.Position = 0 ConcatByteArrays = oStream.Read(LenB(ra) + LenB(rb)) oStream.Close End Function </code></pre> <p>In the above code I'm using the ADODB.Stream object which is ubiquitous on currently supported platforms.</p> <p>If you actually had multiple arrays that you want to concatenate then you could use the following class:-</p> <pre><code>Class ByteArrayBuilder Private moStream Sub Class_Initialize() Set moStream = CreateObject("ADODB.Stream") moStream.Open moStream.Type = 1 End Sub Public Sub Append(rabyt) moStream.Write rabyt End Sub Public Property Get Length Length = moStream.Size End Property Public Function GetArray() moStream.Position = 0 GetArray = moStream.Read(moStream.Size) End Function Sub Class_Terminate() moStream.Close End Sub End Class </code></pre> <p>Call append as many times as you have arrays and retrieve the resulting array with GetArray.</p>
<p>Perhaps...</p> <pre><code>result = CStr(val1) &amp; CStr(val2) </code></pre>
22,317
<p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/" rel="noreferrer">http://somewhere.overtherainbow.com/userid/123424/</a></p> <p>I want you to notice the ending path <strong>/userid/123424/</strong></p> <p>How do you do this in ASP.NET?</p>
<p>This example uses ASP.NET Routing to implement friendly URLs. </p> <p>Examples of the mappings that the application handles are: </p> <p><a href="http://samplesite/userid/1234" rel="noreferrer">http://samplesite/userid/1234</a> - <a href="http://samplesite/users.aspx?userid=1234" rel="noreferrer">http://samplesite/users.aspx?userid=1234</a><br> <a href="http://samplesite/userid/1235" rel="noreferrer">http://samplesite/userid/1235</a> - <a href="http://samplesite/users.aspx?userid=1235" rel="noreferrer">http://samplesite/users.aspx?userid=1235</a> </p> <p>This example uses querystrings and avoids any requirement to modify the code on the aspx page. </p> <h1>Step 1 - add the necessary entries to web.config</h1> <pre><code>&lt;system.web&gt; &lt;compilation debug="true"&gt; &lt;assemblies&gt; … &lt;add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; … &lt;httpModules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;/httpModules&gt; &lt;/system.web&gt; &lt;system.webServer&gt; … &lt;modules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/modules&gt; &lt;handlers … &lt;add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; </code></pre> <h1>Step 2 - add a routing table in global.asax</h1> <p>Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. </p> <pre><code>void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("UseridRoute", new Route ( "userid/{userid}", new CustomRouteHandler("~/users.aspx") )); } </code></pre> <h1>Step 3 - implement the route handler</h1> <p>Add the querystring to the current context before the routing takes place. </p> <pre><code>using System.Web.Compilation; using System.Web.UI; using System.Web; using System.Web.Routing; public class CustomRouteHandler : IRouteHandler { public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { // Add the querystring to the URL in the current context string queryString = "?userid=" + requestContext.RouteData.Values["userid"]; HttpContext.Current.RewritePath( string.Concat( VirtualPath, queryString)); var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; } } </code></pre> <h1>Code from users.aspx</h1> <p>The code on the aspx page for reference. </p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string id = Page.Request.QueryString["userid"]; switch (id) { case "1234": lblUserId.Text = id; lblUserName.Text = "Bill"; break; case "1235": lblUserId.Text = id; lblUserName.Text = "Claire"; break; case "1236": lblUserId.Text = id; lblUserName.Text = "David"; break; default: lblUserId.Text = "0000"; lblUserName.Text = "Unknown"; break; } </code></pre>
<p>Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1</p>
6,720
<p>An obscure puzzle, but it's driving me absolutely nuts:</p> <p>I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine.</p> <p>IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning <code>true</code>). Except it doesn't. It only applies the policy to the <strong><em>first</em></strong> item in the library, and I have absolutely no idea why.</p> <p>It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone?</p> <p>Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away...</p>
<p>There's only a couple of things I can think of to try. First, are you developing on the box where you might be able to use Visual Studio to debug? So just stepping through it.</p> <p>Assuming that's not the case - what I'd do is fire up WinDBG and attach it to the process just before I registered the policy. Turn on first chance exceptions so that it breaks whenever they occur. you can do that by issuing the command "sxe clr" once it is broken in. Here's a little more info about WinDBG:</p> <p><a href="http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx" rel="nofollow noreferrer"><a href="http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx</a></a></p> <p>What I'd do is then watch for First Chance exceptions to be thrown, and do a !PrintException to see what is going on. My guess is that there is an exception being thrown somewhere that is causing the app to stop processing the other items. </p> <p>What does the logic look like for your ProcessListItem? Have you tried just doing a return true to make sure it works?</p>
<p>Some nice ideas there, thanks. The Visual Studio debugger wasn't showing an exception (and I've wrapped everything in try/catch blocks just in case), but I hadn't thought of trying Windbg...</p>
6,885
<p>What factors indicate that a project's solution should not be coded in a dynamic language?</p>
<p>Familiarity and willingness of the programmers to work with the language.</p> <p>Your dynamic language is probably my static language.</p>
<p>How about interop? Is it possible to call a COM component from Ruby or Python?</p>
17,192
<p>Does anybody know a "technique" to discover memory leaks caused by smart pointers? I am currently working on a large project written in <strong>C++</strong> that heavily uses smart pointers with reference counting. Obviously we have some memory leaks caused by smart pointers, that are still referenced somewhere in the code, so that their memory does not get free'd. It's very hard to find the line of code with the "needless" reference, that causes the corresponding object not to be free'd (although it's not of use any longer).</p> <p>I found some advice in the web, that proposed to collect call stacks of the increment/decrement operations of the reference counter. This gives me a good hint, which piece of code has caused the reference counter to get increased or decreased.</p> <p>But what I need is some kind of algorithm that groups the corresponding "increase/decrease call stacks" together. After removing these pairs of call stacks, I hopefully have (at least) one "increase call stack" left over, that shows me the piece of code with the "needless" reference, that caused the corresponding object not to be freed. Now it will be no big deal to fix the leak!</p> <p>But has anybody an idea for an "algorithm" that does the grouping?</p> <p>Development takes place under <strong>Windows XP</strong>.</p> <p>(I hope someone understood, what I tried to explain ...)</p> <p>EDIt: I am talking about leaks caused by circular references.</p>
<p>Note that one source of leaks with <strong>reference-counting smart pointers</strong> are pointers with <strong>circular dependancies</strong>. For example, A have a smart pointer to B, and B have a smart pointer to A. Neither A nor B will be destroyed. You will have to find, and then break the dependancies.</p> <p>If possible, use boost smart pointers, and use shared_ptr for pointers which are supposed to be owners of the data, and weak_ptr for pointers not supposed to call delete.</p>
<p>First step could be to know what class is leaking. Once you know it, you can find who is increasing the reference: 1. put a breakpoint on the constructor of class that is wrapped by shared_ptr. 2. step in with debugger inside shared_ptr when its increasing the reference count: look at variable pn->pi_->use_count_ Take the address of that variable by evaluating expression (something like this: &amp;this->pn->pi_.use_count_), you will get an address 3. In visual studio debugger, go to Debug->New Breakpoint->New Data Breakpoint... Enter the address of the variable 4. Run the program. Your program will stop every time when some point in the code is increasing and decreasing the reference counter. Then you need to check if those are matching.</p>
9,276
<p>What references offer a good summary/tutorial for using RDF/OWL? There seem to be enough tools (Protege, Topbraid, Jena, etc.) that knowing the syntax of the markup languages is not necessary, but knowing the concepts is, of course, still critical. </p> <p>I'm working through the w3c documents (particularly the <a href="http://www.w3.org/TR/rdf-primer/" rel="noreferrer">RDF Primer</a>) but I'd like to find other resources/techniques to use as well.</p>
<p>A very good introduction to the semantic web in comparison to object-oriented languages is this document from W3C: <a href="http://www.w3.org/TR/sw-oosd-primer/" rel="noreferrer">A Semantic Web Primer for Object-Oriented Software Developers</a>. It helped me clarify a lot of things from the beginning.</p>
<p>I've found the linkeddatatools tutorial is easy to understand the basics.</p> <p><a href="http://www.linkeddatatools.com/semantic-web-basics" rel="nofollow">http://www.linkeddatatools.com/semantic-web-basics</a></p>
18,823
<p>I would like to support keyboard shortcuts in my WPF XBAP application, such as <kbd>Ctrl</kbd>+<kbd>O</kbd> for 'Open' etc. How do I disable the browsers built-in keyboard shortcuts and replace them with my own?</p>
<p>You can't disable the browser's built-in handling of keys. It's not your place as browser content to override the browser's own shortcut keys.</p>
<p>Not an answer, but a comment. It would be nice to disable the Backspace key behavior in an XBAP, nothing more annoying than hitting the backspace key while not in an element and the browser navigates you to the previous web page.</p>
15,451
<p>Is it possible for <code>SelectNodes()</code> called on an <code>XmlDocument</code> to return null?</p> <p>My predicament is that I am trying to reach 100% unit test code coverage; ReSharper tells me that I need to guard against a null return from the <code>SelectNodes()</code> method, but I can see no way that an XmlDocument can return null (and therefore, no way to test my guard clause and reach 100% unit test coverage!)</p>
<p>Is it necessary to reach 100% code coverage? Indeed, is it even possible under normal (i.e. controllable, testable) circumstances? </p> <p>We often find that using "syntactic sugar" constructions like the <code>using {}</code> block, there are "hidden" code paths created (most likely <code>finally {}</code> or <code>catch {}</code> blocks) that can't be exercised unless some environmental condition (like a broken socket or broken disk) gets in the way.</p>
<p>If you are calling SelectNodes on the XmlDocument itself and it really is an XmlDocument and not a derived class than SelectNodes won't return null.</p> <p>If you create a descendant class and override the CreateNavigator(XmlNode) method then SelectNodes could return null.</p> <p>Similarly, if you call SelectNodes on an EntityReference, DocumentType or XmlDeclaration node, you'll get null as well</p> <p>In short, for 100% coverage on an XmlDocument or XmlNode you didn't just create, you have to test for null.</p>
8,178
<p>I'm trying to write a windows batch file that can delete files from subdirectories. I would rather not hard code the directory structure in, so I can use this process with other projects.</p> <ul> <li>I need to delete files of X type,</li> <li>I have the parent folder <code>C:\MyProject</code>,</li> <li>There are Y subfolders <code>C:\MyProject\?</code>,</li> <li>There are N files to delete.</li> </ul> <p>Is there a quick <code>del</code> (of type) function I am simply missing?</p>
<p>Actually you can use the standard del command:</p> <pre><code>c: cd MyProject del /S *.type </code></pre> <p>Where type is the extension you want to delete and the /S parameter will check in all subfolders of MyProject.</p>
<p>If the del command didn't have the /S flag to delete recursively, I'd use AWK to do something like this (you'd need the UNIX tools for Windows):</p> <pre><code>dir MyProject\*.* /ad /s /b | gawk "{print \"del \\\"\" $0 \"\\*.type\\\"\";}" | cmd </code></pre> <p>My 2 cents, in case you ever need to do something similar (applying a program to all files of X type in all subfolders) with a command that lacks a recursive flag.</p>
43,799
<p>We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:</p> <pre><code>var tpath = Path.GetTempFileName(); try { using (var sf = new StreamReader(sourcepath)) using (var tf = new StreamWriter(tpath)) { string line; while ((line = sf.ReadLine()) != null) tf.WriteLine(UpdateLine(line)); } File.Delete(sourcepath); File.Move(tpath, sourcepath); } catch { File.Delete(tpath); throw; } </code></pre> <p>If anything throws an exception (file not found, no permission), the original file is left untouched, which is what we want.</p> <p>However, the code has the following problems:</p> <ol> <li><p>Is there a real-world situation where the <code>Delete</code> works but the <code>Move</code> fails? This would delete the original and updated data. This would be bad.</p></li> <li><p>The most common failure is the source file being open from another application, and the <code>Delete</code> fails. This means all the Update work is discarded. Is there a way to see if the source file is deletable at the start, and abandon the update if not?</p></li> <li><p>We have users putting Windows Explorer Summary properties, like Title or Comments, on files. These are discarded when we delete the file. Is there a way to copy the old file's Summary properties to a new file? Should we do this?</p></li> </ol>
<p>The normal way of avoiding the "delete then move fails problem" is:</p> <ul> <li>Write to file.new</li> <li>Move file.current to file.old</li> <li>Move file.new to file.current</li> <li>Delete file.new</li> </ul> <p>Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.</p> <p>Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a <em>reasonable</em> optimisation.</p> <p>Not sure about copying summaries etc, I'm afraid.</p>
<p>I found it useful to wrap this pattern in it's own class.</p> <pre><code>class Program { static void Main( string[] args ) { using( var ft = new FileTransaction( @"C:\MyDir\MyFile.txt" ) ) using( var sw = new StreamWriter( ft.TempPath ) ) { sw.WriteLine( "Hello" ); ft.Commit(); } } } public class FileTransaction :IDisposable { public string TempPath { get; private set; } private readonly string filePath; public FileTransaction( string filePath ) { this.filePath = filePath; this.TempPath = Path.GetTempFileName(); } public void Dispose() { if( TempPath != null ) { try { File.Delete( TempPath ); } catch { } } } public void Commit() { try { var oldPath = filePath + ".old"; File.Move( filePath, oldPath ); } catch {} File.Move( TempPath, filePath ); TempPath = null; } } </code></pre>
42,045
<p>I am having issues converting a png to tiff. The conversion goes fine, but the image is huge. I think the issue is that I am not doing the compression correctly? Anyone have any suggestions??</p> <p>Here is the code sample</p> <pre><code>public static void test() throws IOException { // String fileName = "4958813_1"; String fileName = "4848970_1"; String inFileType = ".PNG"; String outFileType = ".TIFF"; ImageIO.scanForPlugins(); File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType); InputStream fis = new BufferedInputStream(new FileInputStream( fInputFile)); PNGImageReaderSpi spi = new PNGImageReaderSpi(); ImageReader reader = spi.createReaderInstance(); ImageInputStream iis = ImageIO.createImageInputStream(fis); reader.setInput(iis, true); BufferedImage bi = reader.read(0); TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi(); ImageWriter writer = tiffspi.createWriterInstance(); //Iterator&lt;ImageWriter&gt; iter = ImageIO.getImageWritersByFormatName("TIFF"); //ImageWriter writer = iter.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType("LZW"); param.setCompressionQuality(0.5f); File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType); ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile); writer.setOutput(ios); writer.write(bi); } </code></pre>
<p><code>Writer.getDefaultWriteParam()</code> only creates an <code>ImageWriteParam</code> object, it doesn't link it back to anything else.</p> <p>I don't see any mechanism in your code for your modified <code>param</code> object to be subsequently used in the <code>ImageWriter</code>.</p> <p>I believe that instead of:</p> <pre><code>writer.write(bi); </code></pre> <p>you need to use:</p> <pre><code>writer.write(null, new IIOImage(bi, null, null), param); </code></pre>
<p>I don't know Java IO, but generally you want to look at a few things</p> <ol> <li>Can you use JPEG compression instead of LZW?</li> <li>See how to set the TIFF strip size -- if small size is what you want, set it to the height of the image.</li> </ol> <p>Edit: Looks like a TiffWriteParam has the following methods</p> <pre><code>tiffWriteParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT); tiffWriteParam.setTiling(imageWidth, imageHeight, 0, 0); </code></pre> <p>set the imageWidth and imageHeight vars to your image's size. The downside is that it will be slower to read out regions of the image.</p>
35,622
<p>I've been crossing things out on my TODO list. I've recently picked up Colemak. Next I wanted to learn Vim or Emacs. I was leaning towards Vim, however one of its benefits are sticking to the home row. With Colemak, the home row has been changed. I realize that I could remap the keys, but assigning the functionality to different letters is not extremely appealing to me (if there is any relation between letters and their function. I know movement is not correlated but I'm not sure on all the rest.)</p> <p>I don't want to start an argumentative post about text editors, but rather receive comments from Colemak (or Dvorak) users about alternative keymappings and these two editors.</p> <p>Thanks</p>
<p>Glad to see another Colemak user :)</p> <p>For Emacs there really isn't a need to remap, since the initial "shortcuts" aren't designed to be close to each other. If anything, you're gonna be more comfortable using Emacs on Colemak than on Qwerty (at least I was).</p> <p>In Vim it's a lot trickier since hjkl will be completely messed-up. Then again, I've always felt that hlkl was broken and should have instead been jkj; or ijkl, so a remap is probably a good thing. Here's a broader discussion about Colemak+Vim on the Colemak forum: <a href="http://forum.colemak.com/viewtopic.php?id=50" rel="noreferrer">http://forum.colemak.com/viewtopic.php?id=50</a></p>
<p>Here is a <a href="https://stackoverflow.com/questions/165231/vim-dvorak-keybindings-rebindings">previous post</a> that should help you some. There is some discussion on there, some users don't remap. Some do. </p> <p>I am going to remap over the weekend actually. I have for the past year used the default mappings, with Dvorak. </p>
31,645
<p>Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. </p> <p>Consider this code...</p> <pre><code>fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } </code></pre> <p>compared to simply using...</p> <pre><code>Array.Copy(source, target, source.Length); </code></pre> <p>The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <a href="http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx</a>.</p> <p>The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?</p>
<p>It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory.</p> <p>If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.</p>
<p>I believe unsafe code is used if you want to access something outside of the .NET runtime, ie. it is not managed code (no garbage collection and so on). This includes raw calls to the Windows API and all that jazz.</p>
11,103
<p>Just wanted to get an idea for ways (web) developers get round the short fall of (most) WYSIWYG editors, whereby the users that are editing the text aren't always HTML literate enough to produce good/great results.</p> <p>In the past we have resigned ourselves to either locking down the editor or simply not supplying one.</p> <p>What are other peoples experiences?</p>
<p>I came up with a solution that looks pretty good. Some sample XAML that I chalked up in Blend 2.0 SP1 looks like this:</p> <pre><code>&lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="ScreenGlintApplication.Window1" x:Name="Window" Title="Window1" Width="500" Height="250" Background="#FF000000" Foreground="#FF3EE229" &gt; &lt;Grid x:Name="LayoutRoot"&gt; &lt;TextBlock TextWrapping="Wrap" FontSize="40" &gt; &lt;Run Text="This is some sample text to have something to work with. Have a nice day! /Johan"/&gt; &lt;/TextBlock&gt; &lt;Canvas Panel.ZIndex="99" &gt; &lt;Rectangle x:Name="ScreenGlintRect" Width="{Binding Path=ActualWidth, ElementName=Window, Mode=Default}" Height="{Binding Path=ActualHeight, ElementName=Window, Mode=Default}" Opacity="0.4" &gt; &lt;Rectangle.Triggers&gt; &lt;EventTrigger RoutedEvent="Rectangle.Loaded"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="ScreenGlintRect" Storyboard.TargetProperty="(Canvas.Left)" From="-500" To="1000" Duration="0:0:2" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/Rectangle.Triggers&gt; &lt;Rectangle.Fill&gt; &lt;LinearGradientBrush StartPoint="0,1" EndPoint="1,1"&gt; &lt;GradientStop Color="Transparent" Offset="0.0" /&gt; &lt;GradientStop x:Name="GlintColor" Color="LightGreen" Offset="0.50" /&gt; &lt;GradientStop Color="Transparent" Offset="1" /&gt; &lt;/LinearGradientBrush&gt; &lt;/Rectangle.Fill&gt; &lt;/Rectangle&gt; &lt;/Canvas&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>An option is to do this in code behind, which is pretty neat if you want to have granular control of the animation. For example:</p> <pre><code> ScreenGlintRect.Width = Width; ScreenGlintRect.Height = Height; var animation = new DoubleAnimation { Duration = new Duration(TimeSpan.FromSeconds(2)), From = (-Width), To = Width * 2 }; ScreenGlintRect.BeginAnimation(Canvas.LeftProperty, animation); </code></pre> <p>This is the code I'm using and it looks good enough for me. If you got HW acceleration you could try and add some blur to it. You may have to tweak the code and hide/show the rectangle, but basically this is it.</p>
<p>You can put a transparent panel on top like LBugnion said, but don't forget there are many ways you can do this:</p> <ol> <li>Change the visibility of the panel to Hidden. </li> <li>Change the opacity to 0.</li> <li>Change the Alpha of the color to 0.</li> </ol> <p>If you only change the Alpha it still is <em>clickable</em> even when you don't see the color.</p> <p>Off topic but: try to make the effect subtle and maybe have a on/off option. </p>
23,183
<p>Just a random thought, and if I wasn't asking the question myself I'd probably down vote it, but... are screenshots the best way to show printer settings, or would a text version be better? </p> <p>Ok, yes, a screenshot is probably easier to do and post, and will show a familiar UI and be easy on the eye and make it easy to notice errors/improvements. </p> <p>However, having a (standardised) text format would make it <em>searchable</em>. After all, other sites always say, "please copy and paste the error rather than post a screenshot" - because the text in a screenshot is not searchable. </p> <p>Yes, it could/would be a pain to enforce this rule (is it possible to easily export printer settings as a file file?) and/or edit the text version of the settings into the post.</p> <p>This is probably a daft "thought experiment" of an idea... but I thought I'd float it anyway. </p>
<p>Text would probably be best because it is searchable, so things can be found faster then by just looking at the long list of settings available in any slicer/printer/device available with your own eyes.</p> <p>However, as far as I'm aware, exporting settings in text format from a slicer/printer is still wishful thinking due to many factors.</p> <p>I remember a long conversation on the Ultimaker forums a few months ago about this very proposal: being able to export settings in some form, to make it easier for people who are experimenting to follow the various iterations of settings more easily.</p> <p>Some people asked for text format, csv, odt, etc, but the people of Ultimaker ultimately crushed the hopes of everyone by explaining, in technical terms that I did not completely understood, that it wasn't possible without rebuilding the whole thing from scratch.</p> <p>Thus why we're stuck with screenshots for the foreseeable future.</p>
<p>The problem with settings is that there are so much settings, if OP's are asked to post certain settings the OP or the one that helps might miss some other parameters that would be visible in a screenshot. I was able to spot a few problems already using the screenshots.</p> <p>Another thought: "What would you gain by searchable settings?". In case of error messages I am absolutely convinced that you should, but I do not see the advantage for searching/indexing. </p> <p>What does being searchable actually add? Questions and answers are usually not that long to spot certain text when you are on a page, what does it add if it is searchable for the site? E.g. if I would search for <code>combing</code>, you now get some hits, if everyone posts the settings in text you suddenly have many more you need to scroll through...</p>
62
<p>So I was wondering if there are any major differences between the various implementations of the hash algorithms, take the SHA series of algorithms for example. All of them have 3 implementations each, 1 in managed code and 2 wrappers around different native crypto APIs, but are there any major differences between using any of them? I can imagine that the wrapper versions could have higher performance since its being executed in native code, but surley hey all need to perform the exact same calculations and thus provide the same output ie hey are interchangable. Is this correct?</p> <p>For instance SHA512CNG cant be used on XP SP2 (docs are wrong) but SHA512MANAGED can.</p> <hr> <p>@Maxim - Thank you, but not quite what I was asking for. I was asking if there is any difference, other than possibly performance, from using the Managed/CryptoServiceProvider/CNG implementations of a given hash algorithm. With .NET 3.5 you get all of the hash algorithms with three implementations, so</p> <p>SHA512Managed SHA512CryptoServiceProvider SHA512Cng</p> <p>The latter two being wrappers around native APIs. This is true for all SHAxxx implementations for example.</p>
<p>One difference is that the native versions (at least some of them) are FIPS-certified (i.e., approved by the US government), whereas the managed ones are not. If your code happens to be running on a Windows machine that has been configured as "FIPS only", attempts to use the managed versions will fail.</p> <p>Most Windows machines are not configured in that way, but if you're deploying to a government- or defense-oriented (or other highly secure) environment you may run into this situation.</p> <p>See <a href="http://blogs.msdn.com/shawnfa/archive/2005/05/16/417975.aspx" rel="noreferrer">http://blogs.msdn.com/shawnfa/archive/2005/05/16/417975.aspx</a>.</p>
<p>I did a quick and dirty comparison between <code>CNG</code> and <code>managed</code> on SHA512 which is the slowest of all SHA algorithms AFAIK using the code below.</p> <pre><code> static void Main(string[] args) { int loops = 10000000; var data = Encoding.ASCII.GetBytes("123"); var hashLoop = new Action&lt;HashAlgorithm&gt;((HashAlgorithm ha) =&gt; { for (int i = 0; i &lt; loops; i++) ha.ComputeHash(data); }); var t1 = Task.Factory.StartNew(() =&gt; { Time(hashLoop, new SHA512Managed()); }); var t2 = Task.Factory.StartNew(() =&gt; { Time(hashLoop, new SHA512Cng()); }); Task.WaitAll(t1, t2); Console.WriteLine("Benchmark done!"); Console.ReadKey(); } static void Time(Action&lt;HashAlgorithm&gt; action, HashAlgorithm ha) { var sw = new Stopwatch(); sw.Start(); action(ha); sw.Stop(); Console.WriteLine("{1} done in {0}ms", sw.ElapsedMilliseconds, ha.ToString()); } </code></pre> <p>After several runs I found that the difference was that CNG was considerably faster than managed version of the algorithm with about <code>21.7% to 49.5%</code></p>
25,938
<p>I've written a VB.NET application that uses SQL CE 3.5. I'm curious if anyone has any best practice or code to help check if A) SQL CE is installed and B) If so, what version. </p> <p>I searched msdn and google for anything but I didn't find anything helpful. I was poking around the registry and found this key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server Compact Edition\v3.5 with a string value "Version" and the data was 3.5.5692.0. </p> <p>So off the bat my assumption is to check for the presence of this key but it bothers me because the "3.5" key sure sounds like it's tied to the 3.5 DLL. What I'm trying to say is I'd hate to force someone to install SQL 3.5 if they have SQL CE (insert some future version of CE here).</p> <p>Misc info: Target Framework: .NET 2.0 Minimum Target OS: Windows XP SP2</p>
<p>Not sure if you are talking about SQL CE on a Windows machine or a portable device. On a PC, your best bet is to distribute the version of SQL CE with your application. You can register for the rights to do so at <a href="http://www.microsoft.com/Sqlserver/2005/en/us/compact-redistribute.aspx" rel="nofollow noreferrer">http://www.microsoft.com/Sqlserver/2005/en/us/compact-redistribute.aspx</a>.</p>
<p>OK, this only answers the first part of your question, but hope it's useful anyway... This is what I currently use:</p> <pre><code>&lt;Fragment&gt; &lt;util:RegistrySearch Id='SearchForSQLCE' Variable="SQLCEInstalled" Result="exists" Root="HKLM" Key="SOFTWARE\Classes\Microsoft SQL Server Compact Edition Database File" Win64="yes" /&gt; &lt;/Fragment&gt; </code></pre>
32,001