qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
281,380
<p>I am trying to format a date with: </p> <pre><code>&lt;fmt:formatDate value="${newsletter.createdOn}" pattern="MM/dd/yyyy"/&gt; </code></pre> <p>newsletter is an object with a <code>createdOn</code> property which is <code>java.util.Date</code>.</p> <p>When I invoke the previous sentence I get: </p> <p>According to the TLD, the attribute value does not accept expressions. </p> <p>I am importing fmt with </p> <pre><code>&lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %&gt; </code></pre> <p>Does anyone know how can I work around this problem?</p> <p>I am using the jstl.jar coming with tomcat. </p> <p>Under jstl.jar/META-INF/MANIFEST.MF stays: </p> <pre><code>Manifest-Version: 1.0 Ant-Version: Apache Ant 1.5.3 Created-By: 1.4.2-b28 (Sun Microsystems Inc.) Specification-Title: JavaServer Pages Standard Tag Library (JSTL) Specification-Version: 1.1 Implementation-Title: JavaServer Pages Standard Tag Library API Refere nce Implementation Implementation-Version: 1.1.0-D13 Implementation-Vendor: Sun Microsystems, Inc. Implementation-Vendor-Id: com.sun Extension-Name: javax.servlet.jsp.jstl </code></pre> <p>I am using Apache Tomcat Version 6.0.14</p>
[ { "answer_id": 281422, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 5, "selected": false, "text": "<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %>\n" }, { "answer_id": 281425, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "fmt-1_0-rt.tld fmt-1_0.tld rtexprvalue" }, { "answer_id": 281550, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 1, "selected": false, "text": "<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %>\n" }, { "answer_id": 281568, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "web.xml <jsp-config>\n <taglib>\n <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>\n <taglib-location>/WEB-INF/fmt.tld</taglib-location>\n </taglib>\n</jsp-config>\n <%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"/>\n" }, { "answer_id": 5088649, "author": "oli", "author_id": 629823, "author_profile": "https://Stackoverflow.com/users/629823", "pm_score": 1, "selected": false, "text": "<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt_rt\" %>\n" }, { "answer_id": 24552697, "author": "sumit", "author_id": 3801459, "author_profile": "https://Stackoverflow.com/users/3801459", "pm_score": 0, "selected": false, "text": "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix='fmt'%>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
281,383
<p>As the title suggests, I am having trouble maintaining my code on postback. I have a bunch of jQuery code in the Head section and this works fine until a postback occurs after which it ceases to function! </p> <p>How can I fix this? Does the head not get read on postback, and is there a way in which I can force this to happen? </p> <p>JavaScript is:</p> <pre class="lang-html prettyprint-override"><code> &lt;script type="text/javascript"&gt; $(document).ready(function() { $('.tablesorter tbody tr').tablesorter(); $('.tablesearch tbody tr').quicksearch({ position: 'before', attached: 'table.tablesearch', stripeRowClass: ['odd', 'even'], labelText: 'Search:', delay: 100 }); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 281463, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 1, "selected": false, "text": "alert('test');" }, { "answer_id": 1462930, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 2, "selected": false, "text": "function pageLoad(sender, args) {\n\n /* code here */\n\n}\n $(document).ready(function() { ... }); pageLoad()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35454/" ]
281,398
<p>I have an existing web app that allows users to "rate" items based on their difficulty. (0 through 15). Currently, I'm simply taking the average of each user's opinion and presenting the average straight from MySQL. However, it's becoming clear to me (and my users) that weighting the numbers would be more appropriate.</p> <p>Oddly enough, a few hours of Google-ing hasn't turned up much. I did find two articles that showed site-wide ratings systems based off of "Bayesian filters" (which I partially understand). <a href="http://v3.siteframe.org/document.php?id=595" rel="nofollow noreferrer">Here</a>'s one example:</p> <blockquote> <p>The formula is:</p> <p>WR=(V/(V+M)) * R + (M/(V+M)) * C</p> <p>Where:</p> <pre><code>* WR=Weighted Rating (The new rating) * R=Average Rating (arithmetic mean) so far * V=Number of ratings given * M=Minimum number of ratings needed * C=Arithmetic mean rating across the whole site </code></pre> </blockquote> <p>I like the idea here of ramping up the weighting based on the total number of votes per item...however, because the difficulty levels on my site can range drastically from item to item, taking "C" (arithmetic mean rating across the whole site) is not valid. </p> <p>so, a restate of my question:</p> <p>Using MySQL, PHP, or both, I'm try to get from aritmetic mean:</p> <pre><code>(5 + 5 + 4)/3 = 4.67 (rounded) </code></pre> <p>...to a weighted mean:</p> <pre><code>rating / weight 5 / 2 (since it was given 2 times) 5 / 2 4 / 1 (sum[(rate * weight)])/(sum of weights) (5 * 2) + (5 * 2) + (4 * 1) / (2 + 2 + 1) (24)/(5) = 4.8 </code></pre>
[ { "answer_id": 281499, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "select sum(response*ct*ct)/sum(ct*ct) from\n( select response, count(response) as ct from your_table group by response) data\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24708/" ]
281,418
<p>I am using the standard .Net 2.0 DataGridView with sort mode of automatic on the column. It is very very slow (which should probably be another question on how to speed it up) but I can't seem to find an event or combination of events that will maintain a WaitCursor while this sort operation is being performed.</p> <p>Ideas?</p>
[ { "answer_id": 67243965, "author": "DerpyNerd", "author_id": 1536027, "author_profile": "https://Stackoverflow.com/users/1536027", "pm_score": 0, "selected": false, "text": "CellMouseDown CellMouseClick Sorted SortStart DataTable foreach (DataGridViewColumn column in dgvUsers.Columns)\n{\n column.SortMode = DataGridViewColumnSortMode.Programmatic;\n}\n CellMouseDown CellMouseUp mouseDownColumnIndex sortExpression string mouseDownColumnName = \"\";\n string sortExpression = \"\";\n private void dgvUsers_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n {\n mouseDownColumnName = dgvUsers.Columns[e.ColumnIndex].HeaderText;\n }\n\n private void dgvUsers_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)\n {\n if (e.Button == MouseButtons.Left // Obviously\n && e.RowIndex == -1 // column header row index\n && mouseDownColumnName == dgvUsers.Columns[e.ColumnIndex].HeaderText // No drag gesture\n ) {\n dgvUsers.Cursor = Cursors.WaitCursor;\n Task<DataTable> sortAction = Task<DataTable>.Factory.StartNew(() =>\n {\n DataView dvUsers = ((DataTable)dgvUsers.DataSource).DefaultView;\n string headerText = dgvUsers.Columns[e.ColumnIndex].HeaderText;\n if (sortExpression == $\"{headerText} asc\")\n dvUsers.Sort = $\"{headerText} desc\";\n else\n dvUsers.Sort = $\"{headerText} asc\";\n sortExpression = dvUsers.Sort;\n return dvUsers.ToTable();\n });\n sortAction.Wait();\n dgvUsers.DataSource = sortAction.Result;\n\n dgvUsers.Cursor = Cursors.Default;\n }\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36614/" ]
281,436
<p>I have a SSRS 2005 report that has a number of images in it. The way that I have the images included is I have an image object with the URL set in the value property. The actual images are hosted by an IIS virtual directory on the same server. I'm doing it this way because I need to dynamically change the image source using an expression depending on the data within the report. </p> <p>The problem is that the images work great when previewing the report in Visual Studio but do not display when the report is deployed. When I look at the HTML rendered by SSRS the SRC attribute of the image tag is an empty string.</p>
[ { "answer_id": 12333827, "author": "Syed", "author_id": 696799, "author_profile": "https://Stackoverflow.com/users/696799", "pm_score": 0, "selected": false, "text": "< location path=\"Images\" >\n < system.web >\n < authorization >\n < allow users=\"*\" / >\n < /authorization >\n < /system.web >\n < /location >\n" }, { "answer_id": 23566363, "author": "William Mendoza", "author_id": 2579747, "author_profile": "https://Stackoverflow.com/users/2579747", "pm_score": 0, "selected": false, "text": "web.config <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <system.webServer>\n <security>\n <authentication>\n <anonymousAuthentication enabled=\"true\" />\n </authentication>\n </security>\n </system.webServer>\n</configuration>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16980/" ]
281,440
<pre> create table person ( name varchar(15), attr1 varchar(15), attr2 varchar(1), attr3 char(1), attr4 int ) </pre> <p>How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects? Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:</p> <pre><code>@myResults = findAll(attr1 == 3 &amp;&amp; attr2 =~ /abc/); </code></pre>
[ { "answer_id": 665195, "author": "singingfish", "author_id": 36499, "author_profile": "https://Stackoverflow.com/users/36499", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl\nuse warnings;\nuse strict;\nuse DBIx::Class::Schema::Loader qw/ make_schema_at /;\n\nmake_schema_at(\"Zotero::Schema\",\n {\n # components => ['InflateColumn::DateTime'],\n debug => 1,\n relationships => 1,\n dump_directory => './lib' ,\n },\n [\"dbi:SQLite:dbname=../zotero.sqlite\", \"\",\"\"]);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,443
<p>The following source code alerts the following results:</p> <p><strong>Internet Explorer 7</strong>: 29<br> <strong>Firefox 3.0.3</strong>: 37 (correct)<br> <strong>Safari 3.0.4 (523.12.9)</strong>: 38<br> <strong>Google Chrome 0.3.154.9</strong>: 38 </p> <p>Please ignore the following facts: </p> <ul> <li>Webkit (Safari/Chrome) browsers insert an extra text node at the end of the body tag</li> <li>Internet Explorer doesn't have new lines in their whitespace nodes, like they should.</li> <li>Internet Explorer has no beginning whitespace node (there is obvious whitespace before the &lt;form&gt; tag, but no text node to match) </ul> <p>Of the tags in the test page, the following tags have no whitespace text nodes inserted in the DOM after them: <code>form</code>, <code>input[@radio]</code>, <code>div</code>, <code>span</code>, <code>table</code>, <code>ul</code>, <code>a</code>.</p> <p>My question is: <strong>What is it about these nodes that makes them the exception in Internet Explorer?</strong> Why is whitespace not inserted after these nodes, and is inserted in the others? </p> <p>This behavior is the same if you switch the tag order, switch the doctype to XHTML (while still maintaining standards mode).</p> <p>Here's a <a href="http://www.howtocreate.co.uk/wrongWithIE/?chapter=Empty+Space" rel="noreferrer">link that gives a little background information</a>, but no ideal solution. There might not be a solution to this problem, I'm just curious about the behavior.</p> <p>Thanks Internet, Zach</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;script type="text/javascript"&gt; function countNodes() { alert(document.getElementsByTagName('body')[0].childNodes.length); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="countNodes()"&gt; &lt;form&gt;&lt;/form&gt; &lt;input type="submit"/&gt; &lt;input type="reset"/&gt; &lt;input type="button"/&gt; &lt;input type="text"/&gt; &lt;input type="password"/&gt; &lt;input type="file"/&gt; &lt;input type="hidden"/&gt; &lt;input type="checkbox"/&gt; &lt;input type="radio"/&gt; &lt;button&gt;&lt;/button&gt; &lt;select&gt;&lt;/select&gt; &lt;textarea&gt;&lt;/textarea&gt; &lt;div&gt;&lt;/div&gt; &lt;span&gt;&lt;/span&gt; &lt;table&gt;&lt;/table&gt; &lt;ul&gt;&lt;/ul&gt; &lt;a&gt;&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 281592, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<table>\n <thead>\n </thead>\n <tbody>\n </tbody>\n <tfoot>\n </tfoot>\n</table>\n" }, { "answer_id": 289083, "author": "Ishmael", "author_id": 8930, "author_profile": "https://Stackoverflow.com/users/8930", "pm_score": 0, "selected": false, "text": "<INPUT value=\"Submit Query\" type=submit> \n<INPUT value=Reset type=reset> \n<INPUT type=button> \n<INPUT type=text> \n<INPUT value=\"\" type=password> \n<INPUT type=file> \n<INPUT type=hidden>\n<INPUT type=checkbox>\n<INPUT type=radio>\n<BUTTON type=submit></BUTTON> \n<SELECT></SELECT>\n<TEXTAREA></TEXTAREA> \n" }, { "answer_id": 311923, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": true, "text": "<p>\n<input>\n</p>\n <p> <input> var node = element.firstChild;\nwhile(node && node.nodeType == 3) node = node.nextSibling;\n" }, { "answer_id": 16311209, "author": "kaimagpie", "author_id": 2113751, "author_profile": "https://Stackoverflow.com/users/2113751", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<!--REF http://stackoverflow.com/questions/281443/inconsistent-whitespace-text-nodes-in-internet-explorer -->\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<script type=\"text/javascript\">\n function countNodes()\n { alert(document.getElementsByTagName('form')[0].childNodes.length);\n };\n</script>\n</head>\n<body onload=\"countNodes()\">\n <form\n ><input type=\"submit\"/\n ><input type=\"reset\"/\n ><input type=\"button\"/\n ><input type=\"text\"/\n ><input type=\"password\"/\n ><input type=\"file\"/\n ><input type=\"hidden\"/\n ><input type=\"checkbox\"/\n ><input type=\"radio\"/\n ><button></button\n ><select></select\n ><textarea></textarea\n ><div></div\n ><span></span\n ><table></table\n ><ul></ul\n ><a></a\n ></form>\n</body>\n</html>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16711/" ]
281,456
<p>I need to convert several Java classes to C#, but I have faced few problems.</p> <p>In Java I have following class hierarchy:</p> <pre><code>public abstract class AbstractObject { public String getId() { return id; } } public class ConcreteObject extends AbstractObject { public void setId(String id) { this.id= id; } } </code></pre> <p>There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy.</p> <p>How to convert this to C# using properties? Is that possible?</p>
[ { "answer_id": 281469, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "get set NotImplementedException" }, { "answer_id": 281505, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 3, "selected": true, "text": "public abstract class AbstractObject {\n protected string id;\n public string Id\n {\n get { return id; }\n }\n}\n\npublic class ConcreteObject : AbstractObject\n{\n public new string Id\n {\n get { return base.Id; }\n set { id = value; }\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22062/" ]
281,468
<p>I want ajax application to process a simple form with textinput and submit button only , and without validation , i want to add this with a php script . I ask this because i don't know how to program with ajax or javascript .</p>
[ { "answer_id": 281691, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 0, "selected": false, "text": "$(document).ready(function () {\n $('form').ajaxSubmit('#result');\n});\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
281,488
<p>I have a circular, statically allocated buffer in C, which I'm using as a queue for a <strike>depth</strike> breadth first search. I'd like have the top N elements in the queue sorted. It would be easy to just use a regular qsort() - except it's a circular buffer, and the top N elements might wrap around. I could, of course, write my own sorting implementation that uses modular arithmetic and knows how to wrap around the array, but I've always thought that writing sorting functions is a good exercise, but something better left to libraries.</p> <p>I thought of several approaches:</p> <ol> <li>Use a separate linear buffer - first copy the elements from the circular buffer, then apply qsort, then copy them back. Using an additional buffer means an additional O(N) space requirement, which brings me to <ul> <li>Sort the "top" and "bottom" halve using qsort, and then merge them using the additional buffer</li> <li>Same as 2. but do the final merge in-place (I haven't found much on in-place merging, but the implementations I've seen don't seem worth the reduced space complexity)</li> </ul></li> </ol> <p>On the other hand, spending an hour contemplating how to elegantly avoid writing my own quicksort, instead of adding those 25 (or so) lines might not be the most productive either...</p> <p><strong>Correction:</strong> Made a stupid mistake of switching DFS and BFS (I prefer writing a DFS, but in this particular case I have to use a BFS), sorry for the confusion.</p> <p><strong>Further description of the original problem:</strong></p> <p>I'm implementing a <strong>breadth</strong> first search (for something not unlike the <a href="http://en.wikipedia.org/wiki/Fifteen_puzzle" rel="nofollow noreferrer">fifteen</a> puzzle, just more complicated, with about O(n^2) possible expansions in each state, instead of 4). The "bruteforce" algorithm is done, but it's "stupid" - at each point, it expands all valid states, in a hard-coded order. The queue is implemented as a circular buffer (unsigned queue[MAXLENGTH]), and it stores integer indices into a table of states. Apart from two simple functions to queue and dequeue an index, it has no encapsulation - it's just a simple, statically allocated array of unsigned's.</p> <p>Now I want to add some heuristics. The first thing I want to try is to sort the expanded child states after expansion ("expand them in a better order") - just like I would if I were programming a simple best-first DFS. For this, I want to take part of the queue (representing the most recent expanded states), and sort them using some kind of heuristic. I could also expand the states in a different order (so in this case, it's not really important if I break the FIFO properties of the queue).</p> <p>My goal is not to implement <a href="http://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow noreferrer">A*</a>, or a depth first search based algorithm (I can't afford to expand all states, but if I don't, I'll start having problems with infinite cycles in the state space, so I'd have to use something like <a href="http://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search" rel="nofollow noreferrer">iterative deepening</a>).</p>
[ { "answer_id": 281737, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 2, "selected": false, "text": "qsort" }, { "answer_id": 281748, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": true, "text": "libc qsort() qsort O(n) n O(n^2/N) < O(n) []" }, { "answer_id": 288581, "author": "eaanon01", "author_id": 36986, "author_profile": "https://Stackoverflow.com/users/36986", "pm_score": 0, "selected": false, "text": "#define _PRINT_PROGRESS\n#define N 10\nBYTE buff[N]={4,5,2,1,3,5,8,6,4,3};\nBYTE *a = buff;\nBYTE *b = buff;\nBYTE changed = 0;\nint main(void)\n{\n BYTE n=0;\n do\n {\n b++;\n changed = 0;\n for(n=0;n<(N-1);n++)\n {\n if(*a > *b)\n {\n *a ^= *b;\n *b ^= *a;\n *a ^= *b;\n changed = 1;\n }\n a++;\n b++;\n }\n a = buff;\n b = buff;\n#ifdef _PRINT_PROGRESS\n for(n=0;n<N;n++)\n printf(\"%d\",buff[n]);\n printf(\"\\n\");\n }\n#endif\n while(changed);\n system( \"pause\" );\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27610/" ]
281,490
<p>I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?</p>
[ { "answer_id": 281494, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 0, "selected": false, "text": "mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
281,500
<p>I'm trying to connect to an MDF. I've even gone to the lengths of re-installing sql server express entirely (it is now the only flavor of SQL installed on my box, where previously I had 05 dev and express). I've verified that the paths are all correct, and thus far my google-fu hasn't helped.</p> <p>The Full exception message is: </p> <blockquote> <p>Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.</p> </blockquote> <p>The Connection string is:</p> <pre><code>&lt;add name= "CustomerEntities" connectionString="metadata=res://*/Data.CustomerModel.csdl|res://*/Data.CustomerModel.ssdl|res://*/Data.CustomerModel.msl; provider=System.Data.SqlClient; provider connection string='Data Source=.\SQLEXPRESS; AttachDbFilename=\App_Data\CustomerDb.mdf; Integrated Security=True; User Instance=True'" providerName="System.Data.EntityClient" /&gt; </code></pre> <h3>Additional info:</h3> <p>Several of the references to this error I've found online do not apply to me. For example, one I've seen is where this error occurs when trying to start the user instance over remote desktop (I'm doing this locally). While another suggests that it has to do with leftover files from an old express installation ... I've looked in the prescribed locations and not found those artifacts. I also tried running <code>sp_configure 'user instances enabled', '1'</code>, but it said that it was already set to 1.</p>
[ { "answer_id": 281626, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 7, "selected": true, "text": "AttachDbFilename=|DataDirectory|CustomerDb.mdf; c:\\Users\\<user name>\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS Microsoft Sql Server" }, { "answer_id": 17092017, "author": "Hamid Shahid", "author_id": 94897, "author_profile": "https://Stackoverflow.com/users/94897", "pm_score": 0, "selected": false, "text": "\"Data Source=.\\SQLExpress;Initial Catalog=DBFilePath;Integrated Security=SSPI;MultipleActiveResultSets=true\"\n \"Data Source=.\\SQLExpress;Initial Catalog=DBName;Integrated Security=SSPI;MultipleActiveResultSets=true\" \n" }, { "answer_id": 24864601, "author": "sohaiby", "author_id": 1837838, "author_profile": "https://Stackoverflow.com/users/1837838", "pm_score": -1, "selected": false, "text": "sp_configure 'user instances enabled', 1;\n RECONFIGURE\n" }, { "answer_id": 72172246, "author": "iamdeed", "author_id": 13058445, "author_profile": "https://Stackoverflow.com/users/13058445", "pm_score": 0, "selected": false, "text": "<system.webServer>\n <security>\n <authentication>\n <anonymousAuthentication enabled=\"false\" />\n <windowsAuthentication enabled=\"true\" />\n </authentication>\n </security>\n</system.webServer>\n <add name=\"defaultConn\" connectionString=\"Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DB.mdf;Integrated Security=True;User Instance=False;Trusted_Connection=Yes\" providerName=\"System.Data.SqlClient\"/>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
281,503
<p>I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface.</p> <p>I have an interface lets call it Account</p> <pre><code>public interface Account { public void doStuff(); } </code></pre> <p>Now I have two concrete implementors of Account OverSeasAccount and OverDrawnAccount</p> <pre><code>public class OverSeasAccount implements Account { public void doStuff() { //do overseas type stuff } } </code></pre> <p>AND</p> <pre><code>public class OverDrawnAccount implements Account { public void doStuff() { //do overDrawn type stuff } } </code></pre> <p>I have a class called Work with a List</p> <pre><code>private List&lt;Account&gt; accounts; </code></pre> <p>I am looking at discriminator fields but I seem to be only able do this for abstract classes. Is this the case? Any pointers appreciated. Can I use discriminators for interfaces? </p>
[ { "answer_id": 281900, "author": "Andrea Francia", "author_id": 36131, "author_profile": "https://Stackoverflow.com/users/36131", "pm_score": 1, "selected": false, "text": "// not an entity\npublic interface Account {\n public void doStuff();\n}\n\n@Entity\npublic abstract class BaseAccount {\n public void doStuff();\n}\n\n\n@Entity\npublic class OverSeasAccount extends AbstractAccount {\n public void doStuff() { ... }\n}\n\n@Entity\npublic class OverDrawnAccount extends AbstractAccount {\n public void doStuff() { ... }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050/" ]
281,507
<p>Can a Silverlight 2 enabled web page be managed from an Apache server? (I'm not actually interested in doing this but trying to understand Silverlight 2 a bit more.)</p> <p>Assuming that I have IIS6 and Server 2003 what are the .NET version requirements to host a web site with Silverlight 2? Are .NET 3.0 and 3.5 required on the server? My thinking is not because this is a client side technology.</p>
[ { "answer_id": 281519, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "* Windows\n o Operating System: Windows Vista; Windows XP Service Pack 2\n o Intel® Pentium® III 450MHz or faster processor (or equivalent)\n o 128MB of RAM\n* Mac OS\n o Operating System: Apple Mac OS X 10.4.8 or above\n o Intel Core™ Duo 1.83GHz or faster processor\n o 128MB of RAM\n* Linux. For the system requirements, please refer to the Mono Project's Moonlight Web site.\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
281,512
<p>I am having issues converting a png to tiff. The conversion goes fine, but the image is huge. I think the issue is that I am not doing the compression correctly? Anyone have any suggestions??</p> <p>Here is the code sample</p> <pre><code>public static void test() throws IOException { // String fileName = "4958813_1"; String fileName = "4848970_1"; String inFileType = ".PNG"; String outFileType = ".TIFF"; ImageIO.scanForPlugins(); File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType); InputStream fis = new BufferedInputStream(new FileInputStream( fInputFile)); PNGImageReaderSpi spi = new PNGImageReaderSpi(); ImageReader reader = spi.createReaderInstance(); ImageInputStream iis = ImageIO.createImageInputStream(fis); reader.setInput(iis, true); BufferedImage bi = reader.read(0); TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi(); ImageWriter writer = tiffspi.createWriterInstance(); //Iterator&lt;ImageWriter&gt; iter = ImageIO.getImageWritersByFormatName("TIFF"); //ImageWriter writer = iter.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType("LZW"); param.setCompressionQuality(0.5f); File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType); ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile); writer.setOutput(ios); writer.write(bi); } </code></pre>
[ { "answer_id": 281612, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "tiffWriteParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);\ntiffWriteParam.setTiling(imageWidth, imageHeight, 0, 0);\n" }, { "answer_id": 281619, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": true, "text": "Writer.getDefaultWriteParam() ImageWriteParam param ImageWriter writer.write(bi);\n writer.write(null, new IIOImage(bi, null, null), param);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36641/" ]
281,515
<p>I would like to customize the background (and maybe the border too) of all of the UITableViewCells within my UITableView. So far I have not been able to customize this stuff, so I have a bunch of white background cells which is the default.</p> <p>Is there a way to do this with the iPhone SDK?</p>
[ { "answer_id": 290228, "author": "Vladimir Grigorov", "author_id": 22764, "author_profile": "https://Stackoverflow.com/users/22764", "pm_score": 6, "selected": false, "text": "UIView *backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];\nbackgroundView.backgroundColor = [ UIColor yellowColor ];\ncell.backgroundView = backgroundView;\nfor ( UIView *view in cell.contentView.subviews ) \n{\n view.backgroundColor = [ UIColor clearColor ];\n}\n" }, { "answer_id": 1220985, "author": "Nathan B.", "author_id": 149538, "author_profile": "https://Stackoverflow.com/users/149538", "pm_score": 8, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }\n - (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath { ... }\n if (indexPath.row % 2)\n{\n [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];\n}\nelse [cell setBackgroundColor:[UIColor clearColor]];\n" }, { "answer_id": 2657980, "author": "JAG", "author_id": 195165, "author_profile": "https://Stackoverflow.com/users/195165", "pm_score": 4, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath \n{\n UIColor *color = ((indexPath.row % 2) == 0) ? [UIColor colorWithRed:255.0/255 green:255.0/255 blue:145.0/255 alpha:1] : [UIColor clearColor];\n cell.backgroundColor = color;\n}\n" }, { "answer_id": 2803123, "author": "Seba", "author_id": 314624, "author_profile": "https://Stackoverflow.com/users/314624", "pm_score": 7, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n cell.backgroundColor = [UIColor redColor];\n}\n" }, { "answer_id": 4367686, "author": "cipherz", "author_id": 317686, "author_profile": "https://Stackoverflow.com/users/317686", "pm_score": 3, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n\n if ((indexPath.row % 2) == 1) {\n cell.backgroundColor = UIColorFromRGB(0xEDEDED);\n cell.textLabel.backgroundColor = UIColorFromRGB(0xEDEDED);\n cell.selectionStyle = UITableViewCellSelectionStyleGray;\n }\n else\n {\n cell.backgroundColor = [UIColor whiteColor];\n cell.selectionStyle = UITableViewCellSelectionStyleGray;\n }\n\n}\n" }, { "answer_id": 4922087, "author": "albertoFlagSolutions", "author_id": 606529, "author_profile": "https://Stackoverflow.com/users/606529", "pm_score": 2, "selected": false, "text": "UIView *solidColor = [cell viewWithTag:100];\nif (!solidColor) {\n\n solidColor = [[UIView alloc] initWithFrame:cell.bounds];\n solidColor.tag = 100; //Big tag to access the view afterwards\n [cell addSubview:solidColor];\n [cell sendSubviewToBack:solidColor];\n [solidColor release];\n}\nsolidColor.backgroundColor = [UIColor colorWithRed:254.0/255.0\n green:233.0/255.0\n blue:233.0/255.0\n alpha:1.0];\n" }, { "answer_id": 7581848, "author": "Senthil", "author_id": 479533, "author_profile": "https://Stackoverflow.com/users/479533", "pm_score": 2, "selected": false, "text": "UIView *lab = [[UIView alloc] initWithFrame:cell.frame];\n [lab setBackgroundColor:[UIColor grayColor]];\n cell.backgroundView = lab;\n [lab release];\n" }, { "answer_id": 9105770, "author": "gamozzii", "author_id": 758298, "author_profile": "https://Stackoverflow.com/users/758298", "pm_score": 2, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n cell.backgroundColor = cell.contentView.backgroundColor;\n}\n if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {\n cell.contentView.backgroundColor = [UIColor blueColor];\n}\n" }, { "answer_id": 13753006, "author": "JonahGabriel", "author_id": 1607584, "author_profile": "https://Stackoverflow.com/users/1607584", "pm_score": 1, "selected": false, "text": "-(void)layoutSubviews\n{\n [super layoutSubviews];\n self.backgroundColor = [UIColor blueColor];\n}\n" }, { "answer_id": 15076573, "author": "Davide", "author_id": 1721335, "author_profile": "https://Stackoverflow.com/users/1721335", "pm_score": 2, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n UIImage *cellImage = [UIImage imageNamed:@\"myimage.png\"];//myimage is a 20x50 px with gradient color created with gimp\n UIImageView *cellView = [[UIImageView alloc] initWithImage:cellImage];\n cellView.contentMode = UIContentViewModeScaleToFill;\n cell.backgroundView = cellView;\n //set the background label to clear\n cell.titleLabel.backgroundColor= [UIColor clearColor];\n}\n" }, { "answer_id": 15806625, "author": "Bhavesh Nayi", "author_id": 1968952, "author_profile": "https://Stackoverflow.com/users/1968952", "pm_score": 1, "selected": false, "text": " UIView *bg = [[UIView alloc] initWithFrame:cell.frame];\n bg.backgroundColor = [UIColor colorWithRed:175.0/255.0 green:220.0/255.0 blue:186.0/255.0 alpha:1]; \n cell.backgroundView = bg;\n [bg release];\n" }, { "answer_id": 16998190, "author": "Jim Huang", "author_id": 862149, "author_profile": "https://Stackoverflow.com/users/862149", "pm_score": 3, "selected": false, "text": "- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n if (...){\n cell.backgroundColor = [UIColor blueColor];\n } else {\n cell.backgroundColor = [UIColor whiteColor];\n }\n}\n" }, { "answer_id": 33207000, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "- (void)tableView:(UITableView *)tableView1 willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath\n{\n [cell setBackgroundColor:[UIColor clearColor]];\n tableView1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @\"Cream.jpg\"]];\n}\n" }, { "answer_id": 43512681, "author": "Sameera R.", "author_id": 2016932, "author_profile": "https://Stackoverflow.com/users/2016932", "pm_score": 1, "selected": false, "text": "-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {\n cell.backgroundColor = [UIColor grayColor];\n}\n" }, { "answer_id": 72558491, "author": "Mark G", "author_id": 10270556, "author_profile": "https://Stackoverflow.com/users/10270556", "pm_score": -1, "selected": false, "text": "override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n selectionStyle = .none\n}\n\noverride func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n backgroundColor = selected ? .red : .clear\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35478/" ]
281,527
<p>Like any other hard disk, virtual hard discs (*.vhd) will suffer from fragmentation. </p> <p>So to keep good performance i guess i have to defrag first the virtual hard disc from within the virtual machine and also the (physical) hard disc the .vhd is stored on.</p> <p>First, are these assumption correct? And second, is there a way to defrag both (virtual and physical hard disc) at once?</p> <p>Thanks in advance!</p>
[ { "answer_id": 282466, "author": "John Baughman", "author_id": 26923, "author_profile": "https://Stackoverflow.com/users/26923", "pm_score": 3, "selected": false, "text": "jkDefrag -q -a2\njkDefrag -q -a6 C:\\PathToVirtualDisks\\VDiskToDefrag.vhd\njkDefrag -q -a3 -e C:\\PathToVirtualDisks\\VDiskToDefrag.vhd\n -q -a2 -a6 -a3" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4531/" ]
281,531
<p>Most of my PHP apps have an ob_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done.</p> <pre><code>ob_start() //Business Logic, etc header-&gt;output(); echo apply_post_filter(ob_get_clean()); footer-&gt;output(); </code></pre> <p>This ensures that PHP errors get displayed within the content part of the website, and that errors don't interfere with <code>header</code> and <code>session_*</code> calls.</p> <p>My only problem is that with some large pages PHP runs out of memory. How do I stop this from happening?</p> <p>Some ideas:</p> <ol> <li>Write all of the buffered content to a temporary file and output that.</li> <li>When the buffers reaches a certain size, output it. Although this might interfere with the post filter.</li> <li>Raise the memory limit (thanx @troelskn).</li> </ol> <p>Whats the drawbacks on each of these approaches? Especially raising the memory limit?</p>
[ { "answer_id": 283413, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 1, "selected": false, "text": "ini_set('memory_limit','64M');\n" }, { "answer_id": 15505603, "author": "Haravikk", "author_id": 2187548, "author_profile": "https://Stackoverflow.com/users/2187548", "pm_score": 2, "selected": false, "text": "ob_flush()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
281,534
<p>Grasping at straws here... I work with a VB6 desktop system using several 2003-style Access databases (.MDB). Recently, I changed the first function from VB6 to VB.NET, still using an Access database. This is more than a conversion, but a rewrite with additional functionality. It is still fairly simple functionality, with a low-volume database. We have 1400 customers, small businesses with varying machine qualities. Most customers are happy with the new screen and functionality. A very few of those customers have experienced EXTREME slowness loading the datagridview. Customer Service tells us that 1) the machines have at least 1 GB of RAM, and 2) rebooting always solves the problem. </p> <p>I wrote an app to severely slow down my machine, and it STILL runs better for me than it does for those few customers. Also, my Access database has never been trashed by this application. </p> <p>Any suggestions?</p> <p>Thanks!!</p>
[ { "answer_id": 281773, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 3, "selected": true, "text": "\n@echo off\nSystemInfo >c:\\systeminfo.log\ntasklist /v >>c:\\systeminfo.log\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
281,538
<p>Are there major advantages to <a href="https://web.archive.org/web/20090207080811/http://www.innodb.com:80/hot-backup/features/" rel="nofollow noreferrer">InnoDB hot backup</a> vs ZRM <a href="https://www.zmanda.com/zrm-enterprise/" rel="nofollow noreferrer">snapshots</a> in terms of disruption to the running site, the size of compressed backup files, and speed of backup/restore on a medium-sized to largish all-InnoDB database?</p> <p>My understanding is that InnoDB's approach is more reliable, faster, does not cause a significant outage when running, etc.</p>
[ { "answer_id": 281773, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 3, "selected": true, "text": "\n@echo off\nSystemInfo >c:\\systeminfo.log\ntasklist /v >>c:\\systeminfo.log\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
281,563
<p>I'm currently using AntLR to parse some files with a proprietary language. I have a need of highlighting sections of it on an editor (think of highlighting a method in a Java class, for instance).</p> <p>Does anyone has a hint on how to get them? Say I have this code:</p> <pre><code>function test(param1, param2) { } </code></pre> <p>as function is a keyword, the first position I get in the parser is the one of the identifier "test". How can I get the positions from there up to the ending curly brace? The parameters list is dynamic, as one would expect, so you don't know in advance its length.</p> <p>Thank you!</p>
[ { "answer_id": 905885, "author": "fglez", "author_id": 33622, "author_profile": "https://Stackoverflow.com/users/33622", "pm_score": 2, "selected": true, "text": "func: FUNCTION ID '(' ID (',' ID)* ')' {\n System.out.println(\"Position = \" + $FUNCTION.pos);\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
281,579
<p>I'm trying to do Ruby password input with the <a href="http://highline.rubyforge.org/" rel="noreferrer">Highline gem</a> and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:</p> <pre><code>new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false } verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false } </code></pre> <p>And what I'd like to change it to is something like this:</p> <pre><code>foo = Proc.new { |prompt| prompt.echo = false } new_pass = ask("Enter your new password: ") foo verify_pass = ask("Enter again to verify: ") foo </code></pre> <p>Which unfortunately doesn't work. What's the correct way to do this?</p>
[ { "answer_id": 281620, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": "def foo(prompt)\n prompt.echo = false\nend\nnew_pass = ask(\"Enter your new password: \") { |prompt| foo(prompt) }\nverify_pass = ask(\"Enter again to verify: \") { |prompt| foo(prompt) }\n prompt.echo false" }, { "answer_id": 281625, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \") {|x| foo.call(x)}\nverify_pass = ask(\"Enter again to verify: \") {|x| foo.call(x)}\n" }, { "answer_id": 281681, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 7, "selected": true, "text": "foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \", &foo)\nverify_pass = ask(\"Enter again to verify: \", &foo)\n def ask(msg, &block)\n puts block.inspect\nend\n" }, { "answer_id": 281931, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 4, "selected": false, "text": "def ask(question)\n yield(question)\nend\n\nproc = Proc.new { |question| puts question }\nnew_pass = ask(\"Enter your new password: \", &proc)\nverify_pass = ask(\"Enter again to verify: \", &proc)\n" }, { "answer_id": 2884319, "author": "jspooner", "author_id": 68751, "author_profile": "https://Stackoverflow.com/users/68751", "pm_score": 2, "selected": false, "text": "class Array\n def alter_each!\n self.each_with_index do |n, i|\n self[i] = yield(n,i)\n end\n end\n def modify_each!(add_one = true, &block)\n self.each_with_index do |n, i|\n j = (add_one) ? (i + 1) : i\n self[i] = block.call(n,j)\n end\n end\nend\n\na = [\"dog\", \"cat\", \"cow\"]\n\na.alter_each! do |n, i|\n \"#{i}_#{n}\"\nend\n\na.modify_each! false do |n,i|\n \"#{n}_#{i}\"\nend\n\nputs a\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
281,584
<p>Using an ORM approach in applications can often lead to the scenario where you have a collection of objects you've retrieved and would like to display them in a tabular view using a DataGridView.</p> <p>In my (limited) experience, binding collections of objects using a custom BindingList to a DataGridView results in poor performance and unsatisfactory sorting. I'm looking for a generic solution to this problem such that it's straightforward to populate a DataGridView and also extract the underlying objects later.</p> <p>I will describe a good solution I've found, but I'm looking for alternatives.</p>
[ { "answer_id": 281620, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": "def foo(prompt)\n prompt.echo = false\nend\nnew_pass = ask(\"Enter your new password: \") { |prompt| foo(prompt) }\nverify_pass = ask(\"Enter again to verify: \") { |prompt| foo(prompt) }\n prompt.echo false" }, { "answer_id": 281625, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \") {|x| foo.call(x)}\nverify_pass = ask(\"Enter again to verify: \") {|x| foo.call(x)}\n" }, { "answer_id": 281681, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 7, "selected": true, "text": "foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \", &foo)\nverify_pass = ask(\"Enter again to verify: \", &foo)\n def ask(msg, &block)\n puts block.inspect\nend\n" }, { "answer_id": 281931, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 4, "selected": false, "text": "def ask(question)\n yield(question)\nend\n\nproc = Proc.new { |question| puts question }\nnew_pass = ask(\"Enter your new password: \", &proc)\nverify_pass = ask(\"Enter again to verify: \", &proc)\n" }, { "answer_id": 2884319, "author": "jspooner", "author_id": 68751, "author_profile": "https://Stackoverflow.com/users/68751", "pm_score": 2, "selected": false, "text": "class Array\n def alter_each!\n self.each_with_index do |n, i|\n self[i] = yield(n,i)\n end\n end\n def modify_each!(add_one = true, &block)\n self.each_with_index do |n, i|\n j = (add_one) ? (i + 1) : i\n self[i] = block.call(n,j)\n end\n end\nend\n\na = [\"dog\", \"cat\", \"cow\"]\n\na.alter_each! do |n, i|\n \"#{i}_#{n}\"\nend\n\na.modify_each! false do |n,i|\n \"#{n}_#{i}\"\nend\n\nputs a\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3406/" ]
281,586
<p>I want to make custom control which has couple of <code>&lt;input type='checkbox' /&gt;</code> controls which I render in Render method. Is it possible to retain ViewState (e.g. checked or not) on these Controls? </p> <p>There is a way of doing this by using ASP.NET server CheckBox control, adding them in OnLoad event with this.Controls.Add(), and giving them same Ids everytime, but I don't wat to do this :)</p>
[ { "answer_id": 281617, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "bool checked = (bool)(ViewState[\"ThisControlCheckState\"] ?? false);\nif (checked) {\n write(\"<input ... >\");\n}\nelse {\n write(\"<input ... >\");\n}\n ViewState[\"ThisControlCheckState\"] = request.Params[\"checkboxName\"].ToString() == \"1\";\n" }, { "answer_id": 281639, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "Init" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36648/" ]
281,606
<p>Why does UDP have a length field in the header and TCP does not?</p> <p>I am guessing that the length of the segment in TCP is inferred from the IP header but one should be able to do the same for a UDP datagram</p>
[ { "answer_id": 281630, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 1, "selected": false, "text": " +--------+--------+--------+--------+\n | Source Address |\n +--------+--------+--------+--------+\n | Destination Address |\n +--------+--------+--------+--------+\n | zero | PTCL | TCP Length |\n +--------+--------+--------+--------+\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,618
<p>I need my database to be secure in case of the hard drive being stolen.</p> <p>I have not seen many databases (even mainstream ones) claiming to support encryption. </p> <ul> <li>Do you guys know of any databases that support encryption?</li> <li>If I'm using a database that doesn't support encryption, is it a bad idea to encrypt data natively (using java encryption libraries, for example)? Would this potentially cause a problem for databases with strongly typed fields? </li> <li>What other solutions are available for encrypting my database?</li> </ul>
[ { "answer_id": 41123787, "author": "userAndroid", "author_id": 2427218, "author_profile": "https://Stackoverflow.com/users/2427218", "pm_score": 0, "selected": false, "text": "SQLiteDatabase.loadLibs(context);\nSQLiteOpenHelper.getWritableDatabase(“yourSecretKey”):\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,627
<p>I have a flex client that makes service calls to a tomcat server running BlazeDS. I would like to gracefully handle server session timeouts in this environment.</p> <p>I do have security constraints on the service, so the client authenticates against a remote object by initializing a ChannelSet based on the destination, and then logging in using that ChannelSet.</p> <p>After the user is authenticated, if they go get a (long) cup of coffee, their session will inevitably time out.</p> <p>I would like the client to detect the timeout, and return the user back to the login page, with the appropriate informational messages.</p> <p>But I am having difficulty finding the best way to detect this timeout from the client. Is it possible, or must I have the server throw an error when the timeout occurs?</p> <p>Thanks!</p>
[ { "answer_id": 6540057, "author": "RJ Owen", "author_id": 210603, "author_profile": "https://Stackoverflow.com/users/210603", "pm_score": 1, "selected": false, "text": "if(faultEvent.fault.faultCode == \"Client.Error.RequestTimeout\"){\n trace(\"TIMEOUT ERROR\");\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2885/" ]
281,640
<p>How do I get a human-readable file size in bytes abbreviation using .NET?</p> <p><strong>Example</strong>: Take input 7,326,629 and display 6.98 MB</p>
[ { "answer_id": 281665, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": false, "text": "int size = new FileInfo( filePath ).Length / 1024;\nstring humanKBSize = string.Format( \"{0} KB\", size );\nstring humanMBSize = string.Format( \"{0} MB\", size / 1024 );\nstring humanGBSize = string.Format( \"{0} GB\", size / 1024 / 1024 );\n" }, { "answer_id": 281679, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 10, "selected": true, "text": "string[] sizes = { \"B\", \"KB\", \"MB\", \"GB\", \"TB\" };\ndouble len = new FileInfo(filename).Length;\nint order = 0;\nwhile (len >= 1024 && order < sizes.Length - 1) {\n order++;\n len = len/1024;\n}\n\n// Adjust the format string to your preferences. For example \"{0:0.#}{1}\" would\n// show a single decimal place, and no space.\nstring result = String.Format(\"{0:0.##} {1}\", len, sizes[order]);\n" }, { "answer_id": 281684, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 3, "selected": false, "text": "string[] suffixes = { \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\" };\nint s = 0;\nlong size = fileInfo.Length;\n\nwhile (size >= 1024)\n{\n s++;\n size /= 1024;\n}\n\nstring humanReadable = String.Format(\"{0} {1}\", size, suffixes[s]);\n" }, { "answer_id": 281716, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 6, "selected": false, "text": "[DllImport ( \"Shlwapi.dll\", CharSet = CharSet.Auto )]\npublic static extern long StrFormatByteSize ( \n long fileSize\n , [MarshalAs ( UnmanagedType.LPTStr )] StringBuilder buffer\n , int bufferSize );\n\n\n/// <summary>\n/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.\n/// </summary>\n/// <param name=\"filelength\">The numeric value to be converted.</param>\n/// <returns>the converted string</returns>\npublic static string StrFormatByteSize (long filesize) {\n StringBuilder sb = new StringBuilder( 11 );\n StrFormatByteSize( filesize, sb, sb.Capacity );\n return sb.ToString();\n}\n" }, { "answer_id": 4967106, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 5, "selected": false, "text": "public static class Format\n{\n static string[] sizeSuffixes = {\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\" };\n\n public static string ByteSize(long size)\n {\n Debug.Assert(sizeSuffixes.Length > 0);\n\n const string formatTemplate = \"{0}{1:0.#} {2}\";\n\n if (size == 0)\n {\n return string.Format(formatTemplate, null, 0, sizeSuffixes[0]);\n }\n\n var absSize = Math.Abs((double)size);\n var fpPower = Math.Log(absSize, 1000);\n var intPower = (int)fpPower;\n var iUnit = intPower >= sizeSuffixes.Length\n ? sizeSuffixes.Length - 1\n : intPower;\n var normSize = absSize / Math.Pow(1000, iUnit);\n\n return string.Format(\n formatTemplate,\n size < 0 ? \"-\" : null, normSize, sizeSuffixes[iUnit]);\n }\n}\n [TestFixture] public class ByteSize\n{\n [TestCase(0, Result=\"0 B\")]\n [TestCase(1, Result = \"1 B\")]\n [TestCase(1000, Result = \"1 KB\")]\n [TestCase(1500000, Result = \"1.5 MB\")]\n [TestCase(-1000, Result = \"-1 KB\")]\n [TestCase(int.MaxValue, Result = \"2.1 GB\")]\n [TestCase(int.MinValue, Result = \"-2.1 GB\")]\n [TestCase(long.MaxValue, Result = \"9.2 EB\")]\n [TestCase(long.MinValue, Result = \"-9.2 EB\")]\n public string Format_byte_size(long size)\n {\n return Format.ByteSize(size);\n }\n}\n" }, { "answer_id": 4975942, "author": "deepee1", "author_id": 483179, "author_profile": "https://Stackoverflow.com/users/483179", "pm_score": 9, "selected": false, "text": "static String BytesToString(long byteCount)\n{\n string[] suf = { \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\" }; //Longs run out around EB\n if (byteCount == 0)\n return \"0\" + suf[0];\n long bytes = Math.Abs(byteCount);\n int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));\n double num = Math.Round(bytes / Math.Pow(1024, place), 1);\n return (Math.Sign(byteCount) * num).ToString() + suf[place];\n}\n 1024^decimalplaces Console.WriteLine(BytesToString(9223372036854775807)); //Results in 8EB\nConsole.WriteLine(BytesToString(0)); //Results in 0B\nConsole.WriteLine(BytesToString(1024)); //Results in 1KB\nConsole.WriteLine(BytesToString(2000000)); //Results in 1.9MB\nConsole.WriteLine(BytesToString(-9023372036854775807)); //Results in -7.8EB\n Math.Floor Convert.ToInt32 Floor" }, { "answer_id": 10567672, "author": "NET3", "author_id": 1289709, "author_profile": "https://Stackoverflow.com/users/1289709", "pm_score": 3, "selected": false, "text": " /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,\n /// kilobytes, megabytes, or gigabytes, depending on the size.\n /// </summary>\n /// <param name=\"fileSize\">The numeric value to be converted.</param>\n /// <returns>The converted string.</returns>\n public static string FormatByteSize(double fileSize)\n {\n FileSizeUnit unit = FileSizeUnit.B;\n while (fileSize >= 1024 && unit < FileSizeUnit.YB)\n {\n fileSize = fileSize / 1024;\n unit++;\n }\n return string.Format(\"{0:0.##} {1}\", fileSize, unit);\n }\n\n /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,\n /// kilobytes, megabytes, or gigabytes, depending on the size.\n /// </summary>\n /// <param name=\"fileInfo\"></param>\n /// <returns>The converted string.</returns>\n public static string FormatByteSize(FileInfo fileInfo)\n {\n return FormatByteSize(fileInfo.Length);\n }\n}\n\npublic enum FileSizeUnit : byte\n{\n B,\n KB,\n MB,\n GB,\n TB,\n PB,\n EB,\n ZB,\n YB\n}\n" }, { "answer_id": 11124118, "author": "humbads", "author_id": 553396, "author_profile": "https://Stackoverflow.com/users/553396", "pm_score": 7, "selected": false, "text": "// Returns the human-readable file size for an arbitrary, 64-bit file size \n// The default format is \"0.### XB\", e.g. \"4.2 KB\" or \"1.434 GB\"\npublic string GetBytesReadable(long i)\n{\n // Get absolute value\n long absolute_i = (i < 0 ? -i : i);\n // Determine the suffix and readable value\n string suffix;\n double readable;\n if (absolute_i >= 0x1000000000000000) // Exabyte\n {\n suffix = \"EB\";\n readable = (i >> 50);\n }\n else if (absolute_i >= 0x4000000000000) // Petabyte\n {\n suffix = \"PB\";\n readable = (i >> 40);\n }\n else if (absolute_i >= 0x10000000000) // Terabyte\n {\n suffix = \"TB\";\n readable = (i >> 30);\n }\n else if (absolute_i >= 0x40000000) // Gigabyte\n {\n suffix = \"GB\";\n readable = (i >> 20);\n }\n else if (absolute_i >= 0x100000) // Megabyte\n {\n suffix = \"MB\";\n readable = (i >> 10);\n }\n else if (absolute_i >= 0x400) // Kilobyte\n {\n suffix = \"KB\";\n readable = i;\n }\n else\n {\n return i.ToString(\"0 B\"); // Byte\n }\n // Divide by 1024 to get fractional value\n readable = (readable / 1024);\n // Return formatted number with suffix\n return readable.ToString(\"0.### \") + suffix;\n}\n" }, { "answer_id": 12409014, "author": "Berend", "author_id": 1669001, "author_profile": "https://Stackoverflow.com/users/1669001", "pm_score": 1, "selected": false, "text": "string.Format(CultureInfo.CurrentCulture, \"{0:0.##} {1}\", fileSize, unit);" }, { "answer_id": 15065986, "author": "Giles", "author_id": 594006, "author_profile": "https://Stackoverflow.com/users/594006", "pm_score": 2, "selected": false, "text": "public static class LongExtensions\n{\n private static readonly long[] numberOfBytesInUnit;\n private static readonly Func<long, string>[] bytesToUnitConverters;\n\n static LongExtensions()\n {\n numberOfBytesInUnit = new long[6] \n {\n 1L << 10, // Bytes in a Kibibyte\n 1L << 20, // Bytes in a Mebibyte\n 1L << 30, // Bytes in a Gibibyte\n 1L << 40, // Bytes in a Tebibyte\n 1L << 50, // Bytes in a Pebibyte\n 1L << 60 // Bytes in a Exbibyte\n };\n\n // Shift the long (integer) down to 1024 times its number of units, convert to a double (real number), \n // then divide to get the final number of units (units will be in the range 1 to 1023.999)\n Func<long, int, string> FormatAsProportionOfUnit = (bytes, shift) => (((double)(bytes >> shift)) / 1024).ToString(\"0.###\");\n\n bytesToUnitConverters = new Func<long,string>[7]\n {\n bytes => bytes.ToString() + \" B\",\n bytes => FormatAsProportionOfUnit(bytes, 0) + \" KiB\",\n bytes => FormatAsProportionOfUnit(bytes, 10) + \" MiB\",\n bytes => FormatAsProportionOfUnit(bytes, 20) + \" GiB\",\n bytes => FormatAsProportionOfUnit(bytes, 30) + \" TiB\",\n bytes => FormatAsProportionOfUnit(bytes, 40) + \" PiB\",\n bytes => FormatAsProportionOfUnit(bytes, 50) + \" EiB\",\n };\n }\n\n public static string ToReadableByteSizeString(this long bytes)\n {\n if (bytes < 0)\n return \"-\" + Math.Abs(bytes).ToReadableByteSizeString();\n\n int counter = 0;\n while (counter < numberOfBytesInUnit.Length)\n {\n if (bytes < numberOfBytesInUnit[counter])\n return bytesToUnitConverters[counter](bytes);\n counter++;\n }\n return bytesToUnitConverters[counter](bytes);\n }\n}\n" }, { "answer_id": 22366441, "author": "Omar", "author_id": 160823, "author_profile": "https://Stackoverflow.com/users/160823", "pm_score": 5, "selected": false, "text": "System.TimeSpan var maxFileSize = ByteSize.FromKiloBytes(10);\nmaxFileSize.Bytes;\nmaxFileSize.MegaBytes;\nmaxFileSize.GigaBytes;\n // ToString\nByteSize.FromKiloBytes(1024).ToString(); // 1 MB\nByteSize.FromGigabytes(.5).ToString(); // 512 MB\nByteSize.FromGigabytes(1024).ToString(); // 1 TB\n\n// Parsing\nByteSize.Parse(\"5b\");\nByteSize.Parse(\"1.55B\");\n" }, { "answer_id": 23053777, "author": "Jernej Novak", "author_id": 1063571, "author_profile": "https://Stackoverflow.com/users/1063571", "pm_score": 3, "selected": false, "text": "7.Bits().ToString(); // 7 b\n8.Bits().ToString(); // 1 B\n(.5).Kilobytes().Humanize(); // 512 B\n(1000).Kilobytes().ToString(); // 1000 KB\n(1024).Kilobytes().Humanize(); // 1 MB\n(.5).Gigabytes().Humanize(); // 512 MB\n(1024).Gigabytes().ToString(); // 1 TB\n" }, { "answer_id": 31833405, "author": "Mark", "author_id": 1463355, "author_profile": "https://Stackoverflow.com/users/1463355", "pm_score": 4, "selected": false, "text": "private string GetSizeString(long length)\n{\n long B = 0, KB = 1024, MB = KB * 1024, GB = MB * 1024, TB = GB * 1024;\n double size = length;\n string suffix = nameof(B);\n\n if (length >= TB) {\n size = Math.Round((double)length / TB, 2);\n suffix = nameof(TB);\n }\n else if (length >= GB) {\n size = Math.Round((double)length / GB, 2);\n suffix = nameof(GB);\n }\n else if (length >= MB) {\n size = Math.Round((double)length / MB, 2);\n suffix = nameof(MB);\n }\n else if (length >= KB) {\n size = Math.Round((double)length / KB, 2);\n suffix = nameof(KB);\n }\n\n return $\"{size} {suffix}\";\n}\n" }, { "answer_id": 35854271, "author": "Metalogic", "author_id": 487051, "author_profile": "https://Stackoverflow.com/users/487051", "pm_score": 3, "selected": false, "text": "[DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\nprivate static extern long StrFormatKBSize(\n long qdw,\n [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszBuf,\n int cchBuf);\n\npublic static string BytesToString(long byteCount)\n{\n var sb = new StringBuilder(32);\n StrFormatKBSize(byteCount, sb, sb.Capacity);\n return sb.ToString();\n}\n" }, { "answer_id": 44407234, "author": "alvinsay", "author_id": 1448446, "author_profile": "https://Stackoverflow.com/users/1448446", "pm_score": 3, "selected": false, "text": "bytes private static readonly string[] UNITS = new string[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\" };\n\npublic static string FormatSize(ulong bytes)\n{\n int c = 0;\n for (c = 0; c < UNITS.Length; c++)\n {\n ulong m = (ulong)1 << ((c + 1) * 10);\n if (bytes < m)\n break;\n }\n\n double n = bytes / (double)((ulong)1 << (c * 10));\n return string.Format(\"{0:0.##} {1}\", n, UNITS[c]);\n}\n" }, { "answer_id": 46805502, "author": "RooiWillie", "author_id": 1715044, "author_profile": "https://Stackoverflow.com/users/1715044", "pm_score": 2, "selected": false, "text": "private static string ReturnSize(double size, string sizeLabel)\n{\n if (size > 1024)\n {\n if (sizeLabel.Length == 0)\n return ReturnSize(size / 1024, \"KB\");\n else if (sizeLabel == \"KB\")\n return ReturnSize(size / 1024, \"MB\");\n else if (sizeLabel == \"MB\")\n return ReturnSize(size / 1024, \"GB\");\n else if (sizeLabel == \"GB\")\n return ReturnSize(size / 1024, \"TB\");\n else\n return ReturnSize(size / 1024, \"PB\");\n }\n else\n {\n if (sizeLabel.Length > 0)\n return string.Concat(size.ToString(\"0.00\"), sizeLabel);\n else\n return string.Concat(size.ToString(\"0.00\"), \"Bytes\");\n }\n}\n return ReturnSize(size, string.Empty);\n" }, { "answer_id": 49535675, "author": "DKH", "author_id": 5452928, "author_profile": "https://Stackoverflow.com/users/5452928", "pm_score": 4, "selected": false, "text": "public static string ToBytesCount(this long bytes)\n{\n int unit = 1024;\n string unitStr = \"B\";\n if (bytes < unit)\n {\n return string.Format(\"{0} {1}\", bytes, unitStr);\n }\n int exp = (int)(Math.Log(bytes) / Math.Log(unit));\n return string.Format(\"{0:##.##} {1}{2}\", bytes / Math.Pow(unit, exp), \"KMGTPEZY\"[exp - 1], unitStr);\n}\n public static string ToBytesCount(this long bytes, bool isISO = true)\n{\n int unit = isISO ? 1024 : 1000;\n string unitStr = \"B\";\n if (bytes < unit)\n {\n return string.Format(\"{0} {1}\", bytes, unitStr);\n }\n int exp = (int)(Math.Log(bytes) / Math.Log(unit));\n return string.Format(\"{0:##.##} {1}{2}{3}\", bytes / Math.Pow(unit, exp), \"KMGTPEZY\"[exp - 1], isISO ? \"i\" : \"\", unitStr);\n}\n" }, { "answer_id": 53406079, "author": "masterwok", "author_id": 563509, "author_profile": "https://Stackoverflow.com/users/563509", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Convert a byte count into a human readable size string.\n/// </summary>\n/// <param name=\"bytes\">The byte count.</param>\n/// <param name=\"si\">Whether or not to use SI units.</param>\n/// <returns>A human readable size string.</returns>\npublic static string ToHumanReadableByteCount(\n this long bytes\n , bool si\n)\n{\n var unit = si\n ? 1000\n : 1024;\n\n if (bytes < unit)\n {\n return $\"{bytes} B\";\n }\n\n var exp = (int) (Math.Log(bytes) / Math.Log(unit));\n\n return $\"{bytes / Math.Pow(unit, exp):F2} \" +\n $\"{(si ? \"kMGTPE\" : \"KMGTPE\")[exp - 1] + (si ? string.Empty : \"i\")}B\";\n}\n" }, { "answer_id": 64881832, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 0, "selected": false, "text": "Log10 using System;\n\nclass Program {\n static string NumberFormat(double n) {\n var n2 = (int)Math.Log10(n) / 3;\n var n3 = n / Math.Pow(1e3, n2);\n return String.Format(\"{0:f3}\", n3) + new[]{\"\", \" k\", \" M\", \" G\"}[n2];\n }\n\n static void Main() {\n var s = NumberFormat(9012345678);\n Console.WriteLine(s == \"9.012 G\");\n }\n}\n" }, { "answer_id": 65996342, "author": "Kim Homann", "author_id": 5773733, "author_profile": "https://Stackoverflow.com/users/5773733", "pm_score": 2, "selected": false, "text": "StrFormatByteSize() using System.Runtime.InteropServices;\n private long mFileSize;\n\n[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Auto)]\npublic static extern int StrFormatByteSize(\n long fileSize,\n [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,\n int bufferSize);\n \npublic string HumanReadableFileSize\n{\n get\n {\n var sb = new StringBuilder(20);\n StrFormatByteSize(mFileSize, sb, 20);\n return sb.ToString();\n }\n}\n" }, { "answer_id": 69075216, "author": "dkackman", "author_id": 155537, "author_profile": "https://Stackoverflow.com/users/155537", "pm_score": 0, "selected": false, "text": "public static string ToBytesString(this BigInteger byteCount, string format = \"N3\")\n{\n string[] suf = { \"B\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"YiB\" };\n if (byteCount.IsZero)\n {\n return $\"{0.0.ToString(format)} {suf[0]}\";\n }\n\n var abs = BigInteger.Abs(byteCount);\n var place = Convert.ToInt32(Math.Floor(BigInteger.Log(abs, 1024)));\n var pow = Math.Pow(1024, place);\n\n // since we need to do this with integer math, get the quotient and remainder\n var quotient = BigInteger.DivRem(abs, new BigInteger(pow), out var remainder);\n // convert the remainder to a ratio and add both back together as doubles\n var num = byteCount.Sign * (Math.Floor((double)quotient) + ((double)remainder / pow));\n\n return $\"{num.ToString(format)} {suf[place]}\";\n}\n" }, { "answer_id": 71561573, "author": "David V McKay", "author_id": 250988, "author_profile": "https://Stackoverflow.com/users/250988", "pm_score": -1, "selected": false, "text": "const String prefixes = \" KMGTPEY\";\n/// <summary> Returns the human-readable file size for an arbitrary, 64-bit file size. </summary>\npublic static String HumanSize(UInt64 bytes)\n => Enumerable\n .Range(0, prefixes.Length)\n .Where(i => bytes < 1024U<<(i*10))\n .Select(i => $\"{(bytes>>(10*i-10))/1024:0.###} {prefixes[i]}B\")\n .First();\n /// <summary>\n/// Returns the human-readable file size for an arbitrary, 64-bit file size.\n/// </summary>\npublic static String HumanSize(UInt64 bytes)\n{\n const String prefixes = \" KMGTPEY\";\n for (var i = 0; i < prefixes.Length; i++)\n if (bytes < 1024U<<(i*10))\n return $\"{(bytes>>(10*i-10))/1024:0.###} {prefixes[i]}B\";\n\n throw new ArgumentOutOfRangeException(nameof(bytes));\n}\n" }, { "answer_id": 71621946, "author": "SN74H74N", "author_id": 2896816, "author_profile": "https://Stackoverflow.com/users/2896816", "pm_score": -1, "selected": false, "text": "public static string PrettyPrintBytes(long numBytes)\n{\n if (numBytes < 1024)\n return $\"{numBytes} B\";\n \n if (numBytes < 1048576)\n return $\"{numBytes / 1024d:0.##} KB\";\n\n if (numBytes < 1073741824)\n return $\"{numBytes / 1048576d:0.##} MB\";\n\n if (numBytes < 1099511627776)\n return $\"{numBytes / 1073741824d:0.##} GB\";\n\n if (numBytes < 1125899906842624)\n return $\"{numBytes / 1099511627776d:0.##} TB\";\n \n if (numBytes < 1152921504606846976)\n return $\"{numBytes / 1125899906842624d:0.##} PB\";\n\n return $\"{numBytes / 1152921504606846976d:0.##} EB\";\n}\n" }, { "answer_id": 73842309, "author": "kellybs1", "author_id": 20081009, "author_profile": "https://Stackoverflow.com/users/20081009", "pm_score": 0, "selected": false, "text": "// <summary>\n/// <paramref name=\"byteCount\"/> The original size in bytes ( 8 bits )\n/// <paramref name=\"notationFormat\"/> is supported in the following ways:\n/// [ 'B' / 'b' : Binary : Kilobyte (KB) is 1024 bytes, Megabyte (MB) is 1048576 bytes, etc ]\n/// [ 'I' / 'i' : IEC: Kibibyte (KiB) is 1024 bytes, Mebibyte (MiB) is 1048576 bytes, etc ]\n/// [ 'D' / 'd' : Decimal : Kilobyte (KB) is 1000 bytes, Megabyte (MB) is 1000000 bytes, etc ]\n/// </summary>\n\npublic static string ToDataSizeString( this long byteCount, char notationFormat = 'b' )\n{\n char[] supportedFormatChars = { 'b', 'i', 'd' };\n\n var lowerCaseNotationFormat = char.ToLowerInvariant( notationFormat );\n\n // Stop shooting holes in my ship!\n if ( !supportedFormatChars.Contains( lowerCaseNotationFormat ) )\n {\n throw new ArgumentException( $\"notationFormat argument '{notationFormat}' not supported\" );\n }\n\n long ebLimit = 1152921504606846976;\n long pbLimit = 1125899906842624;\n long tbLimit = 1099511627776;\n long gbLimit = 1073741824;\n long mbLimit = 1048576;\n long kbLimit = 1024;\n\n var ebSuffix = \"EB\";\n var pbSuffix = \"PB\";\n var tbSuffix = \"TB\";\n var gbSuffix = \"GB\";\n var mbSuffix = \"MB\";\n var kbSuffix = \"KB\";\n var bSuffix = \" B\";\n\n switch ( lowerCaseNotationFormat )\n {\n case 'b':\n // Sweet as\n break;\n\n case 'i':\n // Limits stay the same, suffixes need changed\n ebSuffix = \"EiB\";\n pbSuffix = \"PiB\";\n tbSuffix = \"TiB\";\n gbSuffix = \"GiB\";\n mbSuffix = \"MiB\";\n kbSuffix = \"KiB\";\n bSuffix = \" B\";\n break;\n\n case 'd':\n // Suffixes stay the same, limits need changed\n ebLimit = 1000000000000000000;\n pbLimit = 1000000000000000;\n tbLimit = 1000000000000;\n gbLimit = 1000000000;\n mbLimit = 1000000;\n kbLimit = 1000;\n break;\n\n default:\n // Should have already Excepted, but hey whatever\n throw new ArgumentException( $\"notationFormat argument '{notationFormat}' not supported\" );\n\n }\n\n string fileSizeText;\n\n // Exa/Exbi sized\n if ( byteCount >= ebLimit )\n {\n fileSizeText = $\"{( (double)byteCount / ebLimit ):N1} {ebSuffix}\";\n }\n // Peta/Pebi sized\n else if ( byteCount >= pbLimit )\n {\n fileSizeText = $\"{( (double)byteCount / pbLimit ):N1} {pbSuffix}\";\n }\n // Tera/Tebi sized\n else if ( byteCount >= tbLimit )\n {\n fileSizeText = $\"{( (double)byteCount / tbLimit ):N1} {tbSuffix}\";\n }\n // Giga/Gibi sized\n else if ( byteCount >= gbLimit )\n {\n fileSizeText = $\"{( (double)byteCount / gbLimit ):N1} {gbSuffix}\";\n }\n // Mega/Mibi sized\n else if ( byteCount >= mbLimit )\n {\n fileSizeText = $\"{( (double)byteCount / mbLimit ):N1} {mbSuffix}\";\n }\n // Kilo/Kibi sized\n else if ( byteCount >= kbLimit )\n {\n fileSizeText = $\"{( (double)byteCount / kbLimit ):N1} {kbSuffix}\";\n }\n // Byte sized\n else\n {\n fileSizeText = $\"{byteCount} {bSuffix}\";\n }\n\n return fileSizeText;\n}\n" }, { "answer_id": 74586340, "author": "Stanislav Vladev", "author_id": 9575469, "author_profile": "https://Stackoverflow.com/users/9575469", "pm_score": 0, "selected": false, "text": "public string[] DetermineDigitalSize(string filename)\n {\n string[] result = new string[2];\n string[] sizes = { \"B\", \"KB\", \"MB\", \"GB\", \"GB\" };\n double len = new FileInfo(filename).Length;\n double adjustedSize = len;\n double testSize = 0;\n int order = 0;\n while (order< sizes.Length-1)\n {\n testSize = adjustedSize / 1024;\n if (testSize >= 1) { adjustedSize = testSize; order++; }\n else { break; }\n }\n result[0] = $\"{adjustedSize:f2}\";\n result[1] = sizes[order];\n return result;\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
281,652
<p>Is there a tsql command on sqlserver 2008 which can be run in order to enable Database Diagramming instead of this dialog appearing:</p> <p>This database does not have one or more of the support objects required to use database diagramming. Do you wish to create them? </p>
[ { "answer_id": 36057298, "author": "HarrySolsem", "author_id": 261271, "author_profile": "https://Stackoverflow.com/users/261271", "pm_score": 1, "selected": false, "text": "IF OBJECT_ID(N'dbo.sp_upgraddiagrams') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_upgraddiagrams\n AS\n BEGIN\n IF OBJECT_ID(N''dbo.sysdiagrams'') IS NOT NULL\n return 0;\n\n CREATE TABLE dbo.sysdiagrams\n (\n name sysname NOT NULL,\n principal_id int NOT NULL, -- we may change it to varbinary(85)\n diagram_id int PRIMARY KEY IDENTITY,\n version int,\n\n definition varbinary(max)\n CONSTRAINT UK_principal_name UNIQUE\n (\n principal_id,\n name\n )\n );\n\n\n /* Add this if we need to have some form of extended properties for diagrams */\n /*\n IF OBJECT_ID(N''dbo.sysdiagram_properties'') IS NULL\n BEGIN\n CREATE TABLE dbo.sysdiagram_properties\n (\n diagram_id int,\n name sysname,\n value varbinary(max) NOT NULL\n )\n END\n */\n\n IF OBJECT_ID(N''dbo.dtproperties'') IS NOT NULL\n begin\n insert into dbo.sysdiagrams\n (\n [name],\n [principal_id],\n [version],\n [definition]\n )\n select \n convert(sysname, dgnm.[uvalue]),\n DATABASE_PRINCIPAL_ID(N''dbo''), -- will change to the sid of sa\n 0, -- zero for old format, dgdef.[version],\n dgdef.[lvalue]\n from dbo.[dtproperties] dgnm\n inner join dbo.[dtproperties] dggd on dggd.[property] = ''DtgSchemaGUID'' and dggd.[objectid] = dgnm.[objectid] \n inner join dbo.[dtproperties] dgdef on dgdef.[property] = ''DtgSchemaDATA'' and dgdef.[objectid] = dgnm.[objectid]\n\n where dgnm.[property] = ''DtgSchemaNAME'' and dggd.[uvalue] like N''_EA3E6268-D998-11CE-9454-00AA00A3F36E_'' \n return 2;\n end\n return 1;\n END\n '\n\n\nEND\n\n-- This sproc could be executed by any other users than dbo\nIF IS_MEMBER('db_owner') = 1\n EXEC dbo.sp_upgraddiagrams;\n\nIF OBJECT_ID(N'dbo.sp_helpdiagrams') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_helpdiagrams\n (\n @diagramname sysname = NULL,\n @owner_id int = NULL\n )\n WITH EXECUTE AS N''dbo''\n AS\n BEGIN\n DECLARE @user sysname\n DECLARE @dboLogin bit\n EXECUTE AS CALLER;\n SET @user = USER_NAME();\n SET @dboLogin = CONVERT(bit,IS_MEMBER(''db_owner''));\n REVERT;\n SELECT\n [Database] = DB_NAME(),\n [Name] = name,\n [ID] = diagram_id,\n [Owner] = USER_NAME(principal_id),\n [OwnerID] = principal_id\n FROM\n sysdiagrams\n WHERE\n (@dboLogin = 1 OR USER_NAME(principal_id) = @user) AND\n (@diagramname IS NULL OR name = @diagramname) AND\n (@owner_id IS NULL OR principal_id = @owner_id)\n ORDER BY\n 4, 5, 1\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_helpdiagrams TO public\n DENY EXECUTE ON dbo.sp_helpdiagrams TO guest\nEND\n\nIF OBJECT_ID(N'dbo.sp_helpdiagramdefinition') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_helpdiagramdefinition\n (\n @diagramname sysname,\n @owner_id int = null \n )\n WITH EXECUTE AS N''dbo''\n AS\n BEGIN\n set nocount on\n\n declare @theId int\n declare @IsDbo int\n declare @DiagId int\n declare @UIDFound int\n\n if(@diagramname is null)\n begin\n RAISERROR (N''E_INVALIDARG'', 16, 1);\n return -1\n end\n\n execute as caller;\n select @theId = DATABASE_PRINCIPAL_ID();\n select @IsDbo = IS_MEMBER(N''db_owner'');\n if(@owner_id is null)\n select @owner_id = @theId;\n revert; \n\n select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname;\n if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId ))\n begin\n RAISERROR (''Diagram does not exist or you do not have permission.'', 16, 1);\n return -3\n end\n\n select version, definition FROM dbo.sysdiagrams where diagram_id = @DiagId ; \n return 0\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_helpdiagramdefinition TO public\n DENY EXECUTE ON dbo.sp_helpdiagramdefinition TO guest\nEND\n\nIF OBJECT_ID(N'dbo.sp_creatediagram') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_creatediagram\n (\n @diagramname sysname,\n @owner_id int = null, \n @version int,\n @definition varbinary(max)\n )\n WITH EXECUTE AS ''dbo''\n AS\n BEGIN\n set nocount on\n\n declare @theId int\n declare @retval int\n declare @IsDbo int\n declare @userName sysname\n if(@version is null or @diagramname is null)\n begin\n RAISERROR (N''E_INVALIDARG'', 16, 1);\n return -1\n end\n\n execute as caller;\n select @theId = DATABASE_PRINCIPAL_ID(); \n select @IsDbo = IS_MEMBER(N''db_owner'');\n revert; \n\n if @owner_id is null\n begin\n select @owner_id = @theId;\n end\n else\n begin\n if @theId <> @owner_id\n begin\n if @IsDbo = 0\n begin\n RAISERROR (N''E_INVALIDARG'', 16, 1);\n return -1\n end\n select @theId = @owner_id\n end\n end\n -- next 2 line only for test, will be removed after define name unique\n if EXISTS(select diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @diagramname)\n begin\n RAISERROR (''The name is already used.'', 16, 1);\n return -2\n end\n\n insert into dbo.sysdiagrams(name, principal_id , version, definition)\n VALUES(@diagramname, @theId, @version, @definition) ;\n\n select @retval = @@IDENTITY \n return @retval\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_creatediagram TO public\n DENY EXECUTE ON dbo.sp_creatediagram TO guest\nEND\n\nIF OBJECT_ID(N'dbo.sp_renamediagram') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_renamediagram\n (\n @diagramname sysname,\n @owner_id int = null,\n @new_diagramname sysname\n\n )\n WITH EXECUTE AS ''dbo''\n AS\n BEGIN\n set nocount on\n declare @theId int\n declare @IsDbo int\n\n declare @UIDFound int\n declare @DiagId int\n declare @DiagIdTarg int\n declare @u_name sysname\n if((@diagramname is null) or (@new_diagramname is null))\n begin\n RAISERROR (''Invalid value'', 16, 1);\n return -1\n end\n\n EXECUTE AS CALLER;\n select @theId = DATABASE_PRINCIPAL_ID();\n select @IsDbo = IS_MEMBER(N''db_owner''); \n if(@owner_id is null)\n select @owner_id = @theId;\n REVERT;\n\n select @u_name = USER_NAME(@owner_id)\n\n select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname \n if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))\n begin\n RAISERROR (''Diagram does not exist or you do not have permission.'', 16, 1)\n return -3\n end\n\n -- if((@u_name is not null) and (@new_diagramname = @diagramname)) -- nothing will change\n -- return 0;\n\n if(@u_name is null)\n select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @new_diagramname\n else\n select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @owner_id and name = @new_diagramname\n\n if((@DiagIdTarg is not null) and @DiagId <> @DiagIdTarg)\n begin\n RAISERROR (''The name is already used.'', 16, 1);\n return -2\n end \n\n if(@u_name is null)\n update dbo.sysdiagrams set [name] = @new_diagramname, principal_id = @theId where diagram_id = @DiagId\n else\n update dbo.sysdiagrams set [name] = @new_diagramname where diagram_id = @DiagId\n return 0\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_renamediagram TO public\n DENY EXECUTE ON dbo.sp_renamediagram TO guest\nEND\n\nIF OBJECT_ID(N'dbo.sp_alterdiagram') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_alterdiagram\n (\n @diagramname sysname,\n @owner_id int = null,\n @version int,\n @definition varbinary(max)\n )\n WITH EXECUTE AS ''dbo''\n AS\n BEGIN\n set nocount on\n\n declare @theId int\n declare @retval int\n declare @IsDbo int\n\n declare @UIDFound int\n declare @DiagId int\n declare @ShouldChangeUID int\n\n if(@diagramname is null)\n begin\n RAISERROR (''Invalid ARG'', 16, 1)\n return -1\n end\n\n execute as caller;\n select @theId = DATABASE_PRINCIPAL_ID(); \n select @IsDbo = IS_MEMBER(N''db_owner''); \n if(@owner_id is null)\n select @owner_id = @theId;\n revert;\n\n select @ShouldChangeUID = 0\n select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname \n\n if(@DiagId IS NULL or (@IsDbo = 0 and @theId <> @UIDFound))\n begin\n RAISERROR (''Diagram does not exist or you do not have permission.'', 16, 1);\n return -3\n end\n\n if(@IsDbo <> 0)\n begin\n if(@UIDFound is null or USER_NAME(@UIDFound) is null) -- invalid principal_id\n begin\n select @ShouldChangeUID = 1 ;\n end\n end\n\n -- update dds data \n update dbo.sysdiagrams set definition = @definition where diagram_id = @DiagId ;\n\n -- change owner\n if(@ShouldChangeUID = 1)\n update dbo.sysdiagrams set principal_id = @theId where diagram_id = @DiagId ;\n\n -- update dds version\n if(@version is not null)\n update dbo.sysdiagrams set version = @version where diagram_id = @DiagId ;\n\n return 0\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_alterdiagram TO public\n DENY EXECUTE ON dbo.sp_alterdiagram TO guest\nEND\n\nIF OBJECT_ID(N'dbo.sp_dropdiagram') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE PROCEDURE dbo.sp_dropdiagram\n (\n @diagramname sysname,\n @owner_id int = null\n )\n WITH EXECUTE AS ''dbo''\n AS\n BEGIN\n set nocount on\n declare @theId int\n declare @IsDbo int\n\n declare @UIDFound int\n declare @DiagId int\n\n if(@diagramname is null)\n begin\n RAISERROR (''Invalid value'', 16, 1);\n return -1\n end\n\n EXECUTE AS CALLER;\n select @theId = DATABASE_PRINCIPAL_ID();\n select @IsDbo = IS_MEMBER(N''db_owner''); \n if(@owner_id is null)\n select @owner_id = @theId;\n REVERT; \n\n select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname \n if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))\n begin\n RAISERROR (''Diagram does not exist or you do not have permission.'', 16, 1)\n return -3\n end\n\n delete from dbo.sysdiagrams where diagram_id = @DiagId;\n\n return 0;\n END\n '\n\n\n GRANT EXECUTE ON dbo.sp_dropdiagram TO public\n DENY EXECUTE ON dbo.sp_dropdiagram TO guest\nEND\n\nIF OBJECT_ID(N'dbo.fn_diagramobjects') IS NULL and IS_MEMBER('db_owner') = 1\nBEGIN\n EXEC sp_executesql N'\n CREATE FUNCTION dbo.fn_diagramobjects() \n RETURNS int\n WITH EXECUTE AS N''dbo''\n AS\n BEGIN\n declare @id_upgraddiagrams int\n declare @id_sysdiagrams int\n declare @id_helpdiagrams int\n declare @id_helpdiagramdefinition int\n declare @id_creatediagram int\n declare @id_renamediagram int\n declare @id_alterdiagram int \n declare @id_dropdiagram int\n declare @InstalledObjects int\n\n select @InstalledObjects = 0\n\n select @id_upgraddiagrams = object_id(N''dbo.sp_upgraddiagrams''),\n @id_sysdiagrams = object_id(N''dbo.sysdiagrams''),\n @id_helpdiagrams = object_id(N''dbo.sp_helpdiagrams''),\n @id_helpdiagramdefinition = object_id(N''dbo.sp_helpdiagramdefinition''),\n @id_creatediagram = object_id(N''dbo.sp_creatediagram''),\n @id_renamediagram = object_id(N''dbo.sp_renamediagram''),\n @id_alterdiagram = object_id(N''dbo.sp_alterdiagram''), \n @id_dropdiagram = object_id(N''dbo.sp_dropdiagram'')\n\n if @id_upgraddiagrams is not null\n select @InstalledObjects = @InstalledObjects + 1\n if @id_sysdiagrams is not null\n select @InstalledObjects = @InstalledObjects + 2\n if @id_helpdiagrams is not null\n select @InstalledObjects = @InstalledObjects + 4\n if @id_helpdiagramdefinition is not null\n select @InstalledObjects = @InstalledObjects + 8\n if @id_creatediagram is not null\n select @InstalledObjects = @InstalledObjects + 16\n if @id_renamediagram is not null\n select @InstalledObjects = @InstalledObjects + 32\n if @id_alterdiagram is not null\n select @InstalledObjects = @InstalledObjects + 64\n if @id_dropdiagram is not null\n select @InstalledObjects = @InstalledObjects + 128\n\n return @InstalledObjects \n END\n '\n\n\n GRANT EXECUTE ON dbo.fn_diagramobjects TO public\n DENY EXECUTE ON dbo.fn_diagramobjects TO guest\nEND\n\nif IS_MEMBER('db_owner') = 1\nBEGIN\n declare @val int\n select @val = 1\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sysdiagrams') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'TABLE', N'sysdiagrams', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_upgraddiagrams') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_upgraddiagrams', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_helpdiagrams') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_helpdiagrams', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_helpdiagramdefinition') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_helpdiagramdefinition', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_creatediagram') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_creatediagram', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_renamediagram') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_renamediagram', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_alterdiagram') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_alterdiagram', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.sp_dropdiagram') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'PROCEDURE', N'sp_dropdiagram', NULL, NULL\n end\n\n if NOT EXISTS( select major_id \n from sys.extended_properties\n where major_id = object_id(N'dbo.fn_diagramobjects') and class = 1 and minor_id = 0 and name = N'microsoft_database_tools_support')\n begin\n exec sp_addextendedproperty N'microsoft_database_tools_support', @val, 'SCHEMA', N'dbo', 'FUNCTION', N'fn_diagramobjects', NULL, NULL\n end\nEND\n\n/* Clean up */\n/*\nDROP FUNCTION dbo.fn_diagramobjects\nDROP PROCEDURE dbo.sp_dropdiagram\nDROP PROCEDURE dbo.sp_alterdiagram\nDROP PROCEDURE dbo.sp_renamediagram\nDROP PROCEDURE dbo.sp_creatediagram\nDROP PROCEDURE dbo.sp_helpdiagramdefinition\nDROP PROCEDURE dbo.sp_helpdiagrams\nDROP TABLE dbo.sysdiagrams\nDROP PROCEDURE dbo.sp_upgraddiagrams\n*/\n" }, { "answer_id": 43288132, "author": "Nagesh M", "author_id": 7834935, "author_profile": "https://Stackoverflow.com/users/7834935", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE dbo.sp_upgraddiagrams\nAS\nBEGIN\n IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL\n return 0;\n\n CREATE TABLE dbo.sysdiagrams\n (\n name sysname NOT NULL,\n principal_id int NOT NULL, -- we may change it to varbinary(85)\n diagram_id int PRIMARY KEY IDENTITY,\n version int,\n\n definition varbinary(max)\n CONSTRAINT UK_principal_name UNIQUE\n (\n principal_id,\n name\n )\n );\n\n\n -- Add this if we need to have some form of extended properties for diagrams */\n\n IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL\n BEGIN\n CREATE TABLE dbo.sysdiagram_properties\n (\n diagram_id int,\n name sysname,\n value varbinary(max) NOT NULL\n )\n END\n\n\n IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL\n begin\n insert into dbo.sysdiagrams\n (\n [name],\n [principal_id],\n [version],\n [definition]\n )\n select \n convert(sysname, dgnm.[uvalue]),\n DATABASE_PRINCIPAL_ID(N'dbo'), -- will change to the sid of sa\n 0, -- zero for old format, dgdef.[version],\n dgdef.[lvalue]\n from dbo.[dtproperties] dgnm\n inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid] \n inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid]\n\n where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' \n return 2;\n end\n return 1;\nEND\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28717/" ]
281,664
<p>Imagine the following scenario - we have Page1 which contains controls Control A and Control B.</p> <p>Say Control A has a button, and on the click of this button we want Control B to react. But we want to do this in an abstract fashion, i.e. we can't have Control B knowing anything about Control A, and vice versa.</p> <p>That way we can develop these controls in isolation, and drive them by unit-testing.</p> <p>Now, I thought I had the solution, just want to know what you guys think of it.</p> <p>On Control A's button click, I put a 'message' on the Session, i.e. Session["MESSAGES"] = "ControlA_Click".</p> <p>In Page1, on the Page_LoadComplete(), I put a call to ProcessMessages, which looks like this:</p> <pre><code> List&lt;Message&gt; messages = SessionMessages.GetMessageList(Page); foreach(Message m in messages) { //Get Controls ControlA controlA = FindControl("controlA") as ControlA; controlA .ProcessMessage(m); ControlB controlB = FindControl("controlB") as ControlB; controlB.ProcessMessage(m); } </code></pre> <p>in ControlB's ProcessMessage() method, we can react to the messages that ControlB is interested in, like so:</p> <pre><code> if (m.MessageName == SessionMessages.C_MESSAGE_SEARCH) { this.Visible = true; } </code></pre> <p>To me, this seems to work. It allows us to develop these controls completely separately from eachother, while still allowing for inter-control-communication at an abstract level.</p> <p>The only thing I can think of that might bring this crashing down is <em>perhaps</em> the ASP.NET life-cycle in relation to Pages and User Controls. The way I figure it though is that ALL events should have been processed on the controls before Page_LoadComplete() is called on the owning Page.</p> <p>Thoughts?</p>
[ { "answer_id": 281728, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 1, "selected": false, "text": "public interface IHandle<T> where T:IMessage\n{\n void Process(T message)\n}\n" }, { "answer_id": 281729, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 0, "selected": false, "text": "public event EventHandler SpecialClick;\n controlA.SpecialClick += new EventHandler(controlA_SpecialClick)\n" }, { "answer_id": 281766, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 2, "selected": false, "text": "\nprivate void ControlA_OnClick(..)\n{\n if(LoginRequested != null)\n LoginRequested(this, loginObj);\n}\n" }, { "answer_id": 282131, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": true, "text": "interface IEventBroker {\n void Send(Message m);\n}\n\nclass ControlA {\n void MyButton_Click(object sender, EventArgs e) {\n var eb = this.Page as IEventBroker;\n if (eb != null) eb.Send(new Message());\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7140/" ]
281,682
<p>I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity</p> <pre><code>XmlDocument xmldoc = new XmlDocument(); string text = "Hello, I am text &amp;alpha; &amp;nbsp; &amp;ndash; &amp;mdash;" xmldoc.InnerXml = "&lt;p&gt;" + text + "&lt;/p&gt;"; </code></pre> <p>This throws the exception: </p> <blockquote> <p>Reference to undeclared entity 'alpha'. Line 2, position 2.. </p> </blockquote> <p>How would I go about solving this problem?</p>
[ { "answer_id": 281686, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": " &#913;\n" }, { "answer_id": 281739, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 3, "selected": false, "text": " <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n" }, { "answer_id": 281751, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 0, "selected": false, "text": "\"Hello, I am text α – —\"" }, { "answer_id": 842836, "author": "LandedGently", "author_id": 103965, "author_profile": "https://Stackoverflow.com/users/103965", "pm_score": 4, "selected": false, "text": "System.Xml.XmlConvert string text = XmlConvert.EncodeName(\"Hello &alpha;\");\n <!DOCTYPE documentElement[\n<!ENTITY Alpha \"&#913;\">\n<!ENTITY ndash \"&#8211;\">\n<!ENTITY mdash \"&#8212;\">\n]>\n" }, { "answer_id": 2285004, "author": "Nick Josevski", "author_id": 75963, "author_profile": "https://Stackoverflow.com/users/75963", "pm_score": 0, "selected": false, "text": "//setup\npublic class CustomXmlResolver : XmlUrlResolver { /* ... */ }\nString originalXml; //fetched xml with html entities in it\n\nvar doc = new XmlDocument();\ndoc.XmlResolver = new AdCastXmlResolver();\n\n//making use of a transitional dtd\ndoc.LoadXml(\"<!DOCTYPE html SYSTEM \\\"xhtml1-transitional.dtd\\\" > \" + originalXml);\n" }, { "answer_id": 66313035, "author": "Felix Sasaki", "author_id": 15178054, "author_profile": "https://Stackoverflow.com/users/15178054", "pm_score": 1, "selected": false, "text": "<!DOCTYPE xsl:stylesheet\n[\n<!ENTITY % htmlentities SYSTEM \"html-entity-list.ent\">\n%htmlentities;\n]>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"...>\n <!ENTITY Auml \"Ä\">\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6201/" ]
281,694
<p>I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:</p> <pre><code>&lt;rp:do-something runat="server" id="doSomething1" /&gt;</code></pre> <p>I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer" title="tagMapping Element">tagMapping element</a> doesn't quite match up for what I'd like to do.</p>
[ { "answer_id": 281686, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": " &#913;\n" }, { "answer_id": 281739, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 3, "selected": false, "text": " <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n" }, { "answer_id": 281751, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 0, "selected": false, "text": "\"Hello, I am text α – —\"" }, { "answer_id": 842836, "author": "LandedGently", "author_id": 103965, "author_profile": "https://Stackoverflow.com/users/103965", "pm_score": 4, "selected": false, "text": "System.Xml.XmlConvert string text = XmlConvert.EncodeName(\"Hello &alpha;\");\n <!DOCTYPE documentElement[\n<!ENTITY Alpha \"&#913;\">\n<!ENTITY ndash \"&#8211;\">\n<!ENTITY mdash \"&#8212;\">\n]>\n" }, { "answer_id": 2285004, "author": "Nick Josevski", "author_id": 75963, "author_profile": "https://Stackoverflow.com/users/75963", "pm_score": 0, "selected": false, "text": "//setup\npublic class CustomXmlResolver : XmlUrlResolver { /* ... */ }\nString originalXml; //fetched xml with html entities in it\n\nvar doc = new XmlDocument();\ndoc.XmlResolver = new AdCastXmlResolver();\n\n//making use of a transitional dtd\ndoc.LoadXml(\"<!DOCTYPE html SYSTEM \\\"xhtml1-transitional.dtd\\\" > \" + originalXml);\n" }, { "answer_id": 66313035, "author": "Felix Sasaki", "author_id": 15178054, "author_profile": "https://Stackoverflow.com/users/15178054", "pm_score": 1, "selected": false, "text": "<!DOCTYPE xsl:stylesheet\n[\n<!ENTITY % htmlentities SYSTEM \"html-entity-list.ent\">\n%htmlentities;\n]>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"...>\n <!ENTITY Auml \"Ä\">\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34224/" ]
281,697
<p>I used code like this to find the remote user name:</p> <pre><code>banner_label.Text = "Welcome, &lt;B&gt;" + User.Identity.Name + "&lt;/B&gt;!" </code></pre> <p>I'd also like to find the remote host name. My production environment will be a corporate intranet with active directory.</p>
[ { "answer_id": 281732, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "Request.UserHostName\n" }, { "answer_id": 281742, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 1, "selected": false, "text": "HttpContext.Current.Request.ServerVariables[\"REMOTE_HOST\"]" }, { "answer_id": 281746, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "System.Net.DNS.GetHostName\n" }, { "answer_id": 282073, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 2, "selected": false, "text": "// NAT'ed addresses are sometimes still shown in HTTP_X_FORWARDED_FOR\nstring userHost = Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"];\n\nif (String.IsNullOrEmpty(userHost) || String.Compare(userHost, \"unknown\", true) == 0)\n userHost = Request.UserHostAddress;\n\nif (String.Compare(userHost, Request.UserHostName) != 0)\n userHost += \" (\" + Request.UserHostName + \")\";\n System.Net.Dns.GetHostEntry(userHost).HostName\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,698
<p>I just don't get it. Tried on VC++ 2008 and G++ 4.3.2</p> <pre><code>#include &lt;map&gt; class A : public std::multimap&lt;int, bool&gt; { public: size_type erase(int k, bool v) { return erase(k); // &lt;- this fails; had to change to __super::erase(k) } }; int main() { A a; a.erase(0, false); a.erase(0); // &lt;- fails. can't find base class' function?! return 0; } </code></pre>
[ { "answer_id": 281707, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "erase(int, bool) erase(0)" }, { "answer_id": 281738, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 4, "selected": false, "text": "class A : public std::multimap<int, bool>\n{\npublic:\n using std::multimap<int, bool>::erase; // Any erase function found in the base class should be injected into the derived class namespace as well\n size_type erase(int k, bool v)\n {\n return erase(k);\n }\n};\n" }, { "answer_id": 281904, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "typedef std::multimap<int, bool> parent;\npublic:\n size_type erase(int k, bool v)\n {\n return parent::erase(k);\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21704/" ]
281,706
<p>I'm having an issue dragging a file from Windows Explorer on to a Windows Forms application. </p> <p>It works fine when I drag text, but for some reason it is not recognizing the file. Here is my test code:</p> <pre><code>namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_DragDrop(object sender, DragEventArgs e) { } private void Form1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.Text)) { e.Effect = DragDropEffects.Copy; } else if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } } } </code></pre> <p>AllowDrop is set to true on Form1, and as I mentioned, it works if I drag text on to the form, just not an actual file.</p> <p>I'm using Vista 64-bit ... not sure if that is part of the problem.</p>
[ { "answer_id": 281770, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 0, "selected": false, "text": "string formats = string.Join( \"\\n\", e.Data.GetFormats(false) );\nMessageBox.Show( formats );\n" }, { "answer_id": 12625720, "author": "k3b", "author_id": 519334, "author_profile": "https://Stackoverflow.com/users/519334", "pm_score": 0, "selected": false, "text": "STAThread [STAThread]\n static void Main(string[] args)\n {\n }\n STAThread" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
281,714
<p>Do you have any ideas how to call DoEvents from a C# DLL</p>
[ { "answer_id": 281730, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 2, "selected": false, "text": "System.Windows.Forms.Application.DoEvents()" }, { "answer_id": 283208, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Control.Invoke/BeginInvoke SynchronizationContext.Current Control.Invoke" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28207/" ]
281,719
<p>I am quantitatively studying various metrics associated with automated tests. Chrome seems to have a reasonable set, so I wanted to add it to my data set. I downloaded the Chrome source code and tried to build it with VisualStudio but got several hundred errors--types not defined, identifiers not defined, etc. Has anyone out there succeeded in building Chrome under Windows? Are there tricks I need to know?</p>
[ { "answer_id": 281736, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "3>Error in tempfile() using /tmp/dftables-XXXXXXXX.in: Parent directory (/tmp/) is not writable\n3> at /cygdrive/c/b/slave/WEBKIT~1/build/webkit/third_party/JavaScriptCore/pcre/dftables line 236\n3>make: *** [chartables.c] Error 255\n set CYGWIN=nontsec\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13842/" ]
281,724
<p>From my experiments, it does not appear to do so. If this is indeed true, what is the best method for removing line breaks? I'm currently experimenting with the parameters that TRIM accepts of the character to remove, starting with trimming <code>\n</code> and <code>\r</code>.</p>
[ { "answer_id": 281740, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 2, "selected": false, "text": "select trim(both '\\n' from FIELDNAME) from TABLE;\n" }, { "answer_id": 281778, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 4, "selected": true, "text": "Trim() Trim()" }, { "answer_id": 439186, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "select trim(both '\\r\\n' from FIELDNAME) from TABLE; select trim(both '\\n' from FIELDNAME) from TABLE;" }, { "answer_id": 477620, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "char trim(both char(13) from fieldname)\n" }, { "answer_id": 617104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "REPLACE(FIELD,'\\r\\n',' ')\n" }, { "answer_id": 2155778, "author": "boardtc", "author_id": 261123, "author_profile": "https://Stackoverflow.com/users/261123", "pm_score": -1, "selected": false, "text": "REPLACE(FIELD,'\\r\\n',' ')" }, { "answer_id": 3709569, "author": "Ilya", "author_id": 7566, "author_profile": "https://Stackoverflow.com/users/7566", "pm_score": 0, "selected": false, "text": "UPDATE table SET field=REPLACE(field, field, TRIM(BOTH '\\r\\n' FROM field))\n" }, { "answer_id": 3910711, "author": "Punit Raizada", "author_id": 213213, "author_profile": "https://Stackoverflow.com/users/213213", "pm_score": 0, "selected": false, "text": "update events set eventuniqueid = substring(eventuniqueid, 1, 6) where length(eventuniqueid) = 7;\n" }, { "answer_id": 4690968, "author": "rjmunro", "author_id": 3408, "author_profile": "https://Stackoverflow.com/users/3408", "pm_score": 3, "selected": false, "text": "trim CREATE FUNCTION `multiTrim`(string varchar(1023),remove varchar(63)) RETURNS varchar(1023) CHARSET utf8\nBEGIN\n -- Remove trailing chars\n WHILE length(string)>0 and remove LIKE concat('%',substring(string,-1),'%') DO\n set string = substring(string,1,length(string)-1);\n END WHILE;\n\n -- Remove leading chars\n WHILE length(string)>0 and remove LIKE concat('%',left(string,1),'%') DO\n set string = substring(string,2);\n END WHILE;\n\n RETURN string;\nEND;\n select multiTrim(string,\"\\r\\n\\t \");\n" }, { "answer_id": 5863354, "author": "Lucas", "author_id": 735229, "author_profile": "https://Stackoverflow.com/users/735229", "pm_score": 5, "selected": false, "text": "Trim() select trim(BOTH '\\n' from [field_name]) as field\n '\\r' '\\n\\r' update [table_name] set [field_name] = trim(BOTH '\\n' from [field_name])\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
281,725
<p>I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.</p> <p>-edit-</p> <p>I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.</p> <pre><code>class SomeTag {}; class InheritSomeTag : public SomeTag {}; template &lt;class T, class Tag=T&gt; struct MyClass { }; template &lt;class T&gt; struct MyClass&lt;T, SomeTag&gt; { typedef int isSpecialized; }; int main() { MyClass&lt;SomeTag&gt;::isSpecialized test1; //ok MyClass&lt;InheritSomeTag&gt;::isSpecialized test2; //how do i make this specialized w/o changing main() return 0; } </code></pre>
[ { "answer_id": 281795, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "MyClass InheritSomeTag main // Base class\ntemplate <typename TSpec = void>\nclass SomeTag { };\n\n// Type tag, NOT part of the inheritance chain\ntemplate <typename TSpec = void>\nstruct InheritSomeTag { };\n\n// Derived class, uses type tag\ntemplate <typename TSpec>\nclass SomeTag<InheritSomeTag<TSpec> > : public SomeTag<void> { };\n\ntemplate <class T, class Tag=T>\nstruct MyClass { };\n\ntemplate <class T, typename TSpec>\nstruct MyClass<T, SomeTag<TSpec> >\n{\n typedef int isSpecialized;\n};\n\nint main()\n{\n MyClass<SomeTag<> >::isSpecialized test1; //ok\n MyClass<SomeTag<InheritSomeTag<> > >::isSpecialized test2; //ok\n}\n" }, { "answer_id": 281830, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 6, "selected": true, "text": "template<typename D, typename B>\nclass IsDerivedFrom\n{\n class No { };\n class Yes { No no[3]; }; \n\n static Yes Test( B* ); // not defined\n static No Test( ... ); // not defined \n\n static void Constraints(D* p) { B* pb = p; pb = p; } \n\npublic:\n enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) }; \n\n IsDerivedFrom() { void(*p)(D*) = Constraints; }\n};\n template<typename T, int>\nclass MyClassImpl\n{\n // general case: T is not derived from SomeTag\n}; \n\ntemplate<typename T>\nclass MyClassImpl<T, 1>\n{\n // T is derived from SomeTag\n public:\n typedef int isSpecialized;\n}; \n template<typename T>\nclass MyClass: public MyClassImpl<T, IsDerivedFrom<T, SomeTag>::Is>\n{\n};\n int main()\n{\n MyClass<SomeTag>::isSpecialized test1; //ok\n MyClass<InheritSomeTag>::isSpecialized test2; //ok also\n return 0;\n}\n" }, { "answer_id": 282006, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "enable_if template<bool C, typename T = void>\nstruct enable_if {\n typedef T type;\n};\n\ntemplate<typename T>\nstruct enable_if<false, T> { };\n\ntemplate<typename, typename>\nstruct is_same {\n static bool const value = false;\n};\n\ntemplate<typename A>\nstruct is_same<A, A> {\n static bool const value = true;\n};\n\ntemplate<typename B, typename D> \nstruct is_base_of { \n static D * create_d(); \n static char (& chk(B *))[1]; \n static char (& chk(...))[2]; \n static bool const value = sizeof chk(create_d()) == 1 && \n !is_same<B volatile const, \n void volatile const>::value;\n};\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T, typename = void>\nstruct MyClass { /* T not derived from SomeTag */ };\n\ntemplate<typename T>\nstruct MyClass<T, typename enable_if<is_base_of<SomeTag, T>::value>::type> {\n typedef int isSpecialized;\n};\n\nint main() {\n MyClass<SomeTag>::isSpecialized test1; /* ok */\n MyClass<InheritSomeTag>::isSpecialized test2; /* ok */\n}\n" }, { "answer_id": 25934222, "author": "Carlo Wood", "author_id": 1487069, "author_profile": "https://Stackoverflow.com/users/1487069", "pm_score": 5, "selected": false, "text": "#include <type_traits>\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T, bool = std::is_base_of<SomeTag, T>::value>\nstruct MyClass { };\n\ntemplate<typename T>\nstruct MyClass<T, true> {\n typedef int isSpecialized;\n};\n\nint main() {\n MyClass<SomeTag>::isSpecialized test1; /* ok */\n MyClass<InheritSomeTag>::isSpecialized test2; /* ok */\n}\n" }, { "answer_id": 73214685, "author": "bonkt", "author_id": 16036714, "author_profile": "https://Stackoverflow.com/users/16036714", "pm_score": 1, "selected": false, "text": "// C++20:\n#include <concepts>\n#include <iostream>\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T>\nstruct MyClass \n{ \n void Print()\n {\n std::cout << \"Not derived from someTag\\n\";\n }\n};\n\n// std::derived_from is a predefined concept already included in the STL\ntemplate<typename T>\n requires std::derived_from<T, SomeTag> \nstruct MyClass<T> \n{\n void Print()\n {\n std::cout << \"derived from someTag\\n\";\n }\n};\n\nint main() \n{\n MyClass<InheritSomeTag> test1;\n test1.Print(); // derived from someTag\n MyClass<int> test2; \n test2.Print(); // Not derived from someTag\n\n // Note how even the base tag itself returns true from std::derived_from:\n MyClass<SomeTag> test3; \n test3.Print(); // derived from someTag \n\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,743
<p>I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).</p> <p>I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.</p>
[ { "answer_id": 281753, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": true, "text": "\"^P\\.?\\s?O\\.?\\sB[Oo][Xx].\"\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13583/" ]
281,744
<p>Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory. But how should the specific prepared statements be defined after that? Right now I'm only using a PoolingDataSource to get connections from the pool. How do I use the prepared statements from the pool?</p>
[ { "answer_id": 282135, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 4, "selected": true, "text": "* public PreparedStatement prepareStatement(String sql)\n* public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)\n" }, { "answer_id": 6016142, "author": "sproketboy", "author_id": 53069, "author_profile": "https://Stackoverflow.com/users/53069", "pm_score": 0, "selected": false, "text": " GenericObjectPool connectionPool = new GenericObjectPool(null);\n connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 30);\n connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30);\n connectionPool.setNumTestsPerEvictionRun(3);\n connectionPool.setTestOnBorrow(true);\n connectionPool.setTestWhileIdle(false);\n connectionPool.setTestOnReturn(false);\n\n props = new Properties();\n props.put(\"user\", username);\n props.put(\"password\", password);\n ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);\n\n PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, \"SELECT 1\", false, true);\n PoolingDataSource dataSource = new PoolingDataSource(connectionPool);\n" }, { "answer_id": 7038489, "author": "Stanislav Bashkyrtsev", "author_id": 886697, "author_profile": "https://Stackoverflow.com/users/886697", "pm_score": 0, "selected": false, "text": "Connection PreparedStatement DataSource PreparedStatement PooledConnection Connection" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12649/" ]
281,758
<p>I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree.</p> <p>For example, if I have a controller <code>HomeController</code>, which needs to have a <code>LoginService</code> injected into it, then in my unit test <code>HomeControllerTest</code> I simply instantiate the object as normal (outside of Spring) and inject the property:</p> <pre><code>protected void setUp() throws Exception { super.setUp(); //... controller = new HomeController(); controller.setLoginService( new SimpleLoginService() ); //... } </code></pre> <p>This works great for testing each component as an isolated unit - except now that I have a few dozen classes in the project, after writing a class and writing a successful unit test for it, I keep forgetting to update my Spring MVC context file that does the actual wiring-up in the deployed application. I find out that I forgot to update the context file when I deploy the project to Tomcat and find a bunch of NullPointers from non-wired-up beans.</p> <p>So, here are my questions:</p> <ol> <li><p>This is my first Spring project - is it normal to create unit tests for the individual beans, as I have done, and then create a second suite of tests (integration tests) to test that everything works as expected with the actual application context? Is there an established best practice for this?</p></li> <li><p>In addition, how do you separate the unit tests from the integration tests? I have all of the source code in <code>src</code>, the unit tests in <code>test</code> - should there be a 2nd test folder (such as <code>test-integration</code>) for integration test cases?</p></li> </ol> <p>Since this is my first Spring project, I'm curious how others usually go about doing this sort of thing - and rather than re-invent the wheel I rather ask the rest of the community.</p>
[ { "answer_id": 281841, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 6, "selected": true, "text": "test Test TestCase AbstractIntegrationTestCase Spring WebApplicationContext test IntTest IntegrationTest test test test" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
281,787
<p>What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?</p> <p>Contrived example: </p> <pre><code>class Container { public: Container::Container() {/*initialize members*/}; int stuff; int otherStuff; }; Container myCollection; </code></pre> <p>I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value". But then if another member is added to Container, </p> <pre><code>class Container { public: Container::Container() {/*initialize members*/}; int stuff; string evenMoreStuff; int otherStuff; }; Container myCollection;</code></pre> <p>This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"</p> <p>Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.) Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.</p>
[ { "answer_id": 281832, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": 0, "selected": false, "text": "char *buffer = new char[sizeof(Container)];\nmemcpy(buffer, containerInstance, sizeof(Container));\n printOn(ostream &)" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22724/" ]
281,791
<p>I want to set the background of an <code>NSBox</code> to be a gradient. In Interface Builder it is possible to set the background color of an <code>NSBox</code> to <code>selectedMenuColor</code> which is a gradient. </p> <p><code>NSBox</code> only has a <code>setFillColor</code> method so how is Interface Builder filling it with a gradient? </p> <p>How do I programmatically fill an <code>NSBox</code> without subclassing it? It would be trivial to subclass <code>NSBox</code> but the workings of Interface Builder suggest there may be better solution.</p>
[ { "answer_id": 281984, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 0, "selected": false, "text": "colorWithPatternImage:" }, { "answer_id": 284076, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 2, "selected": false, "text": "selectedMenuColor colorWithPatternImage:" }, { "answer_id": 17725826, "author": "Surjeet Singh", "author_id": 2331777, "author_profile": "https://Stackoverflow.com/users/2331777", "pm_score": 0, "selected": false, "text": "xib NSBox NSBox IBOutlet NSBox *box;\n\n[box.setWantsLayer:YES];\n\n[box.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];\n [box.setWantsLayer:YES];\n\n[box.layer setBackgroundColor:[[NSColor colorWithPatternImage:[NSImage imageNamed:@\"white.gif\"]] CGColor]];\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,811
<p>How do I test if two dates are within a certain tolerance in NUnit?</p>
[ { "answer_id": 281853, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 1, "selected": false, "text": "long ticks = mydate.Ticks;\nlong tolerance = 1000;\nAssert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );\n" }, { "answer_id": 281857, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10)\n{\n CloseEnough();\n}\n" }, { "answer_id": 282053, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 3, "selected": true, "text": "Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));\n" }, { "answer_id": 6680959, "author": "Howard", "author_id": 842938, "author_profile": "https://Stackoverflow.com/users/842938", "pm_score": 2, "selected": false, "text": "TimeSpan tolerance = new TimeSpan(0,1,0); // e.g. 1 minute\n\nAssert.IsTrue((firstDateTime-SecondDateTime).Duration() > tolerance);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
281,818
<p>I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a <code>type_info</code> class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. <code>typeid(std::vector&lt;int&gt;).name()</code> returns <code>St6vectorIiSaIiEE</code>.</p> <p>Is there a way to produce something useful from this? Like <code>std::vector&lt;int&gt;</code> for the above example. If it only works for non-template classes, that's fine too.</p> <p>The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.</p>
[ { "answer_id": 281860, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 1, "selected": false, "text": "__cxa_demangle cxxabi.h" }, { "answer_id": 281876, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 4, "selected": false, "text": "#ifdef HAVE_CXA_DEMANGLE\nconst char* demangle(const char* name)\n{\n char buf[1024];\n unsigned int size=1024;\n int status;\n char* res = abi::__cxa_demangle (name,\n buf,\n &size,\n &status);\n return res;\n }\n#else\nconst char* demangle(const char* name)\n{\n return name;\n}\n#endif \n" }, { "answer_id": 281880, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 2, "selected": false, "text": "__FUNCTION__\n__FILE__\n__LINE__\n\ne.g.:\n\nlog(__FILE__, __LINE__, __FUNCTION__, mymessage);\n" }, { "answer_id": 281905, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "c++filt" }, { "answer_id": 282009, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 2, "selected": false, "text": "__PRETTY_FUNCTION__ virtual bool mutex::do_unlock()\n" }, { "answer_id": 2624567, "author": "Dan Dare", "author_id": 314786, "author_profile": "https://Stackoverflow.com/users/314786", "pm_score": 1, "selected": false, "text": "// KeithB's solution is good, but has one serious flaw in that unless buf is static\n// it'll get trashed from the stack before it is returned in res - and will point who-knows-where\n// Here's that problem fixed, but the code is still non-re-entrant and not thread-safe.\n// Anyone care to improve it?\n\n#include <cxxabi.h>\n\n// todo: javadoc this properly\nconst char* demangle(const char* name)\n{\n static char buf[1024];\n size_t size = sizeof(buf);\n int status;\n // todo:\n char* res = abi::__cxa_demangle (name,\n buf,\n &size,\n &status);\n buf[sizeof(buf) - 1] = 0; // I'd hope __cxa_demangle does this when the name is huge, but just in case.\n return res;\n }\n" }, { "answer_id": 4541470, "author": "Ali", "author_id": 341970, "author_profile": "https://Stackoverflow.com/users/341970", "pm_score": 8, "selected": true, "text": "#ifndef TYPE_HPP\n#define TYPE_HPP\n\n#include <string>\n#include <typeinfo>\n\nstd::string demangle(const char* name);\n\ntemplate <class T>\nstd::string type(const T& t) {\n\n return demangle(typeid(t).name());\n}\n\n#endif\n #include \"type.hpp\"\n#ifdef __GNUG__\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\nstd::string demangle(const char* name) {\n\n int status = -4; // some arbitrary value to eliminate the compiler warning\n\n // enable c++11 by passing the flag -std=c++11 to g++\n std::unique_ptr<char, void(*)(void*)> res {\n abi::__cxa_demangle(name, NULL, NULL, &status),\n std::free\n };\n\n return (status==0) ? res.get() : name ;\n}\n\n#else\n\n// does nothing if not g++\nstd::string demangle(const char* name) {\n return name;\n}\n\n#endif\n #include <iostream>\n#include \"type.hpp\"\n\nstruct Base { virtual ~Base() {} };\n\nstruct Derived : public Base { };\n\nint main() {\n\n Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code!\n\n std::cout << \"Type of ptr_base: \" << type(ptr_base) << std::endl;\n\n std::cout << \"Type of pointee: \" << type(*ptr_base) << std::endl;\n\n delete ptr_base;\n}\n Base* Derived #include \"type.hpp\"\n#ifdef __GNUG__\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\nstruct handle {\n char* p;\n handle(char* ptr) : p(ptr) { }\n ~handle() { std::free(p); }\n};\n\nstd::string demangle(const char* name) {\n\n int status = -4; // some arbitrary value to eliminate the compiler warning\n\n handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );\n\n return (status==0) ? result.p : name ;\n}\n\n#else\n\n// does nothing if not g++\nstd::string demangle(const char* name) {\n return name;\n}\n\n#endif\n abi::__cxa_demangle() abi::__cxa_demangle() output_buffer realloc realloc() realloc() realloc() HAVE_CXA_DEMANGLE __GNUG__ #include <cxxabi.h>\n\nconst string demangle(const char* name) {\n\n int status = -4;\n\n char* res = abi::__cxa_demangle(name, NULL, NULL, &status);\n\n const char* const demangled_name = (status==0)?res:name;\n\n string ret_val(demangled_name);\n\n free(res);\n\n return ret_val;\n}\n" }, { "answer_id": 29606760, "author": "matzzz", "author_id": 4783138, "author_profile": "https://Stackoverflow.com/users/4783138", "pm_score": 2, "selected": false, "text": "typeid(bla).name() Typeid(bla).name() #ifndef TYPE_HPP\n#define TYPE_HPP\n\n#include <string>\n#include <typeinfo>\n\nstd::string demangle(const char* name);\n\n/*\ntemplate <class T>\nstd::string type(const T& t) {\n\n return demangle(typeid(t).name());\n}\n*/\n\nclass Typeid {\n public:\n\n template <class T>\n Typeid(const T& t) : typ(typeid(t)) {}\n\n std::string name() { return demangle(typ.name()); }\n\n private:\n const std::type_info& typ;\n};\n\n\n#endif\n" }, { "answer_id": 34916852, "author": "moof2k", "author_id": 4343378, "author_profile": "https://Stackoverflow.com/users/4343378", "pm_score": 5, "selected": false, "text": "#include <boost/core/demangle.hpp>\n#include <typeinfo>\n#include <iostream>\n\ntemplate<class T> struct X\n{\n};\n\nint main()\n{\n char const * name = typeid( X<int> ).name();\n\n std::cout << name << std::endl; // prints 1XIiE\n std::cout << boost::core::demangle( name ) << std::endl; // prints X<int>\n}\n abi::__cxa_demangle" }, { "answer_id": 53865723, "author": "sancho.s ReinstateMonicaCellio", "author_id": 2707864, "author_profile": "https://Stackoverflow.com/users/2707864", "pm_score": 2, "selected": false, "text": "type int i = 1;\ncout << \"Type of \" << \"i\" << \" is \" << type(i) << endl;\nint & ri = i;\ncout << \"Type of \" << \"ri\" << \" is \" << type(ri) << endl;\n Type of i is int\nType of ri is int\n type_name<decltype(obj)>() cout << \"Type of \" << \"i\" << \" is \" << type_name<decltype(i)>() << endl;\ncout << \"Type of \" << \"ri\" << \" is \" << type_name<decltype(ri)>() << endl;\n Type of i is int\nType of ri is int&\n #ifndef _MSC_VER\n# include <cxxabi.h>\n#endif\n#include <memory>\n#include <string>\n#include <cstdlib>\n\ntemplate <class T>\nstd::string\ntype_name()\n{\n typedef typename std::remove_reference<T>::type TR;\n std::unique_ptr<char, void(*)(void*)> own\n (\n#ifndef _MSC_VER\n abi::__cxa_demangle(typeid(TR).name(), nullptr,\n nullptr, nullptr),\n#else\n nullptr,\n#endif\n std::free\n );\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n if (std::is_const<TR>::value)\n r += \" const\";\n if (std::is_volatile<TR>::value)\n r += \" volatile\";\n if (std::is_lvalue_reference<T>::value)\n r += \"&\";\n else if (std::is_rvalue_reference<T>::value)\n r += \"&&\";\n return r;\n}\n" }, { "answer_id": 62465912, "author": "Alexis Paques", "author_id": 3540247, "author_profile": "https://Stackoverflow.com/users/3540247", "pm_score": 1, "selected": false, "text": "// type.h\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\ntemplate <typename T>\nstd::string demangle() {\n int status = -4;\n\n std::unique_ptr<char, void (*)(void*)> res{\n abi::__cxa_demangle(typeid(T).name(), NULL, NULL, &status), std::free};\n return (status == 0) ? res.get() : typeid(T).name();\n}\n // main.cpp\n#include <iostream>\n\nnamespace test {\n struct SomeStruct {};\n}\n\nint main()\n{\n std::cout << demangle<double>() << std::endl;\n std::cout << demangle<const int&>() << std::endl;\n std::cout << demangle<test::SomeStruct>() << std::endl;\n\n return 0;\n}\n double \nint \ntest::SomeStruct\n" }, { "answer_id": 66551751, "author": "Human-Compiler", "author_id": 1678770, "author_profile": "https://Stackoverflow.com/users/1678770", "pm_score": 4, "selected": false, "text": "std::type_info template gcc clang __PRETTY_FUNCTION__ __FUNCSIG__ void foo<int> gcc void foo() [with T = int; ] clang void foo() [T = int] msvc void foo<int>() std::string_view constexpr #include <string_view>\n\ntemplate <typename T>\nconstexpr auto get_type_name() -> std::string_view\n{\n#if defined(__clang__)\n constexpr auto prefix = std::string_view{\"[T = \"};\n constexpr auto suffix = \"]\";\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(__GNUC__)\n constexpr auto prefix = std::string_view{\"with T = \"};\n constexpr auto suffix = \"; \";\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n constexpr auto prefix = std::string_view{\"get_type_name<\"};\n constexpr auto suffix = \">(void)\";\n constexpr auto function = std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n\n const auto start = function.find(prefix) + prefix.size();\n const auto end = function.find(suffix);\n const auto size = end - start;\n\n return function.substr(start, size);\n}\n get_type_name<T>() std::string_view std::cout << get_type_name<std::string>() << std::endl;\n std::__cxx11::basic_string<char>\n std::basic_string<char>\n prefix suffix double template <typename T>\nconstexpr auto full_function_name() -> std::string_view\n{\n#if defined(__clang__) || defined(__GNUC__)\n return std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n return std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n}\n\n// Outside of the template so its computed once\nstruct type_name_info {\n static constexpr auto sentinel_function = full_function_name<double>();\n static constexpr auto prefix_offset = sentinel_function.find(\"double\");\n static constexpr auto suffix_offset = sentinel_function.size() - prefix_offset - /* strlen(\"double\") */ 6;\n};\n\ntemplate <typename T>\nconstexpr auto get_type_name() -> std::string_view\n{\n constexpr auto function = full_function_name<T>();\n\n const auto start = type_name_info::prefix_offset;\n const auto end = function.size() - type_name_info::suffix_offset;\n const auto size = end - start;\n\n return function.substr(start, size);\n}\n __FUNCSIG__ __PRETTY_FUNCTION__ __func__" }, { "answer_id": 71820656, "author": "GKxx", "author_id": 8395081, "author_profile": "https://Stackoverflow.com/users/8395081", "pm_score": 0, "selected": false, "text": "boost::typeindex #include <boost/type_index.hpp>\n#include <iostream>\n#include <vector>\n\nclass Widget {};\n\nint main() {\n using boost::typeindex::type_id_with_cvr;\n const std::vector<Widget> vw;\n std::cout << type_id_with_cvr<decltype(vw)>().pretty_name() << std::endl;\n std::cout << type_id_with_cvr<decltype(vw[0])>().pretty_name() << std::endl;\n return 0;\n}\n std::vector<Widget, std::allocator<Widget> > const\nWidget const&\n type_id_with_cvr typeid #include <iostream>\n#include <boost/type_index.hpp>\n#include <typeindex>\n#include <vector>\n#include <typeinfo>\n\nclass Widget {};\n\ntemplate <typename T>\nvoid f(const T &param) {\n std::cout << typeid(param).name() << std::endl;\n std::cout\n << boost::typeindex::type_id_with_cvr<decltype(param)>().pretty_name()\n << std::endl;\n}\n\nint main() {\n const std::vector<Widget> vw(1);\n f(&vw[0]);\n return 0;\n}\n PK6Widget\nWidget const* const&\n typeid PK6Widget param type_id_with_cvr boost::core cvr_saver cvr_saver<type> typeid" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9232/" ]
281,831
<p>I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble.</p> <p>I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus.</p> <p>In MFC, we show the new context menu by calling <strong>TrackPopupMenuEx</strong> with the <strong>TPM_RECURSE</strong> flag.</p> <p><strong>ContextMenu</strong> and the newer <strong>ContextMenuStrip</strong> classes in .NET only have a <em>Show</em> method. Does anyone know how to do this in .NET?</p> <p><strong>EDIT</strong></p> <p>I have tried using <strong>TrackPopupMenuEx</strong> through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new <strong>MenuStrip</strong> and <strong>ContextMenuStrip</strong>.</p> <p>I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for <strong>MenuStrip</strong>, but <strong>ContextMenuStrip</strong> still allows the right click events to pass through as clicks.</p>
[ { "answer_id": 281883, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 2, "selected": false, "text": "[DllImport(\"user32.dll\")]\nstatic extern bool TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y,\nIntPtr hwnd, IntPtr lptpm);\n\nconst int TPM_RECURSE = 0x0001; \n" }, { "answer_id": 282202, "author": "Eren Aygunes", "author_id": 27980, "author_profile": "https://Stackoverflow.com/users/27980", "pm_score": 5, "selected": true, "text": "protected override void OnClick(EventArgs e)\n{\n if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)\n {\n base.OnClick(e);\n }\n}\n MouseButtons != MouseButtons.Right\n public partial class Form1 : Form\n{\n class CustomToolStripMenuItem : ToolStripMenuItem\n {\n private ContextMenuStrip secondaryContextMenu;\n\n public ContextMenuStrip SecondaryContextMenu\n {\n get\n {\n return secondaryContextMenu;\n }\n set\n {\n secondaryContextMenu = value;\n }\n }\n\n public CustomToolStripMenuItem(string text)\n : base(text)\n { }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n if (secondaryContextMenu != null)\n {\n secondaryContextMenu.Dispose();\n secondaryContextMenu = null;\n }\n }\n\n base.Dispose(disposing);\n }\n\n protected override void OnClick(EventArgs e)\n {\n if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)\n {\n base.OnClick(e);\n }\n }\n }\n\n class CustomContextMenuStrip : ContextMenuStrip\n {\n private bool secondaryContextMenuActive = false;\n private ContextMenuStrip lastShownSecondaryContextMenu = null;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n if (lastShownSecondaryContextMenu != null)\n {\n lastShownSecondaryContextMenu.Close();\n lastShownSecondaryContextMenu = null;\n }\n }\n base.Dispose(disposing);\n }\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n e.Control.MouseClick += new MouseEventHandler(Control_MouseClick);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick);\n base.OnControlRemoved(e);\n }\n\n private void Control_MouseClick(object sender, MouseEventArgs e)\n {\n ShowSecondaryContextMenu(e);\n }\n\n protected override void OnMouseClick(MouseEventArgs e)\n {\n ShowSecondaryContextMenu(e);\n base.OnMouseClick(e);\n }\n\n private bool ShowSecondaryContextMenu(MouseEventArgs e)\n {\n CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem;\n\n if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right)\n {\n return false;\n }\n\n lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu;\n secondaryContextMenuActive = true;\n ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);\n ctsm.SecondaryContextMenu.Show(Cursor.Position);\n return true;\n }\n\n void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)\n {\n ((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);\n lastShownSecondaryContextMenu = null;\n secondaryContextMenuActive = false;\n Focus();\n }\n\n protected override void OnClosing(ToolStripDropDownClosingEventArgs e)\n {\n if (secondaryContextMenuActive)\n {\n e.Cancel = true;\n }\n\n base.OnClosing(e);\n }\n }\n\n public Form1()\n {\n InitializeComponent();\n\n\n CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem(\"item primary 1\");\n itemPrimary1.SecondaryContextMenu = new ContextMenuStrip();\n itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { \n new ToolStripMenuItem(\"item primary 1.1\"),\n new ToolStripMenuItem(\"item primary 1.2\"),\n });\n\n CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem(\"item primary 2\");\n itemPrimary2.DropDownItems.Add(\"item primary 2, sub 1\");\n itemPrimary2.DropDownItems.Add(\"item primary 2, sub 2\");\n itemPrimary2.SecondaryContextMenu = new ContextMenuStrip();\n itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { \n new ToolStripMenuItem(\"item primary 2.1\"),\n new ToolStripMenuItem(\"item primary 2.2\"),\n });\n\n CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip();\n primaryContextMenu.Items.AddRange(new ToolStripItem[]{\n itemPrimary1,\n itemPrimary2\n });\n\n this.ContextMenuStrip = primaryContextMenu;\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30827/" ]
281,837
<p>I would like to parse HTML document and replace action attribute of all the forms and add some hidden fields with XSL. Can someone show some examples of XSL that can do this?</p>
[ { "answer_id": 281848, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 0, "selected": false, "text": "XSLT XML HTML" }, { "answer_id": 281932, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 2, "selected": false, "text": "<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"*\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\"/>\n <xsl:apply-templates/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"form[@action='foo']\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\"/>\n <xsl:attribute name=\"action\">non-foo</xsl:attribute>\n <input type=\"hidden\" name=\"my-hidden-prop\" value=\"hide-foo-here\"/>\n <xsl:apply-templates select=\"*\"/>\n </xsl:copy>\n </xsl:template>\n\n</xsl:stylesheet>\n <?xml version =\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"example-xslt.xsl\"?>\n<html>\n <head></head>\n <body>\n <form action=\"foo\">\n </form>\n <form action=\"other\">\n </form>\n </body>\n</html>\n" }, { "answer_id": 281943, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 0, "selected": false, "text": "xsl:output[@method=\"html\"] @doctype-system @doctype-public form" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,843
<p>I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.</p> <pre><code>public sealed class MySecurityAttribute : CodeAccessSecurityAttribute { public override IPermission CreatePermission() { MySecurityPermission permission = new MySecurityPermission(); //set its properties permission.Name = this.Name; permission.Unrestricted = this.Unrestricted; return permission; } } public class MySecurityPermission : IPermission, IUnrestrictedPermission { public MySecurityPermission(PermissionState state) { // what method was the attribute decorating that // created this MySecurityPermission? } public void Demand() { // Or here? } } </code></pre>
[ { "answer_id": 343463, "author": "Miral", "author_id": 43534, "author_profile": "https://Stackoverflow.com/users/43534", "pm_score": 0, "selected": false, "text": "this" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36668/" ]
281,855
<p>For what I can read, it is used to dispatch a new thread in a swing app to perform some "background" work, but what's the benefit from using this rather than a "normal" thread?</p> <p>Is not the same using a new Thread and when it finish invoke some GUI method using SwingUtilities.invokeLater?... </p> <p>What am I missing here?</p> <p><a href="http://en.wikipedia.org/wiki/SwingWorker" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/SwingWorker</a></p> <p><a href="http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html" rel="nofollow noreferrer">http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html</a></p>
[ { "answer_id": 281871, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "update(int status)" }, { "answer_id": 283223, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 2, "selected": false, "text": "import org.jdesktop.swingx.util.SwingWorker; // This one is from swingx\n // another one is built in \n // since JDK 1.6 AFAIK?\n\npublic class SwingWorkerTest {\n\n public static void main( String[] args ) {\n\n /**\n * First method\n */\n new Thread() {\n\n public void run() {\n\n /** Do work that would freeze GUI here */\n\n final Object result = new Object();\n java.awt.EventQueue.invokeLater( new Runnable() {\n\n public void run() {\n /** Update GUI here */\n }\n } );\n\n }\n }.start();\n\n /**\n * Second method\n */\n new SwingWorker< Object , Object >() {\n\n protected Object doInBackground() throws Exception {\n /** Do work that would freeze GUI here */\n\n return null;\n }\n\n protected void done() {\n try {\n Object result = get();\n /** Update GUI here */\n }\n catch ( Exception ex ) {\n ex.printStackTrace();\n if ( ex instanceof java.lang.InterruptedException )\n return;\n }\n }\n }.execute();\n }\n\n}\n" }, { "answer_id": 284127, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "SwingWorker" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
281,864
<p>I have a function that checks if a cookie (by name) exists or not:</p> <pre><code>Private Function cookieExists(ByVal cName As String) As Boolean For Each c As HttpCookie In Response.Cookies If c.Name = cName Then Return True Next Return False End Function </code></pre> <p>I have a class that handles cookies in an application-specific manner, and I want to consolidate all the cookie-related functions to this class. However, I cannot use this code if I simply move it from the aspx page (where it currently resides) to the aforementioned class because I get the error: <code>'Name' Response is not declared.</code> I modified the class to allow the passing of a reference to the <strong><code>Response</code></strong> object:</p> <pre><code>Public Function cookieExists(ByVal cName As String, ByRef Response As HttpResponse) As Boolean For Each c As HttpCookie In Response.Cookies If c.Name = cName Then Return True Next Return False End Function </code></pre> <p>My question is: Is there a better way?</p>
[ { "answer_id": 281872, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 5, "selected": true, "text": "HttpContext.Current.Response\nHttpContext.Current.Request\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
281,866
<p>Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title.</p> <p>I have a similar problem but needing multiple aggregates. I'd like to display a list of items in any of 3 formats depending on user options:</p> <ul> <li>My item's name (15 total, 13 owned by me)</li> <li>My item's name (15 total)</li> <li>My item's name (13 owned by me)</li> </ul> <p>My database is:</p> <ul> <li><strong>items</strong>: itemId, itemName, ownerId</li> <li><strong>categories</strong>: catId, catName</li> <li><strong>map</strong>: mapId, itemId, catId</li> </ul> <p>The query below gets: category name, count of item ids per category</p> <pre><code>SELECT categories.catName, COUNT(map.itemId) AS item_count FROM categories LEFT JOIN map ON categories.catId = map.catId GROUP BY categories.catName </code></pre> <p>This one gets: category name, count of item ids per category for this owner_id only</p> <pre><code>SELECT categories.catName, COUNT(map.itemId) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId WHERE owner = @ownerId GROUP BY categories.catId </code></pre> <p>But how do i get them at the same time in a single query? I.e.: category name, count of item ids per category, count of item ids per category for this owner_id only</p> <p>Bonus. How can I optionally only retrieve where catId count != 0 for any of these? In trying "WHERE item_count &lt;> 0" I get:</p> <pre><code>MySQL said: Documentation #1054 - Unknown column 'rid_count' in 'where clause' </code></pre>
[ { "answer_id": 281894, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "SUM() COUNT() SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n LEFT JOIN map m USING (catid)\n LEFT JOIN items i USING (itemid)\nGROUP BY c.catid;\n map SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n INNER JOIN map m USING (catid)\n INNER JOIN items i USING (itemid)\nGROUP BY c.catid;\n SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n LEFT JOIN map m USING (catid)\n LEFT JOIN items i USING (itemid)\nGROUP BY c.catid\nHAVING item_count > 0;\n WHERE WHERE GROUP BY HAVING ORDER BY" }, { "answer_id": 281908, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "SELECT categories.catName, \n COUNT(map.itemId) AS item_count,\n SUM(CASE WHEN owner= @ownerid THEN 1 ELSE 0 END) AS owner_item_count\nFROM categories\nLEFT JOIN map ON categories.catId = map.catId\nLEFT JOIN items ON items.itemId = map.itemId\nGROUP BY categories.catId\nHAVING COUNT(map.itemId) > 0\n" }, { "answer_id": 281955, "author": "eswald", "author_id": 21229, "author_profile": "https://Stackoverflow.com/users/21229", "pm_score": 2, "selected": false, "text": "SELECT categories.catName, \n COUNT(map.itemId) AS item_count,\n COUNT(items.itemId) AS owner_item_count\nFROM categories\nINNER JOIN map\n ON categories.catId = map.catId\nLEFT JOIN items\n ON items.itemId = map.itemId\n AND items.owner = @ownerId\nGROUP BY categories.catId\n HAVING owner_item_count" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
281,881
<p>I am trying to keep track of something and using the SessionID as they key to that object</p> <p>However the SessionID every 2-3 reqiests changes shouldn't it remain the same?</p> <pre><code>HttpContext.Session.SessionID </code></pre> <p>Is the code I am using.</p>
[ { "answer_id": 458694, "author": "robnardo", "author_id": 56774, "author_profile": "https://Stackoverflow.com/users/56774", "pm_score": 3, "selected": false, "text": "Session[\"myVar\"] = \"1234\";\n <%= this.Session.SessionID %>\n" }, { "answer_id": 5835631, "author": "javierlinked", "author_id": 65629, "author_profile": "https://Stackoverflow.com/users/65629", "pm_score": 5, "selected": false, "text": "Global.asax.cs void Session_Start(object sender, EventArgs e)\n{\n HttpContext.Current.Session.Add(\"__MyAppSession\", string.Empty);\n}\n" }, { "answer_id": 21244428, "author": "Flea", "author_id": 256212, "author_profile": "https://Stackoverflow.com/users/256212", "pm_score": 0, "selected": false, "text": "global.asax" }, { "answer_id": 36168332, "author": "sobelito", "author_id": 643723, "author_profile": "https://Stackoverflow.com/users/643723", "pm_score": 0, "selected": false, "text": "<add key=\"AWSAccessKey\" value=\"XXX\" />\n<add key=\"AWSSecretKey\" value=\"YYY\" />\n <sessionState timeout=\"20\"\n mode=\"Custom\"\n customProvider=\"DynamoDBSessionStoreProvider\">\n <providers>\n <add name=\"DynamoDBSessionStoreProvider\"\n type=\"Amazon.SessionProvider.DynamoDBSessionStateStore, AWS.SessionProvider\"\n AWSProfilesLocation=\".aws/credentials\"\n Table=\"ASP.NET_SessionState\"\n Region=\"us-east-1\"\n />\n </providers>\n</sessionState>\n void Session_Start(object sender, EventArgs e) {\n HttpContext.Current.Session.Add(\"somethingToForceSessionIdToStick\", string.Empty);\n}\n @HttpContext.Current.Session.SessionID\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
281,884
<p>Can someone suggest a small webserver implementation that will illustrate the concepts of what a webserver does? It should be in a language that is easily read, and understood, and should implement security and cgi, maybe javascript? </p>
[ { "answer_id": 10630612, "author": "mikera", "author_id": 214010, "author_profile": "https://Stackoverflow.com/users/214010", "pm_score": 0, "selected": false, "text": "(ns my-app\n (:use noir.core)\n (:require [noir.server :as server]))\n\n(defpage \"/welcome\" []\n \"Welcome to Noir!\")\n\n(server/start 8080)\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23599/" ]
281,888
<p>In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:</p> <pre><code>import subprocess subprocess.Popen('explorer "C:\path\of\folder"') </code></pre> <p>but I have no solution for files.</p>
[ { "answer_id": 281911, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 8, "selected": true, "text": "import subprocess\nsubprocess.Popen(r'explorer /select,\"C:\\path\\of\\folder\\file\"')\n" }, { "answer_id": 27251095, "author": "user1767754", "author_id": 1767754, "author_profile": "https://Stackoverflow.com/users/1767754", "pm_score": 4, "selected": false, "text": "import subprocess\nsubprocess.call(\"explorer C:\\\\temp\\\\yourpath\", shell=True)\n" }, { "answer_id": 49159988, "author": "Guillaume Lebreton", "author_id": 5823489, "author_profile": "https://Stackoverflow.com/users/5823489", "pm_score": 5, "selected": false, "text": "subprocess" }, { "answer_id": 50965628, "author": "ewerybody", "author_id": 469322, "author_profile": "https://Stackoverflow.com/users/469322", "pm_score": 4, "selected": false, "text": "explorer run() import os\nimport subprocess\nFILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')\n\ndef explore(path):\n # explorer would choke on forward slashes\n path = os.path.normpath(path)\n\n if os.path.isdir(path):\n subprocess.run([FILEBROWSER_PATH, path])\n elif os.path.isfile(path):\n subprocess.run([FILEBROWSER_PATH, '/select,', path])\n" }, { "answer_id": 52881473, "author": "MacNutter", "author_id": 10331178, "author_profile": "https://Stackoverflow.com/users/10331178", "pm_score": 4, "selected": false, "text": "import easygui\nfile = easygui.fileopenbox()\n" }, { "answer_id": 65309355, "author": "Stephan Yazvinski", "author_id": 13457123, "author_profile": "https://Stackoverflow.com/users/13457123", "pm_score": 3, "selected": false, "text": "import subprocess\nsubprocess.Popen(f'explorer /select,{variableHere}')\n import subprocess\nsubprocess.Popen(f'explorer \"{variableHere}\"')\n" }, { "answer_id": 70241584, "author": "Pixelsuft", "author_id": 16315296, "author_profile": "https://Stackoverflow.com/users/16315296", "pm_score": -1, "selected": false, "text": "import os\nimport ctypes\nSW_SHOWDEFAULT = 10\npath_to_open = os.getenv('windir')\nctypes.windll.shell32.ShellExecuteW(0, \"open\", path_to_open, 0, 0, SW_SHOWDEFAULT)\n" }, { "answer_id": 72888227, "author": "RAllenAZ", "author_id": 19417436, "author_profile": "https://Stackoverflow.com/users/19417436", "pm_score": 0, "selected": false, "text": "import subprocess\nsubprocess.Popen(r'explorer /open,\"C:\\path\\of\\folder\\file\"')\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25705/" ]
281,890
<p>There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.</p> <p>Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)</p>
[ { "answer_id": 497798, "author": "Kariem", "author_id": 12039, "author_profile": "https://Stackoverflow.com/users/12039", "pm_score": 3, "selected": false, "text": "<target name=\"schemaexport\" description=\"Export schema to DDL file\"\n depends=\"compile-jpa\"> <!-- compile model classes before running hibernatetool -->\n\n <!-- task definition; project.class.path contains all necessary libs -->\n <taskdef name=\"hibernatetool\" classname=\"org.hibernate.tool.ant.HibernateToolTask\"\n classpathref=\"project.class.path\" />\n\n <hibernatetool destdir=\"export/db\"> <!-- check that directory exists -->\n <jpaconfiguration persistenceunit=\"myPersistenceUnitName\" />\n <classpath>\n <!--\n compiled model classes and other configuration files don't forget\n to put the parent directory of META-INF/persistence.xml here\n -->\n </classpath>\n <hbm2ddl outputfilename=\"schemaexport.sql\" format=\"true\"\n export=\"false\" drop=\"true\" />\n </hibernatetool>\n</target>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450527/" ]
281,891
<p>I'm using ASP.NET Membership and noticed there isn't a method in the <a href="http://msdn.microsoft.com/en-us/library/system.web.security.roles_members.aspx" rel="nofollow noreferrer">Roles class</a> to <em>modify</em> a role (its name for instance), only to create and delete them.</p> <p>Is it possible or it's not supported?</p> <p>EDIT: @CheGueVerra: Yes, nice workaround. </p> <p>Do you know (for extra credit :) ) why it's not possible?</p>
[ { "answer_id": 281935, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 5, "selected": true, "text": "public void RenameRoleAndUsers(string OldRoleName, string NewRoleName)\n{\n string[] users = Roles.GetUsersInRole(OldRoleName);\n Roles.CreateRole(NewRoleName);\n Roles.AddUsersToRole(users, NewRoleName);\n Roles.RemoveUsersFromRole(users, OldRoleName);\n Roles.DeleteRole(OldRoleName);\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
281,909
<p>let's say I have a excel spread sheet like below:</p> <pre> col1 col2 ------------ dog1 dog dog2 dog dog3 dog dog4 dog cat1 cat cat2 cat cat3 cat </pre> <p>I want to return a range of cells (dog1,dog2,dog3,dog4) or (cat1,cat2,cat3) based on either "dog" or "cat"</p> <p>I know I can do a loop to check one by one, but is there any other method in VBA so I can "filter" the result in one shot? </p> <p>maybe the Range.Find(XXX) can help, but I only see examples for just one cell not a range of cells.</p> <p>Please advice</p> <p>Regards</p>
[ { "answer_id": 282141, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 0, "selected": false, "text": "=CHAR(RANDBETWEEN(65,90))\n =TRANSPOSE(UniqueChars(A1:A1000000))\n Option Explicit\n\nPublic Function UniqueChars(rng As Range)\n\nDim dict As New Dictionary\nDim vals\nDim row As Long\nDim started As Single\n\n started = Timer\n\n vals = rng.Value2\n\n For row = LBound(vals, 1) To UBound(vals, 1)\n If dict.Exists(vals(row, 1)) Then\n Else\n dict.Add vals(row, 1), vals(row, 1)\n End If\n Next\n\n UniqueChars = dict.Items\n\n Debug.Print Timer - started\n\nEnd Function\n" }, { "answer_id": 282170, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 1, "selected": false, "text": "Range(\"A1:A1000000\").AdvancedFilter Action:=xlFilterCopy, CopyToRange:= Range(\"F1\"), Unique:=True\n" }, { "answer_id": 282353, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Sub GetRange()\nDim cn As Object\nDim rs As Object\nDim strcn, strFile, strPos1, strPos2\n\n Set cn = CreateObject(\"ADODB.Connection\")\n Set rs = CreateObject(\"ADODB.Recordset\")\n\n strFile = ActiveWorkbook.FullName\n\n strcn = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" _\n & strFile & \";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';\"\n\n cn.Open strcn\n\n rs.Open \"SELECT * FROM [Sheet1$]\", cn, 3 'adOpenStatic'\n\n rs.Find \"Col2='cat'\"\n strPos1 = rs.AbsolutePosition + 1\n rs.MoveLast\n If Trim(rs!Col2 & \"\") <> \"cat\" Then\n rs.Find \"Col2='cat'\", , -1 'adSearchBackward'\n strPos2 = rs.AbsolutePosition + 1\n Else\n strPos2 = rs.AbsolutePosition + 1\n End If\n Range(\"A\" & strPos1, \"B\" & strPos2).Select\nEnd Sub\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36674/" ]
281,912
<p>I need a distinct sound to play when a error occurs. The error is the result of a problem with one of perhaps two hundred barcodes that are being inputted in rapid fire. The event queue seems to handle keyboard input (which the barcode scanner emulates) first, and playing of my sound second. So if the barcodes are scanned quickly, the error sound stays in the queue, being bumped by the next scan.</p> <p>Can I manipulate the priority of the queue?</p>
[ { "answer_id": 281915, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "keyup" }, { "answer_id": 281947, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 0, "selected": false, "text": "setTimeout()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
281,913
<p>I need to execute a SQL Server system stored procedure, programmatically, and since it executes in the current schema, I need to change it on the fly.</p> <p>Like this</p> <p>Statement st = connection.createStatement(); st.execute("EXEC SP_ADDUSER ' ', ' '");</p> <p>But SP_ADDUSER only executes on the current schema set for the connection, so if I wanted to create users in various schemas, I'd need to change it, and that's what I am looking for.</p>
[ { "answer_id": 282065, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "EXEC <DatabaseName>..sp_adduser master USE master\nEXEC sp_addlogin 'test1'\nEXEC SandBox..sp_adduser 'test1'\n using System;\nusing System.Data.SqlClient;\n\nnamespace TestUse\n{\n class Program\n {\n static void Main(string[] args)\n {\n SqlConnection cn = new SqlConnection(\"Server=(local);Database=master;Trusted_Connection=True;\");\n cn.Open();\n SqlCommand cmd = new SqlCommand(\"USE master; EXEC sp_addlogin 'test1'; EXEC SandBox..sp_adduser 'test1'\", cn);\n cmd.ExecuteNonQuery();\n cn.Close();\n }\n }\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,922
<p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p> <pre><code>c = ClientCreator(reactor, Greeter) c.connectTCP(self.host, self.port).addCallback(request) reactor.run() </code></pre> <p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p> <p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p> <p>Addendum &amp; Clarification:</p> <p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow noreferrer">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p> <p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow noreferrer">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p> <p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p> <p><strong>Conclusion:</strong> I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow noreferrer">http://launchpad.net/dstorage</a>).</p>
[ { "answer_id": 281991, "author": "eswald", "author_id": 21229, "author_profile": "https://Stackoverflow.com/users/21229", "pm_score": 2, "selected": false, "text": "import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((self.host, self.port))\ns.send(output)\ndata = s.recv(size)\ns.close()\n recv()" }, { "answer_id": 282301, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 1, "selected": false, "text": "reactor.stop()" }, { "answer_id": 288650, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 3, "selected": true, "text": "ClientCreator(...).connectTCP(...) self.transport.loseConnection()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35247/" ]
281,928
<p>I often find myself writing simple for loops to perform an operation to many files, for example:</p> <pre><code>for i in `find . | grep ".xml$"`; do bzip2 $i; done </code></pre> <p>It seems a bit depressing that on my 4-core machine only one core is getting used.. is there an easy way I can add parallelism to my shell scripting?</p> <p>EDIT: To introduce a bit more context to my problems, sorry I was not more clear to start with!</p> <p>I often want to run simple(ish) scripts, such as plot a graph, compress or uncompress, or run some program, on reasonable sized datasets (usually between 100 and 10,000). The scripts I use to solve such problems look like the one above, but might have a different command, or even a sequence of commands to execute.</p> <p>For example, just now I am running:</p> <pre><code>for i in `find . | grep ".xml.bz2$"`; do find_graph -build_graph $i.graph $i; done </code></pre> <p>So my problems are in no way bzip specific! (Although parallel bzip does look cool, I intend to use it in future).</p>
[ { "answer_id": 281952, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "for i in `find . | grep \".xml$\"`; do bzip2 $i&; done\n" }, { "answer_id": 281967, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 3, "selected": false, "text": "runN -n 4 bzip2 `find . | grep \".xml$\"`\n" }, { "answer_id": 282101, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "%.xml.bz2 : %.xml\n\n\nall: $(patsubt %.xml,%xml.bz2,$(shell find . -name '*.xml') ) \n nice make -j 5\n" }, { "answer_id": 282151, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\n# Replace NNN with the number of loops you want to run through\n# and CMD with the command you want to parallel-ize.\n\nset -m\n\nnodes=`grep processor /proc/cpuinfo | wc -l`\njob=($(yes 0 | head -n $nodes | tr '\\n' ' '))\n\nisin()\n{\n local v=$1\n\n shift 1\n while (( $# > 0 ))\n do\n if [ $v = $1 ]; then return 0; fi\n shift 1\n done\n return 1\n}\n\ndowait()\n{\n while true\n do\n nj=( $(jobs -p) )\n if (( ${#nj[@]} < nodes ))\n then\n for (( o=0; o<nodes; o++ ))\n do\n if ! isin ${job[$o]} ${nj[*]}; then let job[o]=0; fi\n done\n return;\n fi\n sleep 1\n done\n}\n\nlet x=0\nwhile (( x < NNN ))\ndo\n for (( o=0; o<nodes; o++ ))\n do\n if (( job[o] == 0 )); then break; fi\n done\n\n if (( o == nodes )); then\n dowait;\n continue;\n fi\n\n CMD &\n let job[o]=$!\n\n let x++\ndone\n\nwait\n" }, { "answer_id": 282177, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "xargs -n find -name \\*.xml -print0 | xargs -0 -n 1 -P 3 bzip2\n" }, { "answer_id": 22211099, "author": "Ole Tange", "author_id": 363028, "author_profile": "https://Stackoverflow.com/users/363028", "pm_score": 2, "selected": true, "text": "pbzip2 find . | grep \".xml$\" | parallel bzip2\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27074/" ]
281,933
<p>Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:</p> <pre><code>String word = "foobooandfoo"; String converted = ""; converted = word.replaceAll("[ao]", "1"); converted = converted.replaceAll("[df]", "2"); converted = converted.replaceAll("[n]", "3"); </code></pre> <p>My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?</p>
[ { "answer_id": 281956, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "Matcher.replaceAll() String" }, { "answer_id": 281958, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "Matcher StringBuilder result = new StringBuilder(word.length());\n\nfor (char c : word.toCharArray()) {\n switch (c) {\n case 'a': case 'o': result.append('1'); break;\n case 'd': case 'f': result.append('2'); break;\n case 'n': result.append('3'); break;\n default: result.append(c); break;\n }\n}\n" }, { "answer_id": 281961, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "public String convert(String text)\n{\n char[] chars = new char[text.length()];\n for (int i=0; i < text.length(); i++)\n {\n char c = text.charAt(i);\n char converted;\n switch (c)\n {\n case 'a': converted = '1'; break;\n case 'o': converted = '1'; break;\n case 'd': converted = '2'; break;\n case 'f': converted = '2'; break;\n case 'n': converted = '3'; break;\n default : converted = c; break;\n }\n chars[i] = converted;\n }\n return new String(chars);\n}\n" }, { "answer_id": 281977, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": " public static void translate(StringBuilder str, char[] table)\n {\n for (int idx = 0; idx < str.length(); ++idx) {\n char ch = str.charAt(idx);\n if (ch < table.length) {\n ch = table[ch];\n str.setCharAt(idx, ch);\n }\n }\n }\n str public static void translate(StringBuilder str, Map<Character, Character> table)\n {\n for (int idx = 0; idx < str.length(); ++idx) {\n char ch = str.charAt(idx);\n Character conversion = table.get(ch);\n if (conversion != null) \n str.setCharAt(idx, conversion);\n }\n }\n StringBuilder" }, { "answer_id": 282025, "author": "Andrea Francia", "author_id": 36131, "author_profile": "https://Stackoverflow.com/users/36131", "pm_score": 0, "selected": false, "text": "String word = \"foobooandfoo\";\nString converted = word.replaceAll(\"[ao]\", \"1\")\n .replaceAll(\"[df]\", \"2\")\n .replaceAll(\"[n]\", \"3\");\n" }, { "answer_id": 282115, "author": "P Arrayah", "author_id": 33459, "author_profile": "https://Stackoverflow.com/users/33459", "pm_score": -1, "selected": false, "text": "// usage:\nMap<String, String> replaceRules = new HashMap<String, String>();\nreplaceRules.put(\"ao\", \"1\");\nreplaceRules.put(\"df\", \"2\");\nreplaceRules.put(\"n\", \"3\");\nString s = replacePartsOf(\"foobooandfoo\", replaceRules);\n\n// actual method\npublic String replacePartsOf(String thisString, Map<String, String> withThese) {\n for(Entry<String, String> rule : withThese.entrySet()) {\n thisString = thisString.replaceAll(rule.getKey(), rule.getValue());\n }\n\n return thisString;\n}\n" }, { "answer_id": 283569, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "String text = \"foobooandfoo\";\nPattern p = Pattern.compile(\"([ao])|([df])|n\");\nMatcher m = p.matcher(text);\nStringBuffer sb = new StringBuffer();\nwhile (m.find())\n{\n m.appendReplacement(sb, \"\");\n sb.append(m.start(1) != -1 ? '1' :\n m.start(2) != -1 ? '2' :\n '3');\n}\nm.appendTail(sb);\nSystem.out.println(sb.toString());\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
281,945
<p>Does anyone know of a way to store values as NVARCHAR in a manually created query in ColdFusion using the querynew() function? I have multiple parts of a largish program relying on using a query as an input point to construct an excel worksheet (using Ben's POI) so it's somewhat important I can continue to use it as a query to avoid a relatively large rewrite.</p> <p>The problem came up when a user tried storing something that is outside of the VARCHAR range, some Japanese characters and such.</p> <p>Edit: If this is not possible, and you are 100% sure, I'd like to know that too :)</p>
[ { "answer_id": 282260, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 1, "selected": false, "text": "<cfset x = QueryNew(\"foobar\")/>\n<cfset queryAddRow(x) />\n<cfset querySetCell(x, \"foobar\", chr(163)) />\n<cfdump var=\"#x#\">\n" }, { "answer_id": 522748, "author": "Mike Oliver", "author_id": 13921, "author_profile": "https://Stackoverflow.com/users/13921", "pm_score": 2, "selected": true, "text": "<cfset x = queryNew(\"foo,bar\",\"integer,varchar\") />\n" }, { "answer_id": 538288, "author": "Henry", "author_id": 35634, "author_profile": "https://Stackoverflow.com/users/35634", "pm_score": 0, "selected": false, "text": "<cfprocessingdirective pageEncoding=\"utf-8\"> \n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
281,951
<p>We're using the following command line from within a Windows Service developed with C# .Net Framework 1.1:</p> <pre><code>net use z: \\myComputer\c$ </code></pre> <p>The service is running under a domain account that is a local administrator on "myComputer". After debugging the code we can see that it does not return any errors but the "z:" drive is never mapped. We've tried the exact same code from a console application and it works properly. What is it that we need to add to the Service to make this work?</p> <p>The code we're using is included below.</p> <p>Regards,<br> Sergio</p> <pre><code>startInfo.FileName = "net"; startInfo.Arguments = string.Format(@"use {0}: \\{1}\{2}", driveLetter, computerName, folder).Trim(); startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; proc.EnableRaisingEvents = false; proc.StartInfo = startInfo; proc.Start(); // If there is an error during the mapping of the drive, it will be read // from the StandardError property which is a StreamReader object and // be fed into the error output parameter. using(StreamReader errorReader = proc.StandardError) { string standardError = string.Empty; while((standardError = errorReader.ReadLine()) != null) { error += standardError + " "; } } proc.WaitForExit(); </code></pre>
[ { "answer_id": 281959, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "net use /?" }, { "answer_id": 11656869, "author": "Gary", "author_id": 393004, "author_profile": "https://Stackoverflow.com/users/393004", "pm_score": 0, "selected": false, "text": "use \\\\server\\c$ /user:admin password\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
281,960
<p>I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;script&gt; function focusTest(el) { el.select(); } &lt;/script&gt; &lt;input type="text" value="one" OnFocus="focusTest(this); return false;" /&gt; &lt;br/&gt; &lt;input type="text" value="two" OnFocus="focusTest(this); return false;" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)</p>
[ { "answer_id": 282015, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": true, "text": "function focusTest(el)\n{\n setTimeout (function () {el.select();} , 50 );\n}\n onMouseUp=\"return false;\"\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2749/" ]
281,979
<p>Do you generate your data dictionary? If so, how?</p> <p>I use extended procedures in SQL Server 2005 to hold onto table and field information. I have some queries that create a dictionary out of them, but it's ... meh. Do you have a particular query or tool you use? Do you generate it off of your database diagrams?</p> <p>Googling for "data dictionary sql server" comes up with many queries, but they're all about equally as attractive. Which is to say, good starting off points, but not production ready.</p>
[ { "answer_id": 282085, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "INFORMATION_SCHEMA INFORMATION_SCHEMA.ROUTINES" }, { "answer_id": 283813, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "currency_id Tbl_currency description item_Description nvarchar(50) document_Description ntext SELECT DISTINT columnName FROM Tbl_Column\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/281979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11947/" ]
282,002
<p>In developing search for a site I am building, I decided to go the cheap and quick way and use Microsoft Sql Server's Full Text Search engine instead of something more robust like Lucene.Net.</p> <p>One of the features I would like to have, though, is google-esque relevant document snippets. I quickly found determining "relevant" snippets is more difficult than I realized. </p> <p>I want to choose snippets based on search term density in the found text. So, essentially, I need to find the most search term dense passage in the text. Where a passage is some arbitrary number of characters (say 200 -- but it really doesn't matter).</p> <p>My first thought is to use .IndexOf() in a loop and build an array of term distances (subtract the index of the found term from the previously found term), then ... what? Add up any two, any three, any four, any five, sequential array elements and use the one with the smallest sum (hence, the smallest distance between search terms).</p> <p>That seems messy.</p> <p>Is there an established, better, or more obvious way to do this than what I have come up with?</p>
[ { "answer_id": 284083, "author": "CleverPatrick", "author_id": 22399, "author_profile": "https://Stackoverflow.com/users/22399", "pm_score": 1, "selected": false, "text": "private static string FindRelevantSnippets(string infoText, string[] searchTerms)\n {\n List<int> termLocations = new List<int>();\n foreach (string term in searchTerms)\n {\n int termStart = infoText.IndexOf(term);\n while (termStart > 0)\n {\n termLocations.Add(termStart);\n termStart = infoText.IndexOf(term, termStart + 1);\n }\n }\n\n if (termLocations.Count == 0)\n {\n if (infoText.Length > 250)\n return infoText.Substring(0, 250);\n else\n return infoText;\n }\n\n termLocations.Sort();\n\n List<int> termDistances = new List<int>();\n for (int i = 0; i < termLocations.Count; i++)\n {\n if (i == 0)\n {\n termDistances.Add(0);\n continue;\n }\n termDistances.Add(termLocations[i] - termLocations[i - 1]);\n }\n\n int smallestSum = int.MaxValue;\n int smallestSumIndex = 0;\n for (int i = 0; i < termDistances.Count; i++)\n {\n int sum = termDistances.Skip(i).Take(5).Sum();\n if (sum < smallestSum)\n {\n smallestSum = sum;\n smallestSumIndex = i;\n }\n }\n int start = Math.Max(termLocations[smallestSumIndex] - 128, 0);\n int len = Math.Min(smallestSum, infoText.Length - start);\n len = Math.Min(len, 250);\n return infoText.Substring(start, len);\n }\n" }, { "answer_id": 6462496, "author": "yu_ominae", "author_id": 643192, "author_profile": "https://Stackoverflow.com/users/643192", "pm_score": 2, "selected": false, "text": "public static string SelectKeywordSnippets(string StringToSnip, string[] Keywords, int SnippetLength)\n {\n string snippedString = \"\";\n List<int> keywordLocations = new List<int>();\n\n //Get the locations of all keywords\n for (int i = 0; i < Keywords.Count(); i++)\n keywordLocations.AddRange(SharedTools.IndexOfAll(StringToSnip, Keywords[i], StringComparison.CurrentCultureIgnoreCase));\n\n //Sort locations\n keywordLocations.Sort();\n\n //Remove locations which are closer to each other than the SnippetLength\n if (keywordLocations.Count > 1)\n {\n bool found = true;\n while (found)\n {\n found = false;\n for (int i = keywordLocations.Count - 1; i > 0; i--)\n if (keywordLocations[i] - keywordLocations[i - 1] < SnippetLength / 2)\n {\n keywordLocations[i - 1] = (keywordLocations[i] + keywordLocations[i - 1]) / 2;\n\n keywordLocations.RemoveAt(i);\n\n found = true;\n }\n }\n }\n\n //Make the snippets\n if (keywordLocations.Count > 0 && keywordLocations[0] - SnippetLength / 2 > 0)\n snippedString = \"... \";\n foreach (int i in keywordLocations)\n {\n int stringStart = Math.Max(0, i - SnippetLength / 2);\n int stringEnd = Math.Min(i + SnippetLength / 2, StringToSnip.Length);\n int stringLength = Math.Min(stringEnd - stringStart, StringToSnip.Length - stringStart);\n snippedString += StringToSnip.Substring(stringStart, stringLength);\n if (stringEnd < StringToSnip.Length) snippedString += \" ... \";\n if (snippedString.Length > 200) break;\n }\n\n return snippedString;\n\n }\n private static List<int> IndexOfAll(string haystack, string needle, StringComparison Comparison)\n {\n int pos;\n int offset = 0;\n int length = needle.Length;\n List<int> positions = new List<int>();\n while ((pos = haystack.IndexOf(needle, offset, Comparison)) != -1)\n {\n positions.Add(pos);\n offset = pos + length;\n }\n return positions;\n }\n" }, { "answer_id": 18797122, "author": "morpheus", "author_id": 147530, "author_profile": "https://Stackoverflow.com/users/147530", "pm_score": 2, "selected": false, "text": "public class Highlighter\n{ \n private class Packet\n {\n public string Sentence;\n public double Density;\n public int Offset;\n }\n\n public static string FindSnippet(string text, string query, int maxLength)\n {\n if (maxLength < 0)\n {\n throw new ArgumentException(\"maxLength\");\n }\n var words = query.Split(' ').Where(w => !string.IsNullOrWhiteSpace(w)).Select(word => word.ToLower()).ToLookup(s => s); \n var sentences = text.Split('.');\n var i = 0;\n var packets = sentences.Select(sentence => new Packet \n { \n Sentence = sentence, \n Density = ComputeDensity(words, sentence),\n Offset = i++\n }).OrderByDescending(packet => packet.Density);\n var list = new SortedList<int, string>(); \n int length = 0; \n foreach (var packet in packets)\n {\n if (length >= maxLength || packet.Density == 0)\n {\n break;\n }\n string sentence = packet.Sentence;\n list.Add(packet.Offset, sentence.Substring(0, Math.Min(sentence.Length, maxLength - length)));\n length += packet.Sentence.Length;\n }\n var sb = new List<string>();\n int previous = -1;\n foreach (var item in list)\n {\n var offset = item.Key;\n var sentence = item.Value;\n if (previous != -1 && offset - previous != 1)\n {\n sb.Add(\".\");\n }\n previous = offset; \n sb.Add(Highlight(sentence, words)); \n }\n return String.Join(\".\", sb);\n }\n\n private static string Highlight(string sentence, ILookup<string, string> words)\n {\n var sb = new List<string>();\n var ff = true;\n foreach (var word in sentence.Split(' '))\n {\n var token = word.ToLower();\n if (ff && words.Contains(token))\n {\n sb.Add(\"[[HIGHLIGHT]]\");\n ff = !ff;\n }\n if (!ff && !string.IsNullOrWhiteSpace(token) && !words.Contains(token))\n {\n sb.Add(\"[[ENDHIGHLIGHT]]\");\n ff = !ff;\n }\n sb.Add(word);\n }\n if (!ff)\n {\n sb.Add(\"[[ENDHIGHLIGHT]]\");\n }\n return String.Join(\" \", sb);\n }\n\n private static double ComputeDensity(ILookup<string, string> words, string sentence)\n { \n if (string.IsNullOrEmpty(sentence) || words.Count == 0)\n {\n return 0;\n }\n int numerator = 0;\n int denominator = 0;\n foreach(var word in sentence.Split(' ').Select(w => w.ToLower()))\n {\n if (words.Contains(word))\n {\n numerator++;\n }\n denominator++;\n }\n if (denominator != 0)\n {\n return (double)numerator / denominator;\n }\n else\n {\n return 0;\n }\n }\n}\n" }, { "answer_id": 45679025, "author": "Tom Gullen", "author_id": 356635, "author_profile": "https://Stackoverflow.com/users/356635", "pm_score": 0, "selected": false, "text": "documentText.Substring(returnValue, snippetLength) ... resolution 1 score Math.pow(wordLength, 2) private static int GetSnippetStartPoint(string documentText, string originalQuery, int snippetLength)\n{\n // Normalise document text\n documentText = documentText.Trim();\n if (string.IsNullOrWhiteSpace(documentText)) return 0;\n\n // Return 0 if entire doc fits in snippet\n if (documentText.Length <= snippetLength) return 0;\n\n // Break query down into words\n var wordsInQuery = new HashSet<string>();\n {\n var queryWords = originalQuery.Split(' ');\n foreach (var word in queryWords)\n {\n var normalisedWord = word.Trim().ToLower();\n if (string.IsNullOrWhiteSpace(normalisedWord)) continue;\n if (wordsInQuery.Contains(normalisedWord)) continue;\n wordsInQuery.Add(normalisedWord);\n }\n }\n\n // Create moving window to get maximum trues\n var windowStart = 0;\n double maxScore = 0;\n var maxWindowStart = 0;\n\n // Higher number less accurate but faster\n const int resolution = 5;\n\n while (true)\n {\n var text = documentText.Substring(windowStart, snippetLength);\n\n // Get score of this chunk\n // This isn't perfect, as window moves in steps of resolution first and last words will be partial.\n // Could probably be improved to iterate words and not characters.\n var words = text.Split(' ').Select(c => c.Trim().ToLower());\n double score = 0;\n foreach (var word in words)\n {\n if (wordsInQuery.Contains(word))\n {\n // The longer the word, the more important.\n // Can simply replace with score += 1 for simpler model.\n score += Math.Pow(word.Length, 2);\n } \n }\n if (score > maxScore)\n {\n maxScore = score;\n maxWindowStart = windowStart;\n }\n\n // Setup next iteration\n windowStart += resolution;\n\n // Window end passed document end\n if (windowStart + snippetLength >= documentText.Length)\n {\n break;\n }\n }\n\n return maxWindowStart;\n}\n SOUNDEX" }, { "answer_id": 53771680, "author": "Peter Rakké", "author_id": 4022446, "author_profile": "https://Stackoverflow.com/users/4022446", "pm_score": 1, "selected": false, "text": "public static string GetSnippet(string text, string word)\n{\n if (text.IndexOf(word, StringComparison.InvariantCultureIgnoreCase) == -1)\n {\n return \"\";\n }\n\n var matches = new Regex(@\"\\b(\\S+)\\s?\", RegexOptions.Singleline | RegexOptions.Compiled).Matches(text);\n\n var p = -1;\n for (var i = 0; i < matches.Count; i++)\n {\n if (matches[i].Value.IndexOf(word, StringComparison.InvariantCultureIgnoreCase) != -1)\n {\n p = i;\n break;\n }\n }\n\n if (p == -1) return \"\";\n var snippet = \"\";\n for (var x = Math.Max(p - 10, 0); x < p + 10; x++)\n {\n snippet += matches[x].Value + \" \";\n }\n return snippet;\n}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22399/" ]
282,007
<p>I want to programmatically disable the notification I get when I connect to a wireless network. I know there is a way to disable ALL notifications (see <a href="http://www.howtogeek.com/howto/windows/disable-notification-balloons-in-xp/" rel="nofollow noreferrer">here</a>) but is there a way to only disable the one issued by Windows wireless Manager (i.e. wlanapi.dll).</p> <p>Many thanks!</p>
[ { "answer_id": 10386235, "author": "Arasch", "author_id": 1366133, "author_profile": "https://Stackoverflow.com/users/1366133", "pm_score": 0, "selected": false, "text": "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\nNew \\ DWORD\nEnableBalloonTips\nHexadecimal\n0\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,014
<p>I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...</p> <p>Here's the weird part. When I open a form in the designer (Visual&nbsp;Studio&nbsp;2008) that uses the object the file gets created. It's obviously running under the design time vhost process...</p> <p>The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...</p> <p>What is the explanation? Is there a reference?</p>
[ { "answer_id": 282031, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 0, "selected": false, "text": "Form_Load" }, { "answer_id": 282277, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace Test\n{\n public class ComponentClass : Component\n {\n public ComponentClass()\n {\n MessageBox.Show(\"Runtime!\");\n }\n }\n}\n using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace Test\n{\n public class ComponentClass : Component\n {\n public ComponentClass()\n {\n if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n {\n MessageBox.Show(\"Runtime!\");\n }\n }\n }\n}\n" }, { "answer_id": 1000153, "author": "tzup", "author_id": 121755, "author_profile": "https://Stackoverflow.com/users/121755", "pm_score": 2, "selected": false, "text": "public static bool DesignMode\n{\n get { return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == \"devenv\"); }\n}\n if (!DesignMode)\n{\n // Run code that breaks in Visual Studio Designer (like trying to get a DB connection)\n}\n LicensManager.UsageMode" }, { "answer_id": 5048767, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 2, "selected": false, "text": "public static bool IsAnyInDesignMode(Control control){\n while(control != null){\n if(control.Site != null && control.Site.DesignMode)\n return true;\n control = control.Parent;\n }\n return false;\n}\n DesignMode" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36693/" ]
282,016
<p>I need to make a piece of C# code interact through COM with all kinds of implementations.</p> <p>To make it easeier for users of that integration, I included the interacted interfaces in IDL (as part of a relevant existing DLL, but without coclass or implementation), then got that into my C# code by running Tlbimp to create the types definition.</p> <p>I implemented my C#, creating COM objects based on Windows registry info and casting the object into the interface I need.</p> <p>I then created a C# implementation of the interface in a seperate project and registered it. The main program creates the testing COM object correctly but fails to cast it into the interface (gets a null object when using C# 'as', gets an InvalidCastException of explicit cast).</p> <p>Can someone suggest why the interface is not identified as implemented by the testing object?</p> <p>This is the interface defition in IDL (compiled in C++ in VS 2005):</p> <pre><code> [ object, uuid(B60C546F-EE91-48a2-A352-CFC36E613CB7), dual, nonextensible, helpstring("IScriptGenerator Interface"), pointer_default(unique) ] interface IScriptGenerator : IDispatch{ [helpstring("Init the Script generator")] HRESULT Init(); [helpstring("General purpose error reporting")] HRESULT GetLastError([out] BSTR *Error); }; </code></pre> <p>This is the stub created for C# by Tlbimp:</p> <pre><code>[TypeLibType(4288)] [Guid("B60C546F-EE91-48A2-A352-CFC36E613CB7")] public interface IScriptGenerator { [DispId(1610743813)] void GetLastError(out string Error); [DispId(1610743808)] void Init(); } </code></pre> <p>This is part of the main C# code, creating a COM object by its ProgID and casting it to the IScriptGenerator interface:</p> <pre><code>public ScriptGenerator(string GUID) { Type comType = Type.GetTypeFromProgID(GUID); object comObj = null; if (comType != null) { try { comObj = Activator.CreateInstance(comType); } catch (Exception ex) { Debug.Fail("Cannot create the script generator COM object due to the following exception: " + ex, ex.Message + "\n" + ex.StackTrace); throw ex; } } else throw new ArgumentException("The GUID does not match a registetred COM object", "GUID"); m_internalGenerator = comObj as IScriptGenerator; if (m_internalGenerator == null) { Debug.Fail("The script generator doesn't support the required interface - IScriptGenerator"); throw new InvalidCastException("The script generator with the GUID " + GUID + " doesn't support the required interface - IScriptGenerator"); } } </code></pre> <p>And this is the implementing C# code, to test it's working (and it's not):</p> <pre><code> [Guid("EB46E31F-0961-4179-8A56-3895DDF2884E"), ProgId("ScriptGeneratorExample.ScriptGenerator"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(SOAAPIOLELib.IScriptGeneratorCallback))] public class ScriptGenerator : IScriptGenerator { public void GetLastError(out string Error) { throw new NotImplementedException(); } public void Init() { // nothing to do } } </code></pre>
[ { "answer_id": 282325, "author": "Juan Zamudio", "author_id": 15058, "author_profile": "https://Stackoverflow.com/users/15058", "pm_score": 0, "selected": false, "text": "[InterfaceType(ComInterfaceType.InterfaceIsDual)]\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36694/" ]
282,018
<p>I'm doing some maintenance on a private svn server. Authentication is handled through Apache basic HTTP+mod_authz_svn. I need to have it so every user has read/write access, except for a single read-only user. The read-only user still needs to be authenticated, though. I setup my authz config file like this:</p> <pre>[/] * = rw read-only = r</pre> <p>But this doesn't work. The user "read-only" can still commit changes. I can make things read-only for everyone, but the * bit seems to override what I'm trying to set for "read-only."</p> <p>FWIW, relevant piece of the Apache conf is:</p> <pre> &lt;Location /repos&gt; DAV svn SVNPath ... SVNIndexXSLT "/svnindex.xsl" AuthzSVNAccessFile ... AuthType Basic AuthName ... AuthUserFile ... Require valid-user &lt;/Location&gt; </pre>
[ { "answer_id": 282052, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 3, "selected": false, "text": "[groups]\nall-but-ro = harry, sally, ...\n\n[/]\n@all-but-ro = rw\nread-only = r\n [/]\nread-only = r\n* = rw\n" }, { "answer_id": 282074, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "AuthzSVNAccessFile \"<path-to-svn-acl-file>\"\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36683/" ]
282,019
<p>I would like to declare a record in Delphi that contains the same layout as it has in C.</p> <p>For those interested : This record is part of a union in the Windows OS's LDT_ENTRY record. (I need to use this record in Delphi because I'm working on an Xbox emulator in Delphi - see project Dxbx on sourceforge).</p> <p>Anyway, the record in question is defined as:</p> <pre><code> struct { DWORD BaseMid : 8; DWORD Type : 5; DWORD Dpl : 2; DWORD Pres : 1; DWORD LimitHi : 4; DWORD Sys : 1; DWORD Reserved_0 : 1; DWORD Default_Big : 1; DWORD Granularity : 1; DWORD BaseHi : 8; } Bits; </code></pre> <p>As far as I know, there are no bit-fields possible in Delphi. I did try this:</p> <pre><code> Bits = record BaseMid: Byte; // 8 bits _Type: 0..31; // 5 bits Dpl: 0..3; // 2 bits Pres: Boolean; // 1 bit LimitHi: 0..15; // 4 bits Sys: Boolean; // 1 bit Reserved_0: Boolean; // 1 bit Default_Big: Boolean; // 1 bit Granularity: Boolean; // 1 bit BaseHi: Byte; // 8 bits end; </code></pre> <p>But alas: it's size becomes 10 bytes, instead of the expected 4. I would like to know how I should declare the record, so that I get a record with the same layout, the same size, and the same members. Preferrably without loads of getter/setters.</p> <p>TIA.</p>
[ { "answer_id": 282275, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "type\n TBits = record\n private\n FBaseMid : Byte;\n FTypeDplPres : Byte;\n FLimitHiSysEa: Byte;\n FBaseHi : Byte;\n\n function GetType: Byte;\n procedure SetType(const AType: Byte);\n function GetDpl: Byte;\n procedure SetDbl(const ADpl: Byte);\n function GetBit1(const AIndex: Integer): Boolean;\n procedure SetBit1(const AIndex: Integer; const AValue: Boolean);\n function GetLimitHi: Byte;\n procedure SetLimitHi(const AValue: Byte);\n function GetBit2(const AIndex: Integer): Boolean;\n procedure SetBit2(const AIndex: Integer; const AValue: Boolean);\n\n public\n property BaseMid: Byte read FBaseMid write FBaseMid;\n property &Type: Byte read GetType write SetType; // 0..31\n property Dpl: Byte read GetDpl write SetDbl; // 0..3\n property Pres: Boolean index 128 read GetBit1 write SetBit1; \n property LimitHi: Byte read GetLimitHi write SetLimitHi; // 0..15\n\n property Sys: Boolean index 16 read GetBit2 write SetBit2; \n property Reserved0: Boolean index 32 read GetBit2 write SetBit2; \n property DefaultBig: Boolean index 64 read GetBit2 write SetBit2; \n property Granularity: Boolean index 128 read GetBit2 write SetBit2; \n property BaseHi: Byte read FBaseHi write FBaseHi;\n end;\n\n function TBits.GetType: Byte;\n begin\n Result := (FTypeDplPres shr 3) and $1F;\n end;\n\n procedure TBits.SetType(const AType: Byte);\n begin\n FTypeDplPres := (FTypeDplPres and $07) + ((AType and $1F) shr 3);\n end;\n\n function TBits.GetDpl: Byte;\n begin\n Result := (FTypeDplPres and $06) shr 1;\n end;\n\n procedure TBits.SetDbl(const ADpl: Byte);\n begin\n FTypeDblPres := (FTypeDblPres and $F9) + ((ADpl and $3) shl 1);\n end;\n\n function TBits.GetBit1(const AIndex: Integer): Boolean;\n begin\n Result := FTypeDplPres and AIndex = AIndex;\n end;\n\n procedure TBits.SetBit1(const AIndex: Integer; const AValue: Boolean);\n begin\n if AValue then\n FTypeDblPres := FTypeDblPres or AIndex\n else\n FTypeDblPres := FTypeDblPres and not AIndex;\n end;\n\n function TBits.GetLimitHi: Byte;\n begin\n Result := (FLimitHiSysEa shr 4) and $0F;\n end;\n\n procedure TBits.SetLimitHi(const AValue: Byte);\n begin\n FLimitHiSysEa := (FLimitHiSysEa and $0F) + ((AValue and $0F) shr 4);\n end;\n\n function TBits.GetBit2(const AIndex: Integer): Boolean;\n begin\n Result := FLimitHiSysEa and AIndex = AIndex;\n end;\n\n procedure TBits.SetBit2(const AIndex: Integer; const AValue: Boolean);\n begin\n if AValue then\n FLimitHiSysEa := FLimitHiSysEa or AIndex\n else\n FLimitHiSysEa := FLimitHiSysEa and not AIndex;\n end;\n" }, { "answer_id": 282385, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 6, "selected": true, "text": "RBits = record\npublic\n BaseMid: BYTE;\nprivate\n Flags: WORD;\n function GetBits(const aIndex: Integer): Integer;\n procedure SetBits(const aIndex: Integer; const aValue: Integer);\npublic\n BaseHi: BYTE;\n property _Type: Integer index $0005 read GetBits write SetBits; // 5 bits at offset 0\n property Dpl: Integer index $0502 read GetBits write SetBits; // 2 bits at offset 5\n property Pres: Integer index $0701 read GetBits write SetBits; // 1 bit at offset 7\n property LimitHi: Integer index $0804 read GetBits write SetBits; // 4 bits at offset 8\n property Sys: Integer index $0C01 read GetBits write SetBits; // 1 bit at offset 12\n property Reserved_0: Integer index $0D01 read GetBits write SetBits; // 1 bit at offset 13\n property Default_Big: Integer index $0E01 read GetBits write SetBits; // 1 bit at offset 14\n property Granularity: Integer index $0F01 read GetBits write SetBits; // 1 bit at offset 15\nend;\n (BitOffset shl 8) + NrBits {$OPTIMIZATION ON}\n{$OVERFLOWCHECKS OFF}\nfunction RBits.GetBits(const aIndex: Integer): Integer;\nvar\n Offset: Integer;\n NrBits: Integer;\n Mask: Integer;\nbegin\n NrBits := aIndex and $FF;\n Offset := aIndex shr 8;\n\n Mask := ((1 shl NrBits) - 1);\n\n Result := (Flags shr Offset) and Mask;\nend;\n\nprocedure RBits.SetBits(const aIndex: Integer; const aValue: Integer);\nvar\n Offset: Integer;\n NrBits: Integer;\n Mask: Integer;\nbegin\n NrBits := aIndex and $FF;\n Offset := aIndex shr 8;\n\n Mask := ((1 shl NrBits) - 1);\n Assert(aValue <= Mask);\n\n Flags := (Flags and (not (Mask shl Offset))) or (aValue shl Offset);\nend;\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12170/" ]
282,024
<p>So I'm generating a random number using Rnd and Randomize to set a seed that looks like this:</p> <pre><code>Randomize lSeed Response.Write Rnd </code></pre> <p>I'm noticing that it's returning the same result for two values in a row for lSeed (e.g. 123, 124) but then on say 125 it will return a new value but 126 will be the same as the on for 125. Why would this be?</p> <p>Edit:</p> <p>I have tried something like this</p> <pre><code>Randomize Randomize lSeed Response.write Rnd </code></pre> <p>And I get the same results I described above.</p>
[ { "answer_id": 282033, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 0, "selected": false, "text": "' For ASP, you can create a function like:\nPublic Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer\n Randomize()\n Return ((Rnd() * (high - low)) + low)\nEnd Function\n\n' For ASP.NET, you can create a function like:\nPrivate _rnd As System.Random()\nPublic Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer\n ' Purpose: Returns Random Integer between low and high, inclusive\n ' Note: _rnd variable must be defined outside of RandRange function\n If _rnd Is Nothing Then\n _rnd = New System.Random()\n End If\n Return _rnd.Next(low, high)\nEnd Function\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
282,035
<p>How does one lock the focus of a .net application to a specific control? For example, if I have a form with 5 text boxes, and I want them filled out in a specific order, how can I stop someone who is in box 1 from tabbing/clicking to box 2, or hitting OK or Cancel or anything else? Is there an easy way, or do I have to manually disable/enable each other control at the appropriate time? </p> <p>The trouble with the obvious solution (Reset Focus when Focus is Lost) is that MSDN says you can lock up your machine that way:</p> <p>(Source:<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx</a>)</p> <p>Caution:</p> <p>Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at <a href="http://msdn.microsoft.com/library" rel="nofollow noreferrer">http://msdn.microsoft.com/library</a>. </p>
[ { "answer_id": 282060, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "private void textBox1_Leave(object sender, EventArgs e)\n{\n if string.isNullOrEmpty(textBox1.Text)\n {\n textBox1.focus();\n }\n}\n private void textBox_Leave(object sender, EventArgs e)\n{\n TextBox textBox = sender as TextBox;\n if (string.isNullOrEmpty(textBox.Text)\n {\n textBox.focus();\n }\n}\n" }, { "answer_id": 283285, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 2, "selected": false, "text": "e.Cancel = true; void textBox1_Validating(object sender, CancelEventArgs e)\n {\n if (true) //Condition not met\n {\n e.Cancel = true;//Return focus to the current control\n }\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,061
<p>I have a bit of a problem. I wrote an API a long time ago for our production system, and it used Apache XML Beans. The schema was homogeneous (ie no imports, everything was from within the same schema), and everything worked just fine, even if the code for API handling was incredibly verbose. I've since written a far simpler and more elegant restful API using JAXB, with parts of the old one in mind, ie different schema, but some of the elements are identical. In the hopes of cleaning up and simplifying my binding code in the old API, I've replaced some of the parts by deleting them and importing the new schema and using those elements instead. However, whenever I try to parse documents that use the new mixture of schema, I get a validation error from XML Beans :</p> <pre><code>error: cvc-complex-type.2.4a: Expected element 'redundant-element@http://www.my.com/old/xmlns' instead of 'redundant-element@http://www.my.com/new/xmlns' here in element redundant-element-list@http://www.my.com/old/xmlns </code></pre> <p>Has anybody encountered this before ? Have any solutions or ideas ? I'd really appreciate it. Thank you kindly.</p>
[ { "answer_id": 282060, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "private void textBox1_Leave(object sender, EventArgs e)\n{\n if string.isNullOrEmpty(textBox1.Text)\n {\n textBox1.focus();\n }\n}\n private void textBox_Leave(object sender, EventArgs e)\n{\n TextBox textBox = sender as TextBox;\n if (string.isNullOrEmpty(textBox.Text)\n {\n textBox.focus();\n }\n}\n" }, { "answer_id": 283285, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 2, "selected": false, "text": "e.Cancel = true; void textBox1_Validating(object sender, CancelEventArgs e)\n {\n if (true) //Condition not met\n {\n e.Cancel = true;//Return focus to the current control\n }\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32232/" ]
282,062
<p>I have a class like this:</p> <pre><code>public class Stretcher : Panel { public static readonly DependencyProperty StretchAmountProp = DependencyProperty.RegisterAttached("StretchAmount", typeof(double), typeof(Stretcher), null); public static void SetStretchAmount(DependencyObject obj, double amount) { FrameworkElement elem = obj as FrameworkElement; elem.Width *= amount; obj.SetValue(StretchAmountProp, amount); } } </code></pre> <p>I can set the stretch amount property in XAML using the attribute syntax:</p> <pre><code>&lt;UserControl x:Class="ManagedAttachedProps.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:map="clr-namespace:ManagedAttachedProps" Width="400" Height="300"&gt; &lt;Rectangle Fill="Aqua" Width="100" Height="100" map:Stretch.StretchAmount="100" /&gt; &lt;/UserControl&gt; </code></pre> <p>and my rectangle is stretched, but I can't use property element syntax like this:</p> <pre><code>&lt;UserControl x:Class="ManagedAttachedProps.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:map="clr-namespace:ManagedAttachedProps" Width="400" Height="300"&gt; &lt;Rectangle Fill="Aqua" Width="100" Height="100"&gt; &lt;map:Stretcher.StretchAmount&gt;100&lt;/map:Stretcher.StretchAmount&gt; &lt;/Rectangle&gt; &lt;/UserControl&gt; </code></pre> <p>with the property element syntax my set block seems to be totally ignored (I can even put invalid double values in there), and the SetStretchAmount method is never called.</p> <p>I know it's possible to do something like this, because VisualStateManager does it. I've tried using types other than double and nothing seems to work.</p>
[ { "answer_id": 282410, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 3, "selected": true, "text": "public class Stretch\n{\n public double StretchAmount { get; set; }\n}\n public static readonly DependencyProperty StretchAmountProp = DependencyProperty.RegisterAttached(\"StretchAmount\", typeof(Stretch), typeof(Stretcher), null);\n\npublic static void SetStretchAmount(DependencyObject obj, Stretch amount) \n{ \n FrameworkElement elem = obj as FrameworkElement; \n elem.Width *= amount.StretchAmount; \n obj.SetValue(StretchAmountProp, amount); \n}\n" }, { "answer_id": 284264, "author": "Jacksonh", "author_id": 6803, "author_profile": "https://Stackoverflow.com/users/6803", "pm_score": 1, "selected": false, "text": "<Rectangle Fill=\"Aqua\" Width=\"100\" Height=\"100\" x:Name=\"the_rect\">\n <map:Stretcher.StretchAmount>\n <map:Stretch StretchAmount=\"100\" />\n </map:Stretcher.StretchAmount>\n</Rectangle>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6803/" ]
282,084
<p>Help!</p> <p>I have a PHP (PHP 5.2.5) script on HOST1 trying to connect to an MySql database HOST2. Both hosts are in Shared Host environments controlled through CPanel.</p> <p>HOST2 is set to allow remote database connections from HOST1.</p> <p>The PHP connect I'm using is:- $h2 = IPADDRESS; $dbu = DBUSER; $dbp = DBPASS;</p> <pre><code>$DBlink = mysql_connect($h2, $dbu, $dbp); </code></pre> <p>This always fails with:-</p> <pre><code>Access denied for user '&lt;dbusername&gt;'@'***SOMESTRING***' (using password: YES) </code></pre> <p>nb: <strong><em>SOMESTRING</em></strong> looks like it could be something to do with the shared host environment.</p> <p>Any ideas???</p> <p>BTW: I can make remote connections to HOST2 from my laptop using OpenOffice via ODBC, and SQLyog. The SQLyog and ODBC settings are exactly the same as the PHP script is trying to use.</p>
[ { "answer_id": 282136, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "mysql_connect() new mysqli()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27200/" ]
282,091
<p>I am instantiating a local COM server using CoCreateInstance. Sometimes the application providing the server takes a long time to start. When this happens, Windows pops a dialog box like this:</p> <p><strong>Server Busy</strong></p> <p>The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy program and correct the problem.</p> <p>[Switch To...] [Retry] [Cancel]</p> <p>I have found mention of a Visual Basic property on the Application object, OleRequestPendingTimeout, that can be used to control the time before this dialog comes up. I can't find any good documentation on this or an equivalent that is useful from C++. Can anyone point me in the right direction?</p>
[ { "answer_id": 282309, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 2, "selected": false, "text": "IMessageFilter CoRegisterMessageFilter" }, { "answer_id": 282442, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 4, "selected": true, "text": "// prevent the damned \"Server Busy\" dialog.\nAfxOleGetMessageFilter()->EnableBusyDialog(0);\nAfxOleGetMessageFilter()->EnableNotRespondingDialog(0); \n" }, { "answer_id": 1790155, "author": "Vasiliy Zverev", "author_id": 217812, "author_profile": "https://Stackoverflow.com/users/217812", "pm_score": 2, "selected": false, "text": "AfxOleGetMessageFilter()->SetMessagePendingDelay(nTimeout);\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36699/" ]
282,093
<p>I want my php script to create an output file in a folder based on the date. The way I'm doing this is that its supposed to get the foldername/filename from a text file outputted by another program which I am unable to edit.</p> <p>So the file its grabbing the data from looks like this:</p> <pre><code>data/newfolder/10302008/log_for_Today.txt | 24234234 </code></pre> <p>Only with multiple lines, I just need the script to go through it line by line, grab the folder/filename and create an empty file with that name in that location.</p> <p>The directories are all 777. Now I know how to create a new empty exe file in a folder but can't seem to figure out how to create the folder first then the exe inside of it, any ideas?</p>
[ { "answer_id": 282137, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 2, "selected": false, "text": "$directories = explode( '/', $path );\n $file = array_pop( $directories );\n$base = '/my/base/dir';\n\nforeach( $directories as $dir )\n{\n\n $path = sprintf( '%s/%s', $base, $dir )\n mkdir( $path ); \n chmod( $path, 777 );\n $base = $path;\n\n}\n\n// file_put_contents or something similar\nfile_put_contents( sprintf( '%s/%s', $base, $file ), $data );\n" }, { "answer_id": 282140, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 6, "selected": false, "text": "if(!file_exists(dirname($file)))\n mkdir(dirname($file), 0777, true);\n//do stuff with $file.\n" }, { "answer_id": 30337367, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$pathToFile = 'test1/test2/test3/test4/test.txt';\n$fileName = basename($pathToFile);\n$folders = explode('/', str_replace('/' . $fileName, '', $pathToFile));\n\n$currentFolder = '';\nforeach ($folders as $folder) {\n $currentFolder .= $folder . DIRECTORY_SEPARATOR;\n if (!file_exists($currentFolder)) {\n mkdir($currentFolder, 0755);\n }\n}\nfile_put_contents($pathToFile, 'test');\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,099
<p>What's the Hi/Lo algorithm?</p> <p>I've found this in the <a href="http://en.wikipedia.org/wiki/NHibernate" rel="noreferrer">NHibernate</a> documentation (it's one method to generate unique keys, section 5.1.4.2), but I haven't found a good explanation of how it works.</p> <p>I know that Nhibernate handles it, and I don't need to know the inside, but I'm just curious.</p>
[ { "answer_id": 18440926, "author": "Thomas W", "author_id": 768795, "author_profile": "https://Stackoverflow.com/users/768795", "pm_score": 5, "selected": false, "text": "create table KEY_ALLOC (\n SEQ varchar(32) not null,\n NEXT bigint not null,\n primary key (SEQ)\n);\n select NEXT from KEY_ALLOC where SEQ=?;\nupdate KEY_ALLOC set NEXT=(old value+200) where SEQ=? and NEXT=(old value);\n Linear_Chunk Hi_Lo\n100 65536\n101 65537\n102 65538\n.. server restart\n120 131072\n121 131073\n122 131073\n.. server restart\n140 196608\n" }, { "answer_id": 24368478, "author": "Vlad Mihalcea", "author_id": 1025118, "author_profile": "https://Stackoverflow.com/users/1025118", "pm_score": 5, "selected": false, "text": "hi/lo hi hi hi lo hi hi incrementSize lo [(hi -1) * incrementSize) + 1, (hi * incrementSize) + 1)\n [0, incrementSize)\n [(hi -1) * incrementSize) + 1)\n lo hi hi/lo pooled-lo" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36703/" ]
282,105
<p>I've used a Continuous Integration server in the past with great success, and hadn't had the need to ever perform a code freeze on the source control system. </p> <p>However, lately it seems that everywhere I look, most shops are using the concept of code freezes when preparing for a release, or even a new test version of their product. This idea runs even in my current project.</p> <p>When you check-in early and often, and use unit tests, integration tests, acceptance tests, etc., are code freezes still needed?</p>
[ { "answer_id": 282121, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "Development\n ||\n \\/\n QAT \n ||\n \\/\n UAT => Freeze until deploy date => Deploy => Merge and repeat\n \\ /\n \\- New Branch for future dev -------/\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
282,118
<p>Is it possible to create a toggle button in C# WinForms? I know that you can use a CheckBox control and set it's Appearance property to "Button", but it doesn't look right. I want it to appear sunken, not flat, when pressed. Any thoughts?</p>
[ { "answer_id": 3776945, "author": "Simon Sabin", "author_id": 281338, "author_profile": "https://Stackoverflow.com/users/281338", "pm_score": 7, "selected": false, "text": "CheckBox Button CheckBox checkBox = new System.Windows.Forms.CheckBox(); \ncheckBox.Appearance = System.Windows.Forms.Appearance.Button; \n" }, { "answer_id": 8457321, "author": "legendJSLC", "author_id": 816077, "author_profile": "https://Stackoverflow.com/users/816077", "pm_score": 3, "selected": false, "text": "tbtnCross.CheckOnClick = true;\n tbtnCross.CheckOnClick = false;\n tbtnCross.Click += new EventHandler(tbtnCross_Click);\n .....\n\n void tbtnCross_Click(object sender, EventArgs e)\n {\n ToolStripButton target = sender as ToolStripButton;\n target.Checked = !target.Checked;\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n arrToolView[0] = tbtnCross;\n arrToolView[1] = tbtnLongtitude;\n arrToolView[2] = tbtnTerrain;\n arrToolView[3] = tbtnResult;\n for (int i = 0; i<arrToolView.Length; i++)\n {\n arrToolView[i].CheckOnClick = false;\n arrToolView[i].Click += new EventHandler(tbtnView_Click);\n }\n InitTree();\n }\n\n void tbtnView_Click(object sender, EventArgs e)\n {\n ToolStripButton target = sender as ToolStripButton;\n if (target.Checked) return;\n foreach (ToolStripButton btn in arrToolView)\n {\n btn.Checked = false;\n //btn.CheckState = CheckState.Unchecked;\n }\n target.Checked = true;\n target.CheckState = CheckState.Checked;\n\n }\n" }, { "answer_id": 20786599, "author": "CoffeeLab", "author_id": 3137001, "author_profile": "https://Stackoverflow.com/users/3137001", "pm_score": -1, "selected": false, "text": "private void settingsBtn_Click(object sender, EventArgs e)\n {\n count++;\n\n if (count % 2 == 0)\n {\n settingsPanel.Show();\n }\n else\n {\n settingsPanel.Hide();\n }\n }\n" }, { "answer_id": 32140822, "author": "ValarmorghulisHQ", "author_id": 3013866, "author_profile": "https://Stackoverflow.com/users/3013866", "pm_score": 3, "selected": false, "text": "var cbtnToggler = new CheckBox();\ncbtnToggler.Appearance = Appearance.Button;\ncbtnToggler.TextAlign = ContentAlignment.MiddleCenter;\ncbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!\n" }, { "answer_id": 42525978, "author": "H2Five", "author_id": 6807434, "author_profile": "https://Stackoverflow.com/users/6807434", "pm_score": 0, "selected": false, "text": "private void Protection_ON_OFF_Button_Click(object sender, EventArgs e)\n {\n\n if (FolderAddButton.Enabled == true)\n {\n FolderAddButton.Enabled = false;\n }\n else\n {\n FolderAddButton.Enabled = true;\n }\n }\n" }, { "answer_id": 45257748, "author": "Anthony", "author_id": 7927457, "author_profile": "https://Stackoverflow.com/users/7927457", "pm_score": 3, "selected": false, "text": "private void button2_Click(object sender, EventArgs e)\n {\n if (button2.Text == \"ON\")\n {\n panel_light.BackColor = Color.Yellow; //symbolizes light turned on\n\n button2.Text = \"OFF\";\n }\n\n else if (button2.Text == \"OFF\")\n {\n panel_light.BackColor = Color.Black; //symbolizes light turned off\n\n button2.Text = \"ON\";\n }\n }\n" }, { "answer_id": 61562077, "author": "Girl Spider", "author_id": 5481566, "author_profile": "https://Stackoverflow.com/users/5481566", "pm_score": 2, "selected": false, "text": " private void checkbox_paint(object sender, PaintEventArgs e)\n {\n CheckBox myCheckbox = (CheckBox)sender;\n Rectangle borderRectangle = myCheckbox.ClientRectangle;\n if (myCheckbox.Checked)\n {\n ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,\n Border3DStyle.Sunken);\n }\n else\n {\n ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,\n Border3DStyle.Raised);\n }\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
282,127
<p>I've got three (relevant) models, specified like this:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :posts has_many :comments has_many :comments_received, :through =&gt; :posts, :source =&gt; :comments end class Post &lt; ActiveRecord::Base belongs_to :user has_many :comments end class Comment &lt; ActiveRecord::Base belongs_to :user belongs_to :post end </code></pre> <p>I'd like to be able to reference all the <code>comments_received</code> for a <code>user</code> with a route - let's say it's for batch approval of comments on all posts. <em>(note that you can also get <code>comments</code> made by the <code>user</code>, but users can't comment on their own posts, so the <code>comments</code> through a <code>post</code> are different and mutually exclusive)</em>. Logically, this should work with:</p> <pre><code>map.resources :users, :has_many =&gt; [:posts, :comments, :comments_received] </code></pre> <p>This should give me routes of</p> <pre><code>user_posts_path user_comments_path user_comments_received_path </code></pre> <p>The first two work, the last one doesn't. I've tried it without the <code>_</code> in <code>comments_received</code> to no avail. I'm looking to get a URL like</p> <pre><code>http://some_domain.com/users/123/comments_received </code></pre> <p>I've also tried nesting it, but maybe I'm doing that wrong. In that case, I'd think the map would be:</p> <pre><code>map.resources :users do |user| user.resources :comments user.resources :posts, :has_many =&gt; :comments end </code></pre> <p>and then the url might be:</p> <pre><code>http://some_domain.com/users/123/posts/comments </code></pre> <p>Maybe this is the right way to do it, but I have the syntax wrong?</p> <p>Am I thinking about this the wrong way? It seems reasonable to me that I should be able to get a page of all the <code>comments</code> added to all of a user's posts. </p> <p>Thanks for your help!</p>
[ { "answer_id": 282443, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 0, "selected": false, "text": "map.resources :users do |user|\n user.resources :awards\n user.resources :contest_entries do |contest_entry|\n contest_entry.resources :awards\n end\nend\n user_path, user_awards_path, user_contest_entry_path, and user_contest_entry_awards_path.\n" }, { "answer_id": 315886, "author": "Sebastian", "author_id": 29909, "author_profile": "https://Stackoverflow.com/users/29909", "pm_score": 0, "selected": false, "text": "def getusercomments\n@user = User.find(params[:id])\n@comments = @user.posts.comments\nend\n map.resources :users, :member => { :getusercomments => :get }\n http://some_domain.com/users/123/getusercomments\n" }, { "answer_id": 805948, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 2, "selected": false, "text": "map.resources :users do |user|\n user.resources :posts\n user.resources :comments\n user.resources :comments_received\nend\n 'rake routes' users GET /users {:action=>\"index\", :controller=>\"users\"}\n user_posts GET /users/:user_id/posts {:action=>\"index\", :controller=>\"posts\"}\n user_comments GET /users/:user_id/comments {:action=>\"index\", :controller=>\"comments\"}\nuser_comments_received_index GET /users/:user_id/comments_received {:action=>\"index\", :controller=>\"comments_received\"}\n map.resources :users do |user|\n user.resources :posts\n user.resources :comments, :collection => {:received => :get}\nend\n users GET /users {:action=>\"index\", :controller=>\"users\"}\n user_posts GET /users/:user_id/posts {:action=>\"index\", :controller=>\"posts\"}\n user_comments GET /users/:user_id/comments {:action=>\"index\", :controller=>\"comments\"} \nreceived_user_comments GET /users/:user_id/comments/received {:action=>\"received\", :controller=>\"comments\"}\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,129
<p>I know about using a -vsdoc.js file for <a href="http://en.wikipedia.org/wiki/IntelliSense" rel="nofollow noreferrer">IntelliSense</a>, and the one for jQuery is easy to find. What other JavaScript, Ajax, and DHTML libraries have them and where can I find those files? Also, is there a document which outlines the specifications for -vsdoc.js files?</p>
[ { "answer_id": 311874, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 5, "selected": true, "text": "<summary locid=\"descriptionID\">Description</summary>\n <param name=\"parameterName\"\n mayBeNull=\"true|false\" optional=\"true|false\"\n type=\"ParameterType\" parameterArray=\"true|false\"\n integer=\"true|false\" domElement=\"true|false\"\n elementType=\"ArrayElementType\" elementInteger=\"true|false\"\n elementDomElement=\"true|false\"\n elementMayBeNull=\"true|false\">Description</param>\n <returns\n type=\"ValueType\" integer=\"true|false\" domElement=\"true|false\"\n mayBeNull=\"true|false\" elementType=\"ArrayElementType\"\n elementInteger=\"true|false\" elementDomElement=\"true|false\"\n elementMayBeNull=\"true|false\">Description</returns>\n <value\n type=\"ValueType\" integer=\"true|false\" domElement=\"true|false\"\n mayBeNull=\"true|false\" elementType=\"ArrayElementType\"\n elementInteger=\"true|false\" elementDomElement=\"true|false\"\n elementMayBeNull=\"true|false\"\n locid=\"descriptionID\">Description</value>\n <field name=\"fieldName\" type=\"FieldType\"\n integer=\"true|false\" domElement=\"true|false\" mayBeNull=\"true|false\"\n elementType=\"ArrayElementType\" elementInteger=\"true|false\"\n elementDomElement=\"true|false\" elementMayBeNull=\"true|false\"\n locid=\"descriptionID\">Description</field>\n <reference path=\"path/to/the/script/reference.js\"\n assembly=\"Assembly.Name\" name=\"ScriptResourceName.js\"/>\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22777/" ]
282,132
<p>I'm probably going to be using Tomcat and the Apache Axis webapp plugin, but I'm curious as to any other potential lightweight solutions.</p> <p>The main goal of this is to connect to MySQL database for doing some demos.</p> <p>Thanks, Todd</p>
[ { "answer_id": 285897, "author": "dshaw", "author_id": 32595, "author_profile": "https://Stackoverflow.com/users/32595", "pm_score": 2, "selected": false, "text": "mvn jetty:run\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8531/" ]
282,139
<p>I'm creating a batch file to make multiple directories from a list in a text file however after the directory is listed sometimes a filename is as well. Is there an easy way to have it ignore all data after the last \ on a line?</p>
[ { "answer_id": 285897, "author": "dshaw", "author_id": 32595, "author_profile": "https://Stackoverflow.com/users/32595", "pm_score": 2, "selected": false, "text": "mvn jetty:run\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,146
<p>I have been given the task of modifying a VB6 project. Nothing incredibly serious, adding a couple forms and fixing a few bugs for the most part. The project uses SQL Server (if that is of any relevance).</p> <p>My background in programming has been VB/C# .NET, PHP, C++ and mostly MySQL although I have used SQL Server on a much smaller scale. What kind of advice can anyone give me or resources for VB6 programming. It's been a few years since I've done any VB .NET work and while I can read the VB6 code and understand what is going on, I'm not sure how well I'm going to be able to start writing and/or modifying without a chance of breaking anything. </p> <p>What kind of advice can others offer? Any resources and/or stories would be great. Feel free to contribute things you may feel relevant yet I neglected to mention.</p> <p>Thanks!</p>
[ { "answer_id": 282205, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "On Error Resume Next" }, { "answer_id": 282250, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 2, "selected": false, "text": "on error resume next on error goto X ...\nOn Error Resume Next\noDbConn.Open sDbConnString\nSelect Case Err.Number\n Case &H80004005\n MsgBox \"Cannot connect to SQL-server, check your settings.\"\n frmSettings.Show\n Exit Sub\n Case Else\n ShowErrorAndQuit Err\nEnd Select\nOn Error Goto 0\n...\n" }, { "answer_id": 282333, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "On Error goto ErrorHandler UBound LBound" }, { "answer_id": 282362, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 0, "selected": false, "text": "On Error Resume Next Private Function MyFunc() As Boolean\n On Error Goto ErrHandler\n\n ''some code here\n If SomeBadExitConditionIsSet Then\n GoTo FuncExit\n End If\n\n ''some more code here\n MyFunc = True\n\nFuncExit:\n ''kill error handling to avoid error cycling\n On Error Resume Next\n ''cleanup code here - you need to check Err.Number after critical operations!\n ''single exit point\n Exit Function\n\nErrHandler:\n ''you can insert local specific error processing here, do not forget save Err.Number etc\n ''there is possibility to raise errors to caller function, \n ''but in this function we do not do that\n Select Case MyGlobalErrHandler(Err.Number, Err.Description)\n Case eRetry\n Resume ''this is useful while debugging - good place to \"Set Next Statement\"\n Case eIgnore\n Resume Next\n Case eCancel\n Resume FuncExit\n Case Else\n Resume FuncExit\n Select End\nEnd Function\n" }, { "answer_id": 283929, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 3, "selected": false, "text": "Public Property Get NewEnum() As IUnknown\n Set NewEnum = mCol.[_NewEnum]\nEnd Property\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444511/" ]
282,150
<p>I've read everywhere about how great they are, but for some reason I can't seem to figure out how exactly I'm supposed to test something. Could someone perhaps post a piece of example code and how they would test it? If it's not too much trouble :)</p>
[ { "answer_id": 282709, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 5, "selected": false, "text": "<?php\nfunction foo($bar)\n{\n return $bar;\n}\n?>\n --TEST--\nfoo() function - A basic test to see if it works. :)\n--FILE--\n<?php\ninclude 'lib.php'; // might need to adjust path if not in the same dir\n$bar = 'Hello World';\nvar_dump(foo($bar));\n?>\n--EXPECT--\nstring(11) \"Hello World\"\n $bar \"Hello World\" var_dump() foo() pear run-test path/to/foo.phpt" }, { "answer_id": 292305, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 4, "selected": false, "text": "/**\n * Provides Assertions\n **/\nclass Assert\n{\n public static function AreEqual( $a, $b )\n {\n if ( $a != $b )\n {\n throw new Exception( 'Subjects are not equal.' );\n }\n }\n}\n\n/**\n * Provides a loggable entity with information on a test and how it executed\n **/\nclass TestResult\n{\n protected $_testableInstance = null;\n\n protected $_isSuccess = false;\n public function getSuccess()\n {\n return $this->_isSuccess;\n }\n\n protected $_output = '';\n public function getOutput()\n {\n return $_output;\n }\n public function setOutput( $value )\n {\n $_output = $value;\n }\n\n protected $_test = null;\n public function getTest()\n {\n return $this->_test;\n }\n\n public function getName()\n {\n return $this->_test->getName();\n }\n public function getComment()\n {\n return $this->ParseComment( $this->_test->getDocComment() );\n }\n\n private function ParseComment( $comment )\n {\n $lines = explode( \"\\n\", $comment );\n for( $i = 0; $i < count( $lines ); $i ++ )\n {\n $lines[$i] = trim( $lines[ $i ] );\n }\n return implode( \"\\n\", $lines );\n }\n\n protected $_exception = null;\n public function getException()\n {\n return $this->_exception;\n }\n\n static public function CreateFailure( Testable $object, ReflectionMethod $test, Exception $exception )\n {\n $result = new self();\n $result->_isSuccess = false;\n $result->testableInstance = $object;\n $result->_test = $test;\n $result->_exception = $exception;\n\n return $result;\n }\n static public function CreateSuccess( Testable $object, ReflectionMethod $test )\n {\n $result = new self();\n $result->_isSuccess = true;\n $result->testableInstance = $object;\n $result->_test = $test;\n\n return $result;\n }\n}\n\n/**\n * Provides a base class to derive tests from\n **/\nabstract class Testable\n{\n protected $test_log = array();\n\n /**\n * Logs the result of a test. keeps track of results for later inspection, Overridable to log elsewhere.\n **/\n protected function Log( TestResult $result )\n {\n $this->test_log[] = $result;\n\n printf( \"Test: %s was a %s %s\\n\"\n ,$result->getName()\n ,$result->getSuccess() ? 'success' : 'failure'\n ,$result->getSuccess() ? '' : sprintf( \"\\n%s (lines:%d-%d; file:%s)\"\n ,$result->getComment()\n ,$result->getTest()->getStartLine()\n ,$result->getTest()->getEndLine()\n ,$result->getTest()->getFileName()\n )\n );\n\n }\n final public function RunTests()\n {\n $class = new ReflectionClass( $this );\n foreach( $class->GetMethods() as $method )\n {\n $methodname = $method->getName();\n if ( strlen( $methodname ) > 4 && substr( $methodname, 0, 4 ) == 'Test' )\n {\n ob_start();\n try\n {\n $this->$methodname();\n $result = TestResult::CreateSuccess( $this, $method );\n }\n catch( Exception $ex )\n {\n $result = TestResult::CreateFailure( $this, $method, $ex );\n }\n $output = ob_get_clean();\n $result->setOutput( $output );\n $this->Log( $result );\n }\n }\n }\n}\n\n/**\n * a simple Test suite with two tests\n **/\nclass MyTest extends Testable\n{\n /**\n * This test is designed to fail\n **/\n public function TestOne()\n {\n Assert::AreEqual( 1, 2 );\n }\n\n /**\n * This test is designed to succeed\n **/\n public function TestTwo()\n {\n Assert::AreEqual( 1, 1 );\n }\n}\n\n// this is how to use it.\n$test = new MyTest();\n$test->RunTests();\n" }, { "answer_id": 576283, "author": "scc", "author_id": 46183, "author_profile": "https://Stackoverflow.com/users/46183", "pm_score": 3, "selected": false, "text": "/**\n* Sums 2 numbers\n* <code>\n* //doctest: add\n* echo add(5,2);\n* //expects:\n* 7\n* </code>\n*/\nfunction add($a,$b){\n return $a + $b; \n}\n" }, { "answer_id": 603387, "author": "PartialOrder", "author_id": 49529, "author_profile": "https://Stackoverflow.com/users/49529", "pm_score": 3, "selected": false, "text": "require_once 'ClassYouWantToTest';\nrequire_once 'PHPUnit...blah,blah,whatever';\n\nclass ClassYouWantToTest extends PHPUnit...blah,blah,whatever\n{\n private $ClassYouWantToTest;\n\n protected function setUp ()\n {\n parent::setUp();\n $this->ClassYouWantToTest = new ClassYouWantToTest(/* parameters */);\n }\n\n protected function tearDown ()\n {\n $this->ClassYouWantToTest = null;\n parent::tearDown();\n }\n\n public function __construct ()\n { \n // not really needed\n }\n\n /**\n * Tests ClassYouWantToTest->methodFoo()\n */\n public function testMethodFoo ()\n {\n $this->assertEquals(\n $this->ClassYouWantToTest->methodFoo('putValueOfParamHere), 'expectedOutputHere);\n\n /**\n * Tests ClassYouWantToTest->methodBar()\n */\n public function testMethodFoo ()\n {\n $this->assertEquals(\n $this->ClassYouWantToTest->methodBar('putValueOfParamHere), 'expectedOutputHere);\n}\n" }, { "answer_id": 11198096, "author": "Davert", "author_id": 1168291, "author_profile": "https://Stackoverflow.com/users/1168291", "pm_score": 2, "selected": false, "text": "<?php\nuse Codeception\\Util\\Stub as Stub;\n\nconst VALID_USER_ID = 1;\nconst INVALID_USER_ID = 0;\n\nclass UserControllerCest {\npublic $class = 'UserController';\n\n\npublic function show(CodeGuy $I) {\n // prepare environment\n $I->haveFakeClass($controller = Stub::makeEmptyExcept($this->class, 'show'));\n $I->haveFakeClass($db = Stub::make('DbConnector', array('find' => function($id) { return $id == VALID_USER_ID ? new User() : null ))); };\n $I->setProperty($controller, 'db', $db);\n\n $I->executeTestedMethodOn($controller, VALID_USER_ID)\n ->seeResultEquals(true)\n ->seeMethodInvoked($controller, 'render');\n\n $I->expect('it will render 404 page for non existent user')\n ->executeTestedMethodOn($controller, INVALID_USER_ID)\n ->seeResultNotEquals(true)\n ->seeMethodInvoked($controller, 'render404','User not found')\n ->seeMethodNotInvoked($controller, 'render');\n}\n}\n" }, { "answer_id": 20313713, "author": "Vivendi", "author_id": 1175327, "author_profile": "https://Stackoverflow.com/users/1175327", "pm_score": 1, "selected": false, "text": "$this->Assert($datetime)->Should()->BeAfter($someDatetime);\n $mock = new CFMock::Create(new DummyClass());\n$mock->ACallTo('SomeMethod')->Returns('some value');\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36712/" ]
282,157
<p>Assuming one has an abstract base class <code>foo</code> with <code>__get()</code> defined, and a child class <code>bar</code> which inherits from <code>foo</code> with a private variable <code>$var</code>, will the parent <code>__get()</code> be called when trying to access the private <code>$var</code> from outside the class? </p>
[ { "answer_id": 282167, "author": "Electronic Zebra", "author_id": 1742702, "author_profile": "https://Stackoverflow.com/users/1742702", "pm_score": 4, "selected": true, "text": "<?php\n abstract class foo\n {\n public function __get($var)\n {\n echo \"Parent (Foo) __get() called for $var\\n\";\n }\n }\n\n class bar extends foo\n {\n private $var;\n public function __construct()\n {\n $this->var = \"25\\n\";\n }\n\n public function getVar()\n {\n return $this->var;\n }\n }\n\n $obj = new bar();\n echo $obj->var;\n echo $obj->getVar();\n?>\n" }, { "answer_id": 282203, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "__get() __set() __call() $var __get()" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742702/" ]
282,161
<p>I just found out that by converting PNG32 to PNG8 via Photoshop will fix the PNG transparency bug in IE&lt;=6. </p> <p>So I had this thought that instead of serving PNG32 to all browser, why not serve PNG8 if the client is using IE&lt;=6. </p> <p>I'm not really an expert when it comes to htaccess/httpd directives so I'm here for help. </p> <p>The title is the psuedocode itself.</p>
[ { "answer_id": 282174, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 0, "selected": false, "text": "RewriteEngine on\nRewriteRule ^/(.*)\\.png$ /$18.png [L,QSA]\n" }, { "answer_id": 282219, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": true, "text": "RewriteEngine on\nRewriteCond %{HTTP_USER_AGENT} ^Mozilla/4.0\\ \\(compatible;\\ MSIE\\ [1-6]\\.\nRewriteCond %{REQUEST_FILENAME} ^(.+)(\\.png)$\nRewriteCond %18%2 -f\nRewriteRule ^(.+)\\.png$ $18.png [L,QSA]\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300/" ]
282,171
<p>How do I write the CC logo in HTML, is there something like <code>&amp;copy;</code> (which gives &copy;)?</p> <p>(CC stands for Creative Commons).</p>
[ { "answer_id": 282413, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 1, "selected": false, "text": "&#nnnn; &#xhhhh;" }, { "answer_id": 5215916, "author": "Ori", "author_id": 582542, "author_profile": "https://Stackoverflow.com/users/582542", "pm_score": 3, "selected": false, "text": "@font-face <!DOCTYPE html> \n<html> \n <head> \n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"> \n <title>Test</title> \n <style type=\"text/css\">\n @media screen {\n @font-face {\n font-family: 'CC-ICONS';\n font-style: normal;\n font-weight: normal;\n src: url('http://mirrors.creativecommons.org/presskit/cc-icons.ttf') format('truetype');\n }\n\n span.cc {\n font-family: 'CC-ICONS';\n color: #ABB3AC;\n }\n }\n </style>\n </head> \n <body> \n <p>Key: a: SA, b: BY, c: CC Circle, d: ND, n: NC, m: Sampling, s: Share, r: Remix, C: CC Full Logo</p>\n <span class=\"cc\">a b c d n m s r C</span>\n <p>This page is licensed under <span class=\"cc\">C</span></p>\n </body> \n</html> \n" }, { "answer_id": 15455897, "author": "Anonimo", "author_id": 2178220, "author_profile": "https://Stackoverflow.com/users/2178220", "pm_score": 2, "selected": false, "text": "&copy; <p></p> <p class=\"copy-left\">&copy;</p>\n .copy-left {\n display: inline-block;\n text-align: right;\n margin: 0px;\n -moz-transform: scaleX(-1);\n -o-transform: scaleX(-1);\n -webkit-transform: scaleX(-1);\n transform: scaleX(-1);\n filter: FlipH;\n -ms-filter: \"FlipH\";\n}\n" }, { "answer_id": 34548834, "author": "Nikki Pantony", "author_id": 3482419, "author_profile": "https://Stackoverflow.com/users/3482419", "pm_score": 2, "selected": false, "text": "<link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\" rel=\"stylesheet\" integrity=\"sha256-3dkvEK0WLHRJ7/Csr0BZjAWxERc5WH7bdeUya2aXxdU= sha512-+L4yy6FRcDGbXJ9mPG8MT/3UCDzwR9gPeyFNMCtInsol++5m3bk2bXWKdZjvybmohrAsn3Ua5x8gfLnbE1YkOg==\" crossorigin=\"anonymous\">\n <i class=\"fa fa-creative-commons\"></i>\n" }, { "answer_id": 38161109, "author": "Luxii", "author_id": 4023495, "author_profile": "https://Stackoverflow.com/users/4023495", "pm_score": 0, "selected": false, "text": "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>." }, { "answer_id": 48062092, "author": "AlchadPlays", "author_id": 8852086, "author_profile": "https://Stackoverflow.com/users/8852086", "pm_score": 0, "selected": false, "text": "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css class=\"fa fa-creative-commons\"" }, { "answer_id": 53719893, "author": "JFS", "author_id": 8719957, "author_profile": "https://Stackoverflow.com/users/8719957", "pm_score": 2, "selected": false, "text": ".creative-commons{\n font-family:Arial;\n border: 1px solid black;\n box-sizing: border-box;\n border-radius: 1em;\n width: 2em;\n height: 2em;\n display: inline-block;\n line-height: 2em;\n text-align: center;\n font-size: 1em;\n } <span class=\"creative-commons\">CC</span>" }, { "answer_id": 61313326, "author": "Daniel", "author_id": 656132, "author_profile": "https://Stackoverflow.com/users/656132", "pm_score": 3, "selected": false, "text": "&#x1f16d;" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34109/" ]
282,176
<p>Imagine I have a process that starts several child processes. The parent needs to know when a child exits.</p> <p>I can use <code>waitpid</code>, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in <code>waitpid</code> to exit gracefully and join it. It's nice to have things clean up themselves, but it may not be that big of a deal.</p> <p>I can use <code>waitpid</code> with <code>WNOHANG</code>, and then sleep for some arbitrary time to prevent a busy wait. However then I can only know if a child has exited every so often. In my case it may not be super critical that I know when a child exits right away, but I'd like to know ASAP...</p> <p>I can use a signal handler for <code>SIGCHLD</code>, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit.</p> <p>What I'd really like to do is use <code>waitpid</code> on some timeout, say 5 sec. Since exiting the process isn't a time critical operation, I can lazily signal the thread to exit, while still having it blocked in <code>waitpid</code> the rest of the time, always ready to react. <em>Is there such a call in linux? Of the alternatives, which one is best?</em></p> <hr> <p>EDIT:</p> <p>Another method based on the replies would be to block <code>SIGCHLD</code> in all threads with <code>pthread</code> \ <code>_sigmask()</code>. Then in one thread, keep calling <code>sigtimedwait()</code> while looking for <code>SIGCHLD</code>. This means that I can time out on that call and check whether the thread should exit, and if not, remain blocked waiting for the signal. Once a <code>SIGCHLD</code> is delivered to this thread, we can react to it immediately, and in line of the wait thread, without using a signal handler.</p>
[ { "answer_id": 290025, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 5, "selected": false, "text": "alarm() wait() select() int selfpipe[2];\nvoid selfpipe_sigh(int n)\n{\n int save_errno = errno;\n (void)write(selfpipe[1], \"\",1);\n errno = save_errno;\n}\nvoid selfpipe_setup(void)\n{\n static struct sigaction act;\n if (pipe(selfpipe) == -1) { abort(); }\n\n fcntl(selfpipe[0],F_SETFL,fcntl(selfpipe[0],F_GETFL)|O_NONBLOCK);\n fcntl(selfpipe[1],F_SETFL,fcntl(selfpipe[1],F_GETFL)|O_NONBLOCK);\n memset(&act, 0, sizeof(act));\n act.sa_handler = selfpipe_sigh;\n sigaction(SIGCHLD, &act, NULL);\n}\n int selfpipe_waitpid(void)\n{\n static char dummy[4096];\n fd_set rfds;\n struct timeval tv;\n int died = 0, st;\n\n tv.tv_sec = 5;\n tv.tv_usec = 0;\n FD_ZERO(&rfds);\n FD_SET(selfpipe[0], &rfds);\n if (select(selfpipe[0]+1, &rfds, NULL, NULL, &tv) > 0) {\n while (read(selfpipe[0],dummy,sizeof(dummy)) > 0);\n while (waitpid(-1, &st, WNOHANG) != -1) died++;\n }\n return died;\n}\n selfpipe_waitpid() select()" }, { "answer_id": 7824046, "author": "ony", "author_id": 230744, "author_profile": "https://Stackoverflow.com/users/230744", "pm_score": 2, "selected": false, "text": "select EINTR SIGCHLD while(1)\n{\n int retval = select(0, NULL, NULL, NULL, &tv, &mask);\n if (retval == -1 && errno == EINTR) // some signal\n { \n pid_t pid = (waitpid(-1, &st, WNOHANG) == 0);\n if (pid != 0) // some child signaled\n }\n else if (retval == 0)\n {\n // timeout\n break;\n }\n else // error\n}\n pselect sigmask" }, { "answer_id": 8020324, "author": "mpartel", "author_id": 965979, "author_profile": "https://Stackoverflow.com/users/965979", "pm_score": 5, "selected": false, "text": "pid_t intermediate_pid = fork();\nif (intermediate_pid == 0) {\n pid_t worker_pid = fork();\n if (worker_pid == 0) {\n do_work();\n _exit(0);\n }\n\n pid_t timeout_pid = fork();\n if (timeout_pid == 0) {\n sleep(timeout_time);\n _exit(0);\n }\n\n pid_t exited_pid = wait(NULL);\n if (exited_pid == worker_pid) {\n kill(timeout_pid, SIGKILL);\n } else {\n kill(worker_pid, SIGKILL); // Or something less violent if you prefer\n }\n wait(NULL); // Collect the other process\n _exit(0); // Or some more informative status\n}\nwaitpid(intermediate_pid, 0, 0);\n" }, { "answer_id": 16084797, "author": "Aktau", "author_id": 558819, "author_profile": "https://Stackoverflow.com/users/558819", "pm_score": 2, "selected": false, "text": "static void ctlWaitPidTimeout(pid_t child, useconds_t usec, int *timedOut) {\n int rc = -1;\n\n static pthread_mutex_t alarmMutex = PTHREAD_MUTEX_INITIALIZER;\n\n TRACE(\"ctlWaitPidTimeout: waiting on %lu\\n\", (unsigned long) child);\n\n /**\n * paranoid, in case this was called twice in a row by different\n * threads, which could quickly turn very messy.\n */\n pthread_mutex_lock(&alarmMutex);\n\n /* set the alarm handler */\n struct sigaction alarmSigaction;\n struct sigaction oldSigaction;\n\n sigemptyset(&alarmSigaction.sa_mask);\n alarmSigaction.sa_flags = 0;\n alarmSigaction.sa_handler = ctlAlarmSignalHandler;\n sigaction(SIGALRM, &alarmSigaction, &oldSigaction);\n\n /* set alarm, because no alarm is fired when the first argument is 0, 1 is used instead */\n ualarm((usec == 0) ? 1 : usec, 0);\n\n /* wait for the child we just killed */\n rc = waitpid(child, NULL, 0);\n\n /* if errno == EINTR, the alarm went off, set timedOut to true */\n *timedOut = (rc == -1 && errno == EINTR);\n\n /* in case we did not time out, unset the current alarm so it doesn't bother us later */\n ualarm(0, 0);\n\n /* restore old signal action */\n sigaction(SIGALRM, &oldSigaction, NULL);\n\n pthread_mutex_unlock(&alarmMutex);\n\n TRACE(\"ctlWaitPidTimeout: timeout wait done, rc = %d, error = '%s'\\n\", rc, (rc == -1) ? strerror(errno) : \"none\");\n}\n\nstatic void ctlAlarmSignalHandler(int s) {\n TRACE(\"ctlAlarmSignalHandler: alarm occured, %d\\n\", s);\n}\n" }, { "answer_id": 20173592, "author": "osexp2003", "author_id": 2293666, "author_profile": "https://Stackoverflow.com/users/2293666", "pm_score": 4, "selected": false, "text": "/* The program creates a child process and waits for it to finish. If a timeout\n * elapses the child is killed. Waiting is done using sigtimedwait(). Race\n * condition is avoided by blocking the SIGCHLD signal before fork().\n */\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <signal.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n\nstatic pid_t fork_child (void)\n{\n int p = fork ();\n\n if (p == -1) {\n perror (\"fork\");\n exit (1);\n }\n\n if (p == 0) {\n puts (\"child: sleeping...\");\n sleep (10);\n puts (\"child: exiting\");\n exit (0);\n }\n\n return p;\n}\n\nint main (int argc, char *argv[])\n{\n sigset_t mask;\n sigset_t orig_mask;\n struct timespec timeout;\n pid_t pid;\n\n sigemptyset (&mask);\n sigaddset (&mask, SIGCHLD);\n\n if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) {\n perror (\"sigprocmask\");\n return 1;\n }\n\n pid = fork_child ();\n\n timeout.tv_sec = 5;\n timeout.tv_nsec = 0;\n\n do {\n if (sigtimedwait(&mask, NULL, &timeout) < 0) {\n if (errno == EINTR) {\n /* Interrupted by a signal other than SIGCHLD. */\n continue;\n }\n else if (errno == EAGAIN) {\n printf (\"Timeout, killing child\\n\");\n kill (pid, SIGKILL);\n }\n else {\n perror (\"sigtimedwait\");\n return 1;\n }\n }\n\n break;\n } while (1);\n\n if (waitpid(pid, NULL, 0) < 0) {\n perror (\"waitpid\");\n return 1;\n }\n\n return 0;\n}\n" }, { "answer_id": 56805612, "author": "Pip", "author_id": 4098080, "author_profile": "https://Stackoverflow.com/users/4098080", "pm_score": 2, "selected": false, "text": "\nstatic bool waitpid_with_timeout(pid_t pid, int timeout_ms, int* status) {\n sigset_t child_mask, old_mask;\n sigemptyset(&child_mask);\n sigaddset(&child_mask, SIGCHLD);\n\n if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {\n printf(\"*** sigprocmask failed: %s\\n\", strerror(errno));\n return false;\n }\n\n timespec ts;\n ts.tv_sec = MSEC_TO_SEC(timeout_ms);\n ts.tv_nsec = (timeout_ms % 1000) * 1000000;\n int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));\n int saved_errno = errno;\n\n // Set the signals back the way they were.\n if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {\n printf(\"*** sigprocmask failed: %s\\n\", strerror(errno));\n if (ret == 0) {\n return false;\n }\n }\n if (ret == -1) {\n errno = saved_errno;\n if (errno == EAGAIN) {\n errno = ETIMEDOUT;\n } else {\n printf(\"*** sigtimedwait failed: %s\\n\", strerror(errno));\n }\n return false;\n }\n\n pid_t child_pid = waitpid(pid, status, WNOHANG);\n if (child_pid != pid) {\n if (child_pid != -1) {\n printf(\"*** Waiting for pid %d, got pid %d instead\\n\", pid, child_pid);\n } else {\n printf(\"*** waitpid failed: %s\\n\", strerror(errno));\n }\n return false;\n }\n return true;\n}\n" }, { "answer_id": 65003348, "author": "chys", "author_id": 498284, "author_profile": "https://Stackoverflow.com/users/498284", "pm_score": 3, "selected": false, "text": "pidfd_open select poll epoll int fd = pidfd_open(pid, 0);\nstruct pollfd pfd = {fd, POLLIN, 0};\npoll(&pfd, 1, 1000) == 1;\n" }, { "answer_id": 69081558, "author": "Arran Cudbard-Bell", "author_id": 2117998, "author_profile": "https://Stackoverflow.com/users/2117998", "pm_score": 0, "selected": false, "text": "kqueue EVFILT_PROC NOTE_EXIT kqueue libkqueue epoll *fd signalfd eventfd pidfd #include <stdio.h>\n#include <stdint.h>\n#include <sys/event.h> /* kqueue header */\n#include <sys/types.h> /* for pid_t */\n\n/* Link with -lkqueue */\n\nint waitpid_timeout(pid_t pid, struct timespec *timeout)\n{\n struct kevent changelist, eventlist;\n int kq, ret;\n\n /* Populate a changelist entry (an event we want to be notified of) */\n EV_SET(&changelist, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);\n\n kq = kqueue();\n\n /* Call kevent with a timeout */\n ret = kevent(kq, &changelist, 1, &eventlist, 1, timeout);\n\n /* Kevent returns 0 on timeout, the number of events that occurred, or -1 on error */\n switch (ret) {\n case -1:\n printf(\"Error %s\\n\", strerror(errno));\n break;\n\n case 0:\n printf(\"Timeout\\n\");\n break;\n\n case 1:\n printf(\"PID %u exited, status %u\\n\", (unsigned int)eventlist.ident, (unsigned int)eventlist.data);\n break;\n }\n close(kq);\n\n return ret;\n}\n libkqueue SIGCHLD kqueue waitid EVFILT_PROC kqueue libkqueue v2.5.0" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
282,178
<p>So I have a User model that :has_many other models like Documents, Videos, Posts and the like. My question arises when I execute a "do" block from the User model like so:</p> <pre><code>has_many :posts do def recent find(:all, :order =&gt; 'created_at desc', :limit =&gt; 12) end end </code></pre> <p>This just lets me call something like user.posts.recent to find only those posts associated with the User. With this in place, how can I still add a :dependent => :destroy or :dependent => :delete_all to this association? Everything I have tried so far has errored out on me.</p>
[ { "answer_id": 283020, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": -1, "selected": false, "text": "has_many :posts, :dependent => :destroy do\n def recent\n find(:all, :order => 'created_at desc', :limit => 12)\n end\n end\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36715/" ]
282,184
<p>Javascript usage has gotten remarkably more sophisticated and powerful in the past five years. One aspect of this sort of functional programming I struggle with, esp with Javascript’s peculiarities, is how to make clear either through comments or code just what is happening. Often this sort of code takes a while to decipher, even if you understand the prototypal, first-class functional Javascript way. Any thoughts or techniques for making perfectly clear what your code does and how in Javascript?</p> <p>I've asked this question elsewhere, but haven't gotten much response.</p>
[ { "answer_id": 282216, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "// comments are not included *on purpose* for illustrating \n// my point about the need for language knowledge\nfunction copy(obj) {\n return new (function(o) {\n for(var property in o) {\n if(o[property].constructor == Array) {\n this[property] = [];\n for(var i = 0; i < o[property].length; i++) {\n this[property][i] = new arguments.callee(o[property][i]);\n }\n } else if(o[property].constructor == Object) {\n this[property] = new arguments.callee(o[property]);\n } else {\n this[property] = o[property];\n }\n }\n })(obj);\n}\n this" }, { "answer_id": 282232, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 1, "selected": false, "text": "{key: {function}} <input>" }, { "answer_id": 7460111, "author": "c69", "author_id": 946789, "author_profile": "https://Stackoverflow.com/users/946789", "pm_score": 0, "selected": false, "text": "var module = ( function () { ... } )(); Module = function () { ... }; Module.prototype.method1 = function () { ... }; this function Car() { _car = this; _car.accelerate = function () { ... }; } function() { return { setTimeout addEventListener" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4440/" ]
282,191
<p>in my flex application, I created a Tilelist. In this Tilelist, I am using an ItemRenderer to create a box consisting of an image and an VSlider in each tile. </p> <p>The tile need to be dragable when you click on the image, but not dragable when you slide the slider. How can I achieve this ? I have been scratching my head searching on Google for one day and I have really no idea.</p> <p>I look forward to your help. Thank you.</p>
[ { "answer_id": 284779, "author": "Blizter", "author_id": 387920, "author_profile": "https://Stackoverflow.com/users/387920", "pm_score": 1, "selected": false, "text": " public var overImage:Boolean = false;\n\n public function checkAllow(evt:DragEvent):void {\n\n if(overImage == false)\n {\n evt.preventDefault()\n }\n }\n\n public function isOverImage():void {\n overImage = true;\n }\n\n public function isOutImage():void {\n overImage = false;\n }\n mouseOver=\"outerDocument.isOverImage()\" mouseOut=\"outerDocument.isOutImage()\"\n Tiles.addEventListener(DragEvent.DRAG_START, checkAllow);\n" }, { "answer_id": 11028482, "author": "Trinu", "author_id": 1257233, "author_profile": "https://Stackoverflow.com/users/1257233", "pm_score": 0, "selected": false, "text": " if(event.target is ScrollThumb )\n {\n return;\n }\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387920/" ]
282,192
<p>I'm trying to auto-generate a plain text email with a trademark symbol in it. I've tried everything I can think of but it's still not going through.</p> <pre><code>&lt;cfmail from="#x#" to="#y#" subject="test" charset="UTF-8"&gt; ™ &amp;trade; #Chr(153)# &lt;/cfmail&gt; </code></pre>
[ { "answer_id": 282381, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "Chr(153) Chr() Chr(8482)" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8724/" ]
282,194
<p>I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.</p>
[ { "answer_id": 282220, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 7, "selected": true, "text": "GetCurrentProcess() WorkingSetSize PROCESS_MEMORY_COUNTERS" }, { "answer_id": 8500024, "author": "Ronin", "author_id": 1091608, "author_profile": "https://Stackoverflow.com/users/1091608", "pm_score": 5, "selected": false, "text": "#include<windows.h>\n#include<stdio.h> \n#include<tchar.h>\n\n// Use to convert bytes to MB\n#define DIV 1048576\n\n// Use to convert bytes to MB\n//#define DIV 1024\n\n// Specify the width of the field in which to print the numbers. \n// The asterisk in the format specifier \"%*I64d\" takes an integer \n// argument and uses it to pad and right justify the number.\n\n#define WIDTH 7\n\nvoid _tmain()\n{\n MEMORYSTATUSEX statex;\n\n statex.dwLength = sizeof (statex);\n\n GlobalMemoryStatusEx (&statex);\n\n\n _tprintf (TEXT(\"There is %*ld percent of memory in use.\\n\"),WIDTH, statex.dwMemoryLoad);\n _tprintf (TEXT(\"There are %*I64d total Mbytes of physical memory.\\n\"),WIDTH,statex.ullTotalPhys/DIV);\n _tprintf (TEXT(\"There are %*I64d free Mbytes of physical memory.\\n\"),WIDTH, statex.ullAvailPhys/DIV);\n _tprintf (TEXT(\"There are %*I64d total Mbytes of paging file.\\n\"),WIDTH, statex.ullTotalPageFile/DIV);\n _tprintf (TEXT(\"There are %*I64d free Mbytes of paging file.\\n\"),WIDTH, statex.ullAvailPageFile/DIV);\n _tprintf (TEXT(\"There are %*I64d total Mbytes of virtual memory.\\n\"),WIDTH, statex.ullTotalVirtual/DIV);\n _tprintf (TEXT(\"There are %*I64d free Mbytes of virtual memory.\\n\"),WIDTH, statex.ullAvailVirtual/DIV);\n _tprintf (TEXT(\"There are %*I64d free Mbytes of extended memory.\\n\"),WIDTH, statex.ullAvailExtendedVirtual/DIV);\n\n\n}\n" }, { "answer_id": 48660816, "author": "Aris Koning", "author_id": 3412158, "author_profile": "https://Stackoverflow.com/users/3412158", "pm_score": 3, "selected": false, "text": "GlobalMemoryStatusEx ullAvailVirtual ullTotalVirtual GlobalMemoryStatusEx" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
282,198
<p>I want to select a bunch of <code>span</code>s in a <code>div</code> whose CSS contains a particular background color. How do I achieve this?</p>
[ { "answer_id": 282208, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": -1, "selected": false, "text": "#id_of_the_div span[background-color=rgb(255,255,255)]\n" }, { "answer_id": 282595, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 7, "selected": true, "text": "[attribute=value] <span> $('#someDiv span[background-color]').size(); // returns 0\n .one, .two {\n background-color: black;\n}\n\n.three {\n background-color: red;\n}\n $('div#someDiv span').filter(function() {\n var match = 'rgb(0, 0, 0)'; // match background-color: black\n /*\n true = keep this element in our wrapped set\n false = remove this element from our wrapped set\n */\n return ( $(this).css('background-color') == match );\n\n}).css('background-color', 'green'); // change background color of all black spans .one, .two {\n background-color: black;\n}\n\n.three {\n background-color: red;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js\"></script>\n\n<div id=\"someDiv\">\n <span class=\"one\">test one</span>\n <span class=\"two\">test two</span>\n <span class=\"three\">test three</span>\n</div>" }, { "answer_id": 65967339, "author": "Shashikant Yadav - Kantbtrue", "author_id": 6647673, "author_profile": "https://Stackoverflow.com/users/6647673", "pm_score": 2, "selected": false, "text": "// Get all spans\nlet spans = document.querySelectorAll('div#someDiv span'); \n\n// Convert spans nodeslist to array\nspans = Array.from( spans ); \n\n// Filter spans array\n// Get CSS properties object of selected element - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)\nlet arr = spans.filter( span => String( document.defaultView.getComputedStyle( span, null ).backgroundColor ) == 'rgb(0, 0, 0)' );\n\n// Change background color of matched span elements\narr.forEach( span => {\n span.style.backgroundColor = 'green';\n}); .one, .two {\n background-color: black;\n}\n\n.three {\n background-color: red;\n} <div id=\"someDiv\">\n <span class=\"one\">test one</span>\n <span class=\"two\">test two</span>\n <span class=\"three\">test three</span>\n</div>" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
282,222
<p>I just want ask the steps when trying to create a simple SQL select statement in UNIX inside/within IF..THEN..FI statement.</p> <p>I know how to use the 'select' and 'if..then' statements in SQL*Plus, but I'm having a difficulties having a UNIX script to point to variables: If 'ABC' to 'Select...'</p> <h2>Example:</h2> <p>if [ "$?" = 'ABC' ] then SELECT employid, name, age FROM tablename; else exit 1 fi</p> <p>if [ "$?" = 'XYZ' ] then SELECT employid, name, age FROM tablename; else exit 1 fi</p> <p>How do I put it in a UNIX script more correctly syntax wise and right to the point?</p> <p>Thanks.</p>
[ { "answer_id": 282253, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "if [ $? -eq ABC ]; then\nSQLPLUS /S USER/PASS@Instance <<EOF\nSET echo off;\nSET pagesize 0;\nSET heading off;\nSPOOL foo.out\nselect foo from bar\nEOF\nfi\n" }, { "answer_id": 282715, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "echo if [ \"$?\" = \"ABC\" ] then echo SELECT employid, name, age FROM tablename; else exit 1; fi\n" } ]
2008/11/11
[ "https://Stackoverflow.com/questions/282222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]