qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
162,534
<p>I just wanna ask what would be better approach to supply these objects in my unit tests.</p> <p>In my unit test I am testing CSLA object. CSLA object is internally using one property and one method of ApplicationUser object. ApplicationUser is inherited from IPrincipal. The properties are: 1) ApplicationContext.User.IsInRole(...) - the method is part of IPrincipal 2) ApplicationContext.User.Identity.Name - the name is property of IIdentity which is part of ApplicationUser aka IPricipal</p> <p>Example of my test (using RhinoMock):</p> <pre><code>public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock&lt;IPrincipal&gt;(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc } } </code></pre> <p>I have slight problem with second value, the identity name. I tried to mock it but have problem to assign mocked IIdentity to ApplicationUser, as it is done internaly. I was told to just create some IIPrincipal (including IIdentity) by myself and not to mock it at all. Which can be done for sure. Not sure if this can be called as Stub using?</p> <p>So can you advice me how to deal with IPrincipal and IIdentity? Any suggestion most welcome.</p>
[ { "answer_id": 162667, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 2, "selected": false, "text": " [SetUp]\n public void Setup()\n {\n var identity = MockRepository.GenerateStub<IIdentity>();\n identity.Stub(p => p.Name).Return(\"TestUser\").Repeat.Any();\n var principal = MockRepository.GenerateStub<IPrincipal>();\n principal.Stub(p => p.Identity).Return(identity).Repeat.Any();\n\n Thread.CurrentPrincipal = principal;\n }\n" }, { "answer_id": 1093800, "author": "Randolpho", "author_id": 12716, "author_profile": "https://Stackoverflow.com/users/12716", "pm_score": 4, "selected": true, "text": "IPrincipal.Identity IPrincipal .Name Identity IIdentity Name IPrincipal.Identity IIdentity public void BeforeTest()\n{\n mocks = new MockRepository();\n IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>();\n IIdentity mockIdentity = mocks.CreateMock<IIdentity>();\n ApplicationContext.User = mockPrincipal;\n using (mocks.Record()) \n {\n Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);\n Expect.Call(mockIdentity.Name).Return(\"ju\"); \n Expect.Call(mockPrincipal.Identity).Return(mockIdentity);\n }\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24507/" ]
162,537
<p>I just upgraded a VS 2005 project to VS 2008 and was examining the changes. I noticed one of the .Designer.cs files had changed significantly. The majority of the changes were simply replacements of <em>System</em> with <em>global::System</em>. For example,</p> <pre><code>protected override System.Data.DataTable CreateInstance() </code></pre> <p>became</p> <pre><code>protected override global::System.Data.DataTable CreateInstance() </code></pre> <p>What's going on here?</p>
[ { "answer_id": 162554, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": " global::System.Data.DataTable \n System.Data.DataTable\n class TestApp\n{\n // Define a new class called 'System' to cause problems.\n public class System { }\n\n // Define a constant called 'Console' to cause more problems.\n const int Console = 7;\n const int number = 66;\n\n static void Main()\n {\n // Error Accesses TestApp.Console\n //Console.WriteLine(number);\n }\n}\n global::System.Console.Writeline(\"This works\");\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
162,542
<p>How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.</p> <p>For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.</p> <p>Then I went into the routes.rb file and entered <code>map.resources :employees</code>, which gives you access to the URL helper functions.</p> <p>In whatever I want to call the Ajax operation from, I should just have a line like:</p> <pre><code>&lt;%= link_to_remote "Delete", employee_path(@employee), :method =&gt; :delete %&gt; </code></pre> <p>When I click on the link, it is still is sending a POST operation, so it does nothing.</p> <p>What am I missing or doing wrong?</p>
[ { "answer_id": 162590, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": true, "text": ":url => employee_url(@employee)\n" }, { "answer_id": 162612, "author": "flitzwald", "author_id": 11811, "author_profile": "https://Stackoverflow.com/users/11811", "pm_score": 2, "selected": false, "text": "<%= link_to_remote \"Delete\", :url => post_url(post), :method => :delete %>\n" }, { "answer_id": 169263, "author": "Chris R.", "author_id": 5923, "author_profile": "https://Stackoverflow.com/users/5923", "pm_score": 0, "selected": false, "text": ":url => employee_url(@employee)" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5923/" ]
162,564
<p>I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update. Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?</p>
[ { "answer_id": 162584, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "UPDATE table\nSET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol))\nWHERE id = @id\n UPDATE table\nSET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol)\nWHERE id = @id\n" }, { "answer_id": 162661, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 1, "selected": false, "text": "DECLARE @newMonth int\nSET @newMonth = 5 --As an example\n\nUPDATE dbo.TheTable\nSET DateField = DATEADD(month, @newMonth - DATEPART(month, DateField) , DateField)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
162,571
<p>I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?</p> <p>I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.</p>
[ { "answer_id": 162597, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "ResultSet.afterLast() ResultSet.getRow() ResultSet.beforeFirst()" }, { "answer_id": 162629, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 6, "selected": true, "text": "SELECT COUNT(1) FROM table_name\n" }, { "answer_id": 10139221, "author": "thezar", "author_id": 978036, "author_profile": "https://Stackoverflow.com/users/978036", "pm_score": 5, "selected": false, "text": "ResultSet rs = stmt.executeQuery(sql);\nint rowCount = rs.last() ? rs.getRow() : 0; // Number of rows in result set. Don't forget to set cyrsor to beforeFirst() row! :)\n" }, { "answer_id": 16268359, "author": "MindBrain", "author_id": 1118559, "author_profile": "https://Stackoverflow.com/users/1118559", "pm_score": 0, "selected": false, "text": "//Create a Statement class to execute the SQL statement\nStatement stmt = con.createStatement();\n\nResultSet rs = stmt.executeQuery(\"SELECT COUNT(*) AS COUNT FROM\nTABLENAME\");\n\n while(rs.next()) {\n System.out.println(\"The count is \" + rs.getInt(\"COUNT\"));\n }\n\n //Closing the connection\n con.close();\n" }, { "answer_id": 17718051, "author": "user2594537", "author_id": 2594537, "author_profile": "https://Stackoverflow.com/users/2594537", "pm_score": 4, "selected": false, "text": "ResultSet rs = st.executeQuery(\"select count(*) from TABLE_NAME\");\nrs.next();\nint count = rs.getInt(1);\n" }, { "answer_id": 51537403, "author": "v8-E", "author_id": 8064000, "author_profile": "https://Stackoverflow.com/users/8064000", "pm_score": 2, "selected": false, "text": "rs.last(); // Moves the cursor to the last row in this ResultSet object.\nint rowCount = rs.getRow(); //Retrieves the current row number.\nrs.beforeFirst(); //Moves the cursor to the front of this ResultSet object,just before the first row.\n int rowCount = rs.last() ? rs.getRow() : 0; \nrs.beforeFirst();\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
162,576
<p>I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: <strong>PHP doesn't play well with email!</strong></p> <p>I've connected to the POP3 server and I can iterate the files. Here's a rough outline of the code:</p> <pre><code>if (!$mbox = imap_open ("{myserver.com:110/pop3/notls}INBOX", "u", "p")) die ('Cannot connect/check mail! Exiting'); if ($hdr = imap_check($mbox)) $msgCount = $hdr-&gt;Nmsgs; else die ("Failed to get mail"); foreach ($overview as $message) { $msgStruct = imap_fetchstructure($mbox, $message-&gt;msgno); // if it has parts, there are attachments that need reading if ($msgStruct-&gt;parts) { foreach ($msgStruct-&gt;parts as $key =&gt; $part) { switch (strtoupper($part-&gt;subtype)) { case 'GIF': case 'JPEG':case 'PNG': //do something - but what?! break; } } } } </code></pre> <p>I've marked where I'm stuck. I can use <code>imap_fetchbody($mbox, $message-&gt;msgno, $key+1)</code> but that gets me a bunch of data like this:</p> <pre><code>/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8S EhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEU Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAAR CAHiAi0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl 5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA ... </code></pre> <p>I'm lead to believe that this is MIME data. I need it as an image! I've seen several classes bombing around the internet that claim to do the required wizardry. I can't get any of them to work. I don't understand why I'm finding this so hard!</p> <p><strong>In short</strong>, I'm looking for something that can turn a raw MIME string into real data.</p>
[ { "answer_id": 162611, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 3, "selected": true, "text": "echo if (substr($ContentType,0,4) == \"text\") {\necho imap_qprint($fileContent);\n} else {\necho imap_base64($fileContent);\n}\n if" }, { "answer_id": 162637, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 1, "selected": false, "text": "imap_base64 imap_savebody" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
162,591
<p>I have a subversion repository with the standard layout, i.e. trunk/ and branches/ (and tags/). When working on a bigger change, a feature branch is used, regularly synced with trunk, and later reintegrated back into trunk (using 1.5 now). Pretty standard stuff.</p> <p>What I am wondering is whether such a feature branch, once finished and merged should be kept around, or deleted. The subversion book occasionally seems to suggest that it is common to delete them, but I've also seen a bunch of Open Source projects which do keep the branches.</p> <p>I am also somewhat concerned about how deleting a branch will make it harder to keep track of which branches existed, especially when potentially duplicate names enter the scenario (say we search-refactor twice), their commit histories disappearing somewhere in the depth of the repository etc. </p> <p>On the other hand, branches are used quite a lot, especially with 1.5 now, and I do like the thought of not having to poke through a large list of inactive branches to find the ones I am currently working on.</p> <p>What are the pros and cons that I am missing? What are people doing?</p>
[ { "answer_id": 162623, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "-rrevision" }, { "answer_id": 162630, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 6, "selected": true, "text": "svn move" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15677/" ]
162,606
<p>I know of a couple of routines that work as follows: </p> <blockquote> <p>X<sub>n+1</sub> = Routine(X<sub>n</sub>, max) </p> </blockquote> <p>For example, something like a LCG generator: </p> <blockquote> <p>X<sub>n+1</sub> = (a*X<sub>n</sub> + c) mod m </p> </blockquote> <p>There isn't enough parameterization in this generator to generate every sequence. </p> <p>Dream Function: </p> <blockquote> <p>X<sub>n+1</sub> = Routine(X<sub>n</sub>, max, permutation number) </p> </blockquote> <p>This routine, parameterized by an index into the set of all permutations, would return the next number in the sequence. The sequence may be arbitrarily large (so storing the array and using factoradic numbers is impractical. </p> <p>Failing that, does anyone have pointers to similar functions that are either stateless or have a constant amount of state for arbitrary 'max', such that they will iterate a shuffled list. </p>
[ { "answer_id": 163312, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 1, "selected": false, "text": "X(n+1) = Routine(Xn, max, permutation number)\nfor(i = n; i > 0; i--)\n {\n int temp = Map.lookup(i) \n otherfun(temp,max,perm)\n }\n" }, { "answer_id": 166032, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 0, "selected": false, "text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned char index_t;\ntypedef unsigned int permutation;\n\nstatic void permutation_to_array(index_t *indices, index_t n, permutation p)\n{\n index_t used = 0;\n for (index_t i = 0; i < n; ++i) {\n index_t left = n - i;\n index_t digit = p % left;\n for (index_t j = 0; j <= digit; ++j) {\n if (used & (1 << j)) {\n digit++;\n }\n }\n used |= (1 << digit);\n indices[i] = digit;\n p /= left;\n }\n}\n\nstatic void dump_array(index_t *indices, index_t n)\n{\n fputs(\"[\", stdout);\n for (index_t i = 0; i < n; ++i) {\n printf(\"%d\", indices[i]);\n if (i != n - 1) {\n fputs(\", \", stdout);\n }\n }\n puts(\"]\");\n}\n\nstatic int factorial(int n)\n{\n int prod = 1;\n for (int i = 1; i <= n; ++i) {\n prod *= i;\n }\n return prod;\n}\n\nint main(int argc, char **argv)\n{\n const index_t n = 4;\n const permutation max = factorial(n);\n index_t *indices = malloc(n * sizeof (*indices));\n for (permutation p = 0; p < max; ++p) {\n permutation_to_array(indices, n, p);\n dump_array(indices, n);\n }\n free(indices);\n}\n" }, { "answer_id": 166046, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 0, "selected": false, "text": "#include <math.h>\n#include <stdio.h>\n\ntypedef signed char index_t;\ntypedef unsigned int permutation;\n\nstatic index_t permutation_next(index_t n, permutation p, index_t value)\n{\n permutation used = 0;\n for (index_t i = 0; i < n; ++i) {\n index_t left = n - i;\n index_t digit = p % left;\n p /= left;\n for (index_t j = 0; j <= digit; ++j) {\n if (used & (1 << j)) {\n digit++;\n }\n }\n used |= (1 << digit);\n if (value == -1) {\n return digit;\n }\n if (value == digit) {\n value = -1;\n }\n }\n /* value not found */\n return -1;\n}\n\nstatic void dump_permutation(index_t n, permutation p)\n{\n index_t value = -1;\n fputs(\"[\", stdout);\n value = permutation_next(n, p, value);\n while (value != -1) {\n printf(\"%d\", value);\n value = permutation_next(n, p, value);\n if (value != -1) {\n fputs(\", \", stdout);\n }\n }\n puts(\"]\");\n}\n\nstatic int factorial(int n)\n{\n int prod = 1;\n for (int i = 1; i <= n; ++i) {\n prod *= i;\n }\n return prod;\n}\n\nint main(int argc, char **argv)\n{\n const index_t n = 4;\n const permutation max = factorial(n);\n for (permutation p = 0; p < max; ++p) {\n dump_permutation(n, p);\n }\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24404/" ]
162,617
<p>When creating a new file with vim, I would like to automatically add some skeleton code.</p> <p>For example, when creating a new xml file, I would like to add the first line:</p> <pre><code> &lt;?xml version="1.0"?&gt; </code></pre> <p>Or when creating an html file, I would like to add:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 162654, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 1, "selected": false, "text": "augroup Xml\n au BufNewFile *.xml :python import vim\n au BufNewFile *.xml :python vim.current.buffer[0:0] = ['<?xml version=\"1.0\"?>']\n au BufNewFile *.xml :python del vim\naugroup END\n\nfu s:InsertHtmlSkeleton()\n python import vim\n python vim.current.buffer[0:0] = ['<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">', \"<html>\", \"<head>\", \" <title></title>\", \"</head>\", \"<body>\", \"\", \"</body>\", \"</html>\"]\n python del vim\nendfu\n\naugroup Html\n au BufNewFile *.html call <SID>InsertHtmlSkeleton()\naugroup END\n" }, { "answer_id": 162662, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 1, "selected": false, "text": ":help event\n :help BufNewFile\n" }, { "answer_id": 162671, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 5, "selected": false, "text": "au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = \"xml\"\nau BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = \"html\"\n" }, { "answer_id": 162704, "author": "erichui", "author_id": 6034, "author_profile": "https://Stackoverflow.com/users/6034", "pm_score": 4, "selected": false, "text": "augroup Xml\n au BufNewFile *.xml 0r ~/vim/skeleton.xml\naugroup end\n" }, { "answer_id": 7264817, "author": "orftz", "author_id": 603891, "author_profile": "https://Stackoverflow.com/users/603891", "pm_score": 3, "selected": false, "text": "if has(\"win32\") || has ('win64')\n let $VIMHOME = $HOME.\"/vimfiles/\"\nelse\n let $VIMHOME = $HOME.\"/.vim/\"\nendif\n\n\" add templates in templates/ using filetype as file name\nau BufNewFile * :silent! exec \":0r \".$VIMHOME.\"templates/\".&ft\n" }, { "answer_id": 26910252, "author": "ibizaman", "author_id": 1013628, "author_profile": "https://Stackoverflow.com/users/1013628", "pm_score": 0, "selected": false, "text": "augroup documentation\n au!\n au BufNewFile *.py :call ExecuteSnippet('docs')\naugroup END\n\nfunction! ExecuteSnippet(name)\n execute \"normal! i\" . a:name . \"\\<c-r>=TriggerSnippet()\\<cr>\"\nendfunction\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24076/" ]
162,618
<p>Using C#</p> <p>How do you remove a specific node from an XMLDocument using XPATH?</p>
[ { "answer_id": 162647, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "XmlDocument doc = new XmlDocument();\n\n// Load you XML Document\n\nXmlNode childNode = doc.SelectSingleNode(childNodeName);\n\n// Remove from the document\ndoc.RemoveChild(childNode);\n" }, { "answer_id": 6174553, "author": "jocheng", "author_id": 413010, "author_profile": "https://Stackoverflow.com/users/413010", "pm_score": 4, "selected": false, "text": "XmlDocument doc = new XmlDocument();\n// ... fill or load the XML Document\nXmlNode childNode = doc.SelectSingleNode(\"/rootnode/childnode/etc\"); // apply your xpath here\nchildNode.ParentNode.RemoveChild(childNode);\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ]
162,644
<p>Firebug is the most convenient tool I've found for editing CSS - so why isn't there a simple "save" option for CSS?</p> <p>I am always finding myself making tweaks in Firebug, then going back to my original .css file and replicating the tweaks.</p> <p>Has anyone come up with a better solution?</p> <p><b>EDIT:</b> I'm aware the code is stored on a server (in most cases not my own), but I use it when building my own websites.</p> <p>Firebug's just using the .css file Firefox downloaded from the server, it knows precisely what lines in which files it's editing. I can't see why there's not an "export" or "save" option, which allows you to store the new .css file. (Which I could then replace the remote one with).</p> <p>I have tried looking in temporary locations, and choosing <em>File</em> > <em>Save...</em> and experimenting with the output options on Firefox, but I still haven't found a way.</p> <p><b>EDIT 2:</b> The official discussion group has <a href="https://groups.google.com/forum/#!searchin/firebug/save$20css" rel="nofollow noreferrer">a lot of questions</a>, but no answers.</p>
[ { "answer_id": 8175478, "author": "Lance", "author_id": 169992, "author_profile": "https://Stackoverflow.com/users/169992", "pm_score": 2, "selected": false, "text": "id id #element-127 {\n background: red;\n}\n .space box-shadow()" }, { "answer_id": 11593735, "author": "Leniel Maccaferri", "author_id": 114029, "author_profile": "https://Stackoverflow.com/users/114029", "pm_score": 6, "selected": true, "text": "CSS" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14966/" ]
162,651
<p>What is the difference between these two pieces of code</p> <pre><code>type IInterface1 = interface procedure Proc1; end; IInterface2 = interface procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface1, IInterface2) protected procedure Proc1; procedure Proc2; end; </code></pre> <p>And the following :</p> <pre><code>type IInterface1 = interface procedure Proc1; end; IInterface2 = interface(Interface1) procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface2) protected procedure Proc1; procedure Proc2; end; </code></pre> <p>If they are one and the same, are there any advantages, or readability issues with either.</p> <p>I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.</p>
[ { "answer_id": 162682, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 1, "selected": false, "text": "...\nIInterface2 = interface(Interface1)\n...\n" }, { "answer_id": 162706, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 3, "selected": true, "text": "IInterface2 = interface(Interface1)\n" }, { "answer_id": 164141, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 3, "selected": false, "text": "Supports as type\n A_I1 = interface\n end;\n\n A_I2 = interface(A_I1)\n end;\n\n A_Class = class(TInterfacedObject, A_I2)\n end;\n\n procedure TestA;\n var\n a: A_Class;\n x: A_I1;\n begin\n a := A_Class.Create;\n x := a; // fails!\n end;\n\n type\n B_I1 = interface\n end;\n\n B_I2 = interface\n end;\n\n B_Class = class(TInterfacedObject, B_I1, B_I2)\n end;\n\n procedure TestB;\n var\n a: B_Class;\n x: B_I1;\n begin\n a := B_Class.Create;\n x := a; // succeeds!\n end;\n\n begin\n TestA;\n TestB;\n end.\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
162,674
<p>When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the <strong>text exceeds the screen</strong>. </p> <p>But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode.</p> <p>Any idea how to do this?</p> <hr> <p>Show, don't tell:</p> <p>How it is: </p> <p><a href="https://i.stack.imgur.com/aqDww.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aqDww.png" alt="how it is"></a> </p> <p>How I want: </p> <p><a href="https://i.stack.imgur.com/buIrV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/buIrV.png" alt="how I want"></a> </p>
[ { "answer_id": 162769, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 2, "selected": false, "text": "ToolTip.Show public void Show(\n string text,\n IWin32Window window,\n int x,\n int y,\n int duration\n)\n" }, { "answer_id": 309457, "author": "Jonas", "author_id": 10833, "author_profile": "https://Stackoverflow.com/users/10833", "pm_score": 3, "selected": false, "text": " private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)\n {\n TreeNode node = treeView1.GetNodeAt(e.X, e.Y);\n if (node != null)\n {\n string text = GetNodeTooltip(node);\n string currentText = toolTip1.GetToolTip(treeView1);\n\n if (text.Equals(currentText) == false)\n {\n toolTip1.SetToolTip(treeView1, text);\n }\n }\n else\n {\n toolTip1.SetToolTip(tree, string.Empty);\n }\n }\n else\n {\n toolTip1.SetToolTip(tree, string.Empty);\n }\n }\n treeView1.ShowNodeToolTips=true TreeNode.ToolTipText" }, { "answer_id": 3541601, "author": "Boris Kalandarov", "author_id": 427631, "author_profile": "https://Stackoverflow.com/users/427631", "pm_score": 2, "selected": false, "text": "private ToolTip toolTipController = new ToolTip() { UseFading = false,UseAnimation = false};\n\nprotected override void OnMouseMove(MouseEventArgs e)\n{\n var node = GetNodeAt(e.X, e.Y);\n if (node != null)\n {\n var text = node.Text;\n\n if (!text.Equals(toolTipController.GetToolTip(this)))\n {\n toolTipController.Show(text, this, e.Location, 2000);\n }\n }\n else\n {\n toolTipController.RemoveAll();\n }\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
162,677
<p>How would I write a Perl CGI script that receives a file via a HTTP post and saves that to the file system?</p>
[ { "answer_id": 162724, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 4, "selected": true, "text": " #!/usr/bin/perl -wT\n\nuse strict;\nuse CGI;\nuse CGI::Carp qw ( fatalsToBrowser );\nuse File::Basename;\n\n$CGI::POST_MAX = 1024 * 5000;\nmy $safe_filename_characters = \"a-zA-Z0-9_.-\";\nmy $upload_dir = \"/home/www/upload\";\n\nmy $query = new CGI;\nmy $filename = $query->param(\"photo\");\nmy $email_address = $query->param(\"email_address\");\n\nif ( !$filename )\n{\n print $query->header ( );\n print \"There was a problem uploading your photo (try a smaller file).\";\n exit;\n}\n\nmy ( $name, $path, $extension ) = fileparse ( $filename, '\\..*' );\n$filename = $name . $extension;\n$filename =~ tr/ /_/;\n$filename =~ s/[^$safe_filename_characters]//g;\n\nif ( $filename =~ /^([$safe_filename_characters]+)$/ )\n{\n $filename = $1;\n}\nelse\n{\n die \"Filename contains invalid characters\";\n}\n\nmy $upload_filehandle = $query->upload(\"photo\");\n\nopen ( UPLOADFILE, \">$upload_dir/$filename\" ) or die \"$!\";\nbinmode UPLOADFILE;\n\nwhile ( <$upload_filehandle> )\n{\n print UPLOADFILE;\n}\n\nclose UPLOADFILE;\n\nprint $query->header ( );\nprint <<END_HTML;\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>Thanks!</title>\n </head>\n <body>\n <p>Thanks for uploading your photo!</p>\n </body>\n</html>\nEND_HTML\n" }, { "answer_id": 162751, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "my $fh = $query->upload('upload_field');\nwhile(<$fh>) {\n print SAVE_FILE $_;\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6701/" ]
162,681
<p>Given the email address: "Jim" &lt;jim@example.com&gt;</p> <p>If I try to pass this to MailAddress I get the exception:</p> <blockquote> <p>The specified string is not in the form required for an e-mail address.</p> </blockquote> <p>How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?</p> <p>EDIT: I'm looking for C# code to parse it.</p> <p>EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string. </p>
[ { "answer_id": 162700, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 2, "selected": false, "text": "\"Jimbo <jim@example.com>\"\n" }, { "answer_id": 162701, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "new MailAddress(\"jim@example.com\", \"Jimbo\");\n string input = \"\\\"Jimbo\\\" jim@example.com\";\nstring[] pieces = input.Split(' ');\nMailAddress ma = new MailAddress(pieces[1].Replace(\"<\", string.Empty).Replace(\">\",string.Empty), pieces[0].Replace(\"\\\"\", string.Empty));\n" }, { "answer_id": 162709, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "string inputEmailString = \"\\\"Jimbo\\\" <jim@example.com>\";\nstring[] strSet = inputEmailString.Split('\\\"','<','>'); \n\nMailAddress mAddress = new MailAddress(strSet[0], strSet[2]);\n" }, { "answer_id": 162723, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 0, "selected": false, "text": "string str = \"\\\"Jimbo\\\" jim@example.com\"\nstring[] parts = str.Trim().Replace(\"\\\"\",\"\").Split(' ')\n" }, { "answer_id": 162731, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n string email = \"\\\"Jimbo\\\" <jim@example.com>\";\n Console.WriteLine(parseEmail(email));\n }\n\n private static string parseEmail(string inputString)\n {\n Regex r = \n new Regex(@\"^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,6})$\");\n\n string[] tokens = inputString.Split(' ');\n\n foreach (string s in tokens)\n {\n string temp = s;\n temp = temp.TrimStart('<'); temp = temp.TrimEnd('>');\n\n if (r.Match(temp).Success)\n return temp;\n }\n\n throw new ArgumentException(\"Not an e-mail address\");\n }\n}\n" }, { "answer_id": 162744, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": " string emailAddress, displayname;\n string unparsedText = \"\\\"Jimbo\\\" <jim@example.com>\";\n string[] emailParts = unparsedText.Split(new char[] { '<' });\n\n if (emailParts.Length == 2)\n {\n displayname = emailParts[0].Trim(new char[] { ' ', '\\\"' });\n emailAddress = emailParts[1].TrimEnd('>');\n }\n" }, { "answer_id": 163075, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "MailAddress MailAddress \"Tom Smith <tsmith@contoso.com>\" string emailAddress = \"\\\"Jim\\\" <jim@example.com>\";\n\nMailAddress address = new MailAddress(emailAddress.Replace(\"\\\"\", \"\"));\n" }, { "answer_id": 163216, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 0, "selected": false, "text": "string addrin = \"\\\"Jim Smith\\\" <jim@example.com>\";\nchar[] bracks = {'<','>'};\nstring[] pieces = addrin.Split(bracks);\npieces[0] = pieces[0]\n .Substring(0, pieces[0].Length - 1)\n .Replace(\"\\\"\", string.Empty);\nMailAddress ma = new MailAddress(pieces[1], pieces[0]);\n" }, { "answer_id": 163301, "author": "Dylan", "author_id": 4580, "author_profile": "https://Stackoverflow.com/users/4580", "pm_score": 0, "selected": false, "text": "string emailTo = \"\\\"Jim\\\" <jim@example.com>\";\nstring emailRegex = @\"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\"\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\";\nstring emailAddress = Regex.Match(emailTo.ToLower(), emailRegex).Value;\nstring displayName = null;\n\ntry\n{\n displayName = emailTo.Substring(0, emailTo.ToLower().IndexOf(emailAddress) - 1);\n}\ncatch \n{\n // No display name \n}\n\nMailAddress addr = new MailAddress(emailAddress, displayName);\n" }, { "answer_id": 163499, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "string s = \"\\\"Jim\\\" <jim@example.com>\";\nSystem.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);\nDebug.WriteLine(\"DisplayName: \" + a.DisplayName);\nDebug.WriteLine(\"Address: \" + a.Address);\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4580/" ]
162,727
<p>I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way? </p> <p>For example, the format could be described as:</p> <pre><code>&lt;Field1(8)&gt;&lt;Field2(16)&gt;&lt;Field3(12)&gt; </code></pre> <p>And an example file with two records could look like:</p> <pre><code>SomeData0000000000123456SomeMoreData Data2 0000000000555555MoreData </code></pre> <p>I just want to make sure I'm not overlooking a more elegant way than Substring().</p> <hr> <p><strong>Update:</strong> I ultimately went with a regex like Killersponge suggested:</p> <pre><code>private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled); const string REGEX_LOT = "^(?&lt;Field1&gt;.{6})" + "(?&lt;Field2&gt;.{16})" + "(?&lt;Field3&gt;.{12})"; </code></pre> <p>I then use the following to access the fields:</p> <pre><code>Match match = reLot.Match(record); string field1 = match.Groups["Field1"].Value; </code></pre>
[ { "answer_id": 162909, "author": "Leandro Oliveira", "author_id": 16610, "author_profile": "https://Stackoverflow.com/users/16610", "pm_score": 5, "selected": false, "text": "[FixedLengthRecord()] \npublic class MyData\n{ \n [FieldFixedLength(8)] \n public string someData; \n\n [FieldFixedLength(16)] \n public int SomeNumber; \n\n [FieldFixedLength(12)] \n [FieldTrim(TrimMode.Right)]\n public string someMoreData;\n}\n var engine = new FileHelperEngine<MyData>(); \n\n// To Read Use: \nvar res = engine.ReadFile(\"FileIn.txt\"); \n\n// To Write Use: \nengine.WriteFile(\"FileOut.txt\", res); \n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]
162,730
<p>I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:</p> <pre><code>a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy </code></pre> <p>I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text.</p> <p>For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.?</p> <p>Do you have data showing the pixel width of each character? Or a program to generate it?</p> <p>I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.</p>
[ { "answer_id": 162746, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 1, "selected": false, "text": "table-layout: fixed;\n" }, { "answer_id": 162785, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<td><div style=\"width:100px;overflow:hidden\">a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_ta ... </div></td>\n" }, { "answer_id": 164513, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 1, "selected": false, "text": "function fixFatColumns() {\n $('table#MyTable td').each(function() {\n var defined_width = $(this).attr('width');\n if (defined_width) {\n var actual_width = $(this).width();\n var contents = $(this).html();\n if (contents.length) {\n var working_div = $('#ATempDiv');\n if (working_div.is('*')) {\n working_div.html(contents);\n } else {\n $('body').append('<div id=\"ATempDiv\" style=\"position:absolute;top:-100px;left:-500px;font-size:13px;font-family:Arial\">'+contents+'</div>');\n working_div = $('#ATempDiv');\n }\n\n if (working_div.width() > defined_width) {\n contents = working_div.text();\n working_div.text(contents);\n while (working_div.width() + 8 > defined_width) {\n // shorten the contents of the columns\n var working_text = working_div.text();\n if (working_text.length > 1) working_text = working_text.substr(0,working_text.length-1);\n working_div.text(working_text);\n }\n $(this).html(working_text+'...')\n }\n\n working_div.empty();\n }\n\n }\n });\n\n}\n" }, { "answer_id": 451873, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 0, "selected": false, "text": "http://www.css3.info/preview/text-overflow/\n" }, { "answer_id": 451881, "author": "Soviut", "author_id": 46914, "author_profile": "https://Stackoverflow.com/users/46914", "pm_score": 0, "selected": false, "text": "td\n{\n overflow: scroll; /* or overflow: hidden; etc. */\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ]
162,735
<p>What do you think the next evolution of languages will look like?</p>
[ { "answer_id": 5415702, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 0, "selected": false, "text": " C -> Device drivers\n C++ -> Highperformance Computing\n Java -> Server side programs (J2EE)\n C# -> Server, Client(Silverlight, WinForm, WPF)\n Ruby, Python, ... -> WebScripting (Serverside) and helper scripts\n ECMAScript (Javascript) -> WebScripting (Clientside)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
162,748
<p>On a project I'm working on, we use subversion, with tortoiseSVN as a client, under windows XP.</p> <p>As we enter in production and continue development in parallel, many branches are created.</p> <p>Often, we have to backport modifications made on the branch to the trunk, or to older branches. Backporting is a very delicate task, as many errors can be introduced into the code.</p> <p>What are your favorite tools to make backporting easier and more secure ? If possible, add only one tool per answer, and vote for your favorite ones.</p>
[ { "answer_id": 5415702, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 0, "selected": false, "text": " C -> Device drivers\n C++ -> Highperformance Computing\n Java -> Server side programs (J2EE)\n C# -> Server, Client(Silverlight, WinForm, WPF)\n Ruby, Python, ... -> WebScripting (Serverside) and helper scripts\n ECMAScript (Javascript) -> WebScripting (Clientside)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2965/" ]
162,752
<p>I am looking for an algorithm to calculate the next set of operations in a sequence. Here is the simple definition of the sequence.</p> <ol> <li>Task 1A will be done every 500 hours</li> <li>Task 2A will be done every 1000 hours</li> <li>Task 3A will be done every 1500 hours</li> </ol> <p>So at t=500, do 1A. At t=1000, do both 1A and 2A, at t=1500 do 1A and 3A, but not 2A as 1500 is not a multiple of 1000. You get the idea.</p> <p>It would be quite easy if I had the actual time, but I don't. What I have is the history of tasks (eg last time a [1A+2A] was done). </p> <p>Knowing last time (eg [1A+2A]) is not enough to decide:</p> <ul> <li>[1A+2A] could be at t=1000: next is [1A+3A] at t=1500</li> <li>[1A+2A] could be at t=5000: next is [1A] at t=5500</li> </ul> <p>Is there an algorithm for this? It looks like a familiar problem (some sort of sieve?) but I can't seem to find a solution.</p> <p>Also it must "scale" as I actually have more than 3 tasks.</p>
[ { "answer_id": 195931, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 2, "selected": true, "text": "history = [list of tuples like (timestamp, (A, B, ...)), ordered by timestamp]\nlastTaskTime = {}\ntaskIntervals = {}\n\nfor timestamp, tasks in history:\n for task in tasks:\n if task not in lastTaskTime:\n lastTaskTime[task] = timestamp\n else:\n lastTimestamp = lastTaskTime[task]\n interval = abs(timestamp - lastTimestamp)\n if task not in taskIntervals or interval < taskIntervals[task]:\n taskIntervals[task] = interval # Found a shorter interval\n\n # Always remember the last timestamp\n lastTaskTime[task] = timestamp\n\n# taskIntervals contains the shortest time intervals of each tasks executed at least twice in the past\n# lastTaskTime contains the last time each task was executed\n nextTime = None\nnextTasks = []\n\nfor task in lastTaskTime:\n lastTime = lastTaskTime[task]\n interval = taskIntervals[task]\n\n if not nextTime or lastTime + interval < nextTime:\n nextTime = lastTime + interval\n nextTasks = [task]\n elif lastTime + interval == nextTime:\n nextTasks.append(task)\n\n# nextTime contains the time when the next set of tasks will be executed\n# nextTasks contains the set of tasks to be executed\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341/" ]
162,753
<p>I am using a multi-dimensional dynamic array in delphi and am trying to figure this out:</p> <p>I have 2 seperate values for the first index and second index that are totally seperate of each other.</p> <p>As new values come I want to grow the array if that new value is outside of either bound.</p> <p>For new values x, y</p> <p>I check:</p> <pre><code>if Length(List) &lt; (x + 1) then SetLength(List, x + 1); if Length(List[0]) &lt; (y + 1) then SetLength(List, Length(List), y + 1); </code></pre> <p>Is this the correct way to do this or is there a better way to grow the array as needed?</p>
[ { "answer_id": 162783, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "SetLength(List, Length(List), y + 1);\n" }, { "answer_id": 165847, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 3, "selected": true, "text": "if Length(List) < (x + 1) then\n SetLength(List, x + 1);\nif Length(List[x]) < (y + 1) then\n SetLength(List[x], y + 1);\n" }, { "answer_id": 166614, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 1, "selected": false, "text": "{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nvar\n List: array of array of integer;\n\nbegin\n //set both dimensions\n SetLength(List, 3, 2);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 3, Y = 2\n //set main dimension to 4, keep subdimension untouched\n SetLength(List, 4);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 2\n //set subdimension to 3, keep main dimenstion untouched\n SetLength(List, Length(List), 3);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 3\n //all List[0]..List[3] have 3 elements\n Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //3333\n //you can change subdimension for each List[] vector\n SetLength(List[0], 1);\n SetLength(List[3], 7);\n //List is now a ragged array\n Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //1337\n //this does not even compile because it tries to set dimension that does not exist!\n// SetLength(List[0], Length(List[0]), 12);\n Readln;\nend.\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16059/" ]
162,762
<p>I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:</p> <pre><code>ORA-12154: TNS:could not resolve the connect identifier specified </code></pre> <p>If i run the application in my pc with visual studio it works fine.</p> <p>Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".</p> <p>In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere</p> <p>any idea? Thanks for the help.</p>
[ { "answer_id": 20966307, "author": "Rohit Hans", "author_id": 3168126, "author_profile": "https://Stackoverflow.com/users/3168126", "pm_score": 0, "selected": false, "text": "Variable Name: TNS_ADMIN\n\nVariable Value: (YourDrive):\\app\\(UserName)\\product\\11.2.0\\dbhome_1\\NETWORK\\ADMIN\n" }, { "answer_id": 39546535, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 0, "selected": false, "text": "con = new OracleConnection();\ncon.ConnectionString = \"User Id=username;Password=password;Data Source=uit45\";\ncon.Open(); // throws error here\n con = new OracleConnection(\"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=db-uit45.xxx)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=uit45)));User Id=username;Password=password\");\ncon.Open();\n HOST,PORT,SID,User Id Password" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24521/" ]
162,764
<p>I have a database with user 'dbo' that has a login name "domain\xzy". How do I change it from "domain\xzy" to "domain\abc".</p>
[ { "answer_id": 32514655, "author": "Mike", "author_id": 914490, "author_profile": "https://Stackoverflow.com/users/914490", "pm_score": 1, "selected": false, "text": "USE [My_Database_Name]\nGO\nEXEC dbo.sp_changedbowner @loginame = N'domain\\abc', @map = false\nGO\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24522/" ]
162,778
<p>I am creating an RSS reader as a hobby project, and at the point where the user is adding his own URL's.</p> <p>I was thinking of two things.</p> <ul> <li>A plaintext file where each url is a single line</li> <li>SQLite where i can have unique ID's and descriptions following the URL</li> </ul> <p>Is the SQLite idea to much of an overhead or is there a better way to do things like this?</p>
[ { "answer_id": 162802, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 1, "selected": false, "text": "last_fetch_time" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22459/" ]
162,797
<p>Do you know any solution to put a picture over a Flash?</p> <p>It <strong>must</strong> work in IE6, IE7, Firefox for Windows, MacOSX, Linux and Safari.</p>
[ { "answer_id": 163324, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<object width=\"550\" height=\"450\"\n codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\" \n classid=\"clsid:D27CDB6E-AE6D-11CF-96B8-444553540000\">\n<param name=\"movie\" value=\"http://somesite.org/Tests/Spiffy.swf\"/>\n<param name=\"wmode\" value=\"opaque\"/>\n<object type=\"application/x-shockwave-flash\" width=\"550\" height=\"450\"\n data=\"http://somesite.org/Tests/Spiffy.swf\">\n<param name=\"wmode\" value=\"opaque\"/>\n<img src=\"NoFlash.png\" width=\"550\" height=\"450\" alt=\"Placeholder if no Flash\" />\n</object>\n</object>\n<div style=\"background-color: blue;\n min-width: 100px; width: 100px; min-height: 100px; height: 100px;\n position: relative; right: -250px; top: -250px;\">&Nbsp;</div>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24509/" ]
162,798
<p>One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:</p> <pre><code>self.__value = 1 def value(): return self.__value </code></pre> <p>Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.</p> <p>I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?</p>
[ { "answer_id": 162854, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": true, "text": "_ContainerThing__value __value value _value" }, { "answer_id": 164691, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "__ __ _ _ _ getattr() setattr() property()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
162,804
<p>I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time. </p> <p>How would I do that? Platform: win32. </p>
[ { "answer_id": 162837, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 3, "selected": true, "text": "strncpy char *strncpy(\n char *strDest,\n const char *strSource,\n size_t count \n);\n void send250(char *inMsg, int msgLen)\n{\n char block[250];\n while (msgLen > 0)\n {\n int len = (msgLen>250) ? 250 : msgLen;\n strncpy(block, inMsg, 250);\n\n // send block to other entity\n\n msgLen -= len;\n inMsg += len;\n }\n}\n" }, { "answer_id": 162849, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "char *somehugearray;\nchar chunk[251] ={0};\nint k;\nint l;\nfor(l=0;;){\n for(k=0; k<250 && somehugearray[l]!=0; k++){\n chunk[k] = somehugearray[l];\n l++;\n }\n chunk[k] = '\\0';\n dohandoff(chunk);\n}\n" }, { "answer_id": 162928, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "char *str_end = str + strlen(str);\nchar *chunk_start = str;\n\nwhile (true) {\n char *chunk_end = chunk_start + 250;\n\n if (chunk_end >= str_end) {\n transmit(chunk_start);\n break;\n }\n\n char hijacked = *chunk_end;\n *chunk_end = '\\0';\n transmit(chunk_start);\n *chunk_end = hijacked;\n\n chunk_start = chunk_end;\n}\n" }, { "answer_id": 165602, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 0, "selected": false, "text": "void send250(char *inMsg, int msgLen)\n{\n char block[250];\n while (msgLen > 0)\n {\n int len = (msgLen>249) ? 249 : msgLen;\n strncpy(block, inMsg, 249);\n block[249] = 0;\n\n // send block to other entity\n\n msgLen -= len;\n inMsg += len;\n }\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
162,810
<p>I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.</p> <p>I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.</p> <p>But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.</p> <p>Is there a way to log the machine name via log4net in this manner?</p>
[ { "answer_id": 162979, "author": "Thad", "author_id": 24500, "author_profile": "https://Stackoverflow.com/users/24500", "pm_score": 4, "selected": false, "text": "<parameter>\n <parameterName value=\"@machine\" />\n <dbType value=\"String\" />\n <size value=\"255\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%X{machine}\" />\n </layout>\n</parameter>\n MDC.Set(\"machine\", Environment.MachineName);" }, { "answer_id": 163362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "log4net:HostName <conversionPattern value=\"%property{log4net:HostName}\" />\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2834/" ]
162,852
<p>I deleted millions of rows of old data from a production SQL database recently, and it didn't seem to shrink the size of the .MDF file much. We have a finite amount of disk space.</p> <p>I am wondering if there is anything else I can do to "tighten" the file (like something analogous to Access' Compact and Repair function)?</p>
[ { "answer_id": 162910, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "backup log MY_DATABASE WITH TRUNCATE_ONLY;\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842/" ]
162,871
<p>I'm quite new to NHibernate and starting to find my way around.</p> <p>I have a domain model that is somewhat like a tree.</p> <p>Funds have Periods have Selections have Audits<br> Now I would like to get all Audits for a specific Fund</p> <p>Would look like this if I made it in SQL</p> <p>SELECT A.*<br> FROM Audit A<br> JOIN Selection S ON A.fkSelectionID = S.pkID<br> JOIN Period P ON S.fkPeriodID = P.pkID<br> JOIN Fund F ON P.fkFundID = F.pkID<br> WHERE F.pkID = 1</p> <p>All input appreciated!</p>
[ { "answer_id": 162966, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 1, "selected": false, "text": "select elements(s.Audits)\nfrom Fund as f inner join Period as p inner join Selection as s \nwhere f = myFundInstance \n" }, { "answer_id": 214286, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "session.CreateCriteria ( typeof(Audit) )\n .CreateCriteria(\"Selection\")\n .CreateCriteria(\"Period\")\n .CreateCriteria(\"Fund\")\n .Add(Restrinction.IdEq(fundId))\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11434/" ]
162,873
<p>How do you include a file that is more than 2 directories back. I know you can use <code>../index.php</code> to include a file that is 2 directories back, but how do you do it for 3 directories back? Does this make sense? I tried <code>.../index.php</code> but it isn't working.</p> <p>I have a file in <code>/game/forum/files/index.php</code> and it uses PHP include to include a file. Which is located in <code>/includes/boot.inc.php</code>; <code>/</code> being the root directory.</p>
[ { "answer_id": 162881, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 4, "selected": false, "text": "../../index.php \n" }, { "answer_id": 162882, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 3, "selected": false, "text": "../../directory/file.txt ../../../" }, { "answer_id": 162883, "author": "HAXEN", "author_id": 11434, "author_profile": "https://Stackoverflow.com/users/11434", "pm_score": 3, "selected": false, "text": "../../../includes/boot.inc.php\n" }, { "answer_id": 162884, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": false, "text": ".. ../../index.php\n" }, { "answer_id": 162887, "author": "MazarD", "author_id": 22672, "author_profile": "https://Stackoverflow.com/users/22672", "pm_score": 3, "selected": false, "text": "../../../index.php\n" }, { "answer_id": 162888, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 4, "selected": false, "text": "../../../includes/boot.inc.php\n ../" }, { "answer_id": 162891, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": false, "text": ". = current directory\n.. = parent directory\n ../ ../" }, { "answer_id": 162899, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "../../../../../../../../../../etc/passwd\n" }, { "answer_id": 162905, "author": "Dan Hulton", "author_id": 8327, "author_profile": "https://Stackoverflow.com/users/8327", "pm_score": 6, "selected": false, "text": "'../file' '../../file' require_once($_SERVER['DOCUMENT_ROOT'] . 'directory/directory/file');\n DOCUMENT_ROOT" }, { "answer_id": 162918, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "/ .." }, { "answer_id": 11953884, "author": "im_brian_d", "author_id": 1342440, "author_profile": "https://Stackoverflow.com/users/1342440", "pm_score": 4, "selected": false, "text": "../ ../../ ../../../ define('BD', '/home/user/public_html/example/');\n\ndefine('HTMLBD', 'http://example.com/');\n file(BD.'location/of/file.php');\n" }, { "answer_id": 12095160, "author": "gaborous", "author_id": 1121352, "author_profile": "https://Stackoverflow.com/users/1121352", "pm_score": 5, "selected": false, "text": "include dirname(__FILE__).'/../../index.php';\n include '../../index.php' htdocs\n¦ parent.php\n¦ goal.php\n¦\n+---sub\n ¦ included.php\n ¦ goal.php\n parent.php <?php\ninclude dirname(__FILE__).'/sub/included.php';\n?>\n sub/included.php <?php\nprint(\"WRONG : \" . realpath('goal.php'));\nprint(\"GOOD : \" . realpath(dirname(__FILE__).'/goal.php'));\n?>\n parent.php WRONG : X:\\htdocs\\goal.php\nGOOD : X:\\htdocs\\sub\\goal.php\n parent.php dirname(__FILE__).'/path' included.php include '/../../index.php';\n / include ../../index.php include_path" }, { "answer_id": 12289657, "author": "Bronek", "author_id": 769465, "author_profile": "https://Stackoverflow.com/users/769465", "pm_score": 1, "selected": false, "text": "require_once '../file.php'; // server internal error 500\n require_once '/../file.php'; // OK\n" }, { "answer_id": 12437609, "author": "khan", "author_id": 1673412, "author_profile": "https://Stackoverflow.com/users/1673412", "pm_score": 2, "selected": false, "text": "../../ root/inc/usr/ap root/2nd/path path ap ../../2nd/path" }, { "answer_id": 19946346, "author": "user2951753", "author_id": 2951753, "author_profile": "https://Stackoverflow.com/users/2951753", "pm_score": 3, "selected": false, "text": "./ = Your current directory\n../ = One directory lower\n../../ = Two directories lower\n../../../ = Three directories lower\n" }, { "answer_id": 22999028, "author": "allenn", "author_id": 3521287, "author_profile": "https://Stackoverflow.com/users/3521287", "pm_score": 2, "selected": false, "text": "dbsettings.php:\n$host='localhost';\n$user='username':\n$pass='pass';\n\nproxy.php:\ninclude_once 'db/dbsettings.php\n\nrequiredDbSettings.php:\ninclude_once './../proxy.php';\n" }, { "answer_id": 40989202, "author": "ron", "author_id": 2672617, "author_profile": "https://Stackoverflow.com/users/2672617", "pm_score": 3, "selected": false, "text": "dirname(\"/usr/local/lib\", 2);\n" }, { "answer_id": 43917676, "author": "LF00", "author_id": 6521116, "author_profile": "https://Stackoverflow.com/users/6521116", "pm_score": 3, "selected": false, "text": "__DIR__ __DIR__ . /../../index.php\n" }, { "answer_id": 55488815, "author": "rajpoot rehan", "author_id": 6687325, "author_profile": "https://Stackoverflow.com/users/6687325", "pm_score": 4, "selected": false, "text": "require_once('../images/yourimg.png');\n require_once('../../images/yourimg.png');\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
162,874
<p>I'm using <a href="http://enunciate.codehaus.org" rel="nofollow noreferrer">Enunciate</a> to build a prototype REST api and need to include a jar containing custom code as a library.</p> <p>My Ant Script looks like this:</p> <p></p> <pre><code>&lt;!--include all jars--&gt; &lt;path id="en.classpath"&gt; &lt;fileset dir="${lib}"&gt; &lt;include name="**/*.jar" /&gt; &lt;/fileset&gt; &lt;/path&gt; &lt;!--define the task--&gt; &lt;taskdef name="enunciate" classname="org.codehaus.enunciate.main.EnunciateTask"&gt; &lt;classpath refid="en.classpath" /&gt; &lt;/taskdef&gt; &lt;mkdir dir="${dist}" /&gt; &lt;enunciate dir="${src}" configFile="${basedir}/enunciate.xml"&gt; &lt;include name="**/*.java" /&gt; &lt;classpath refid="en.classpath"/&gt; &lt;export artifactId="spring.war.file" destination="${dist}/${war.name}" /&gt; &lt;/enunciate&gt; </code></pre> <p></p> <p>The problem is that my custom jar is being excluded from the WAR file. It is necessary to compile the enunciate annotated classes so the jar is obviously on the classpath at compile time but enunciate is failing to include it in the distribution. I have also noticed that several of the jars needed by enunciate are not being included in the WAR file.</p> <p>Why are they being excluded and how do I fix it?</p>
[ { "answer_id": 221420, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 2, "selected": false, "text": "<jar jarfile=\"${dist}/${war.name}\" update=\"true\">\n <fileset dir=\"${lib}\">\n <include name=\"**/*.jar\" />\n </fileset>\n</jar>\n" }, { "answer_id": 32510845, "author": "Amber", "author_id": 1324406, "author_profile": "https://Stackoverflow.com/users/1324406", "pm_score": 0, "selected": false, "text": "<webapp doLibCopy=\"false\">\n <war destfile=\"build-output/{mywar}\" update=\"true\">\n <lib dir=\"WebContent/WEB-INF/lib\">\n <include name=\"**/*.jar\" />\n </lib>\n <lib dir=\"build-output\">\n <include name=\"some_other.jar\" />\n </lib>\n</war>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518/" ]
162,879
<p>Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?</p> <p>I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):</p> <pre class="lang-vb prettyprint-override"><code>Class MyClass Private _link As Uri 'Option 1: overloaded property Public Property Link1 As Uri Get return _link End Get Set(ByVal value As Uri) _link = value End Set End Property Public Property link1 As String Get return _link.ToString() End Get Set(Byval value As String) _link = new Uri(value) End Set End Property ' Option 2: Overloaded setter Public Property link2 As Uri Get return _link End Get Set(Byval value As Uri) _link = value End Set Set(Byval value As String) _link = new Uri(value) End Set End Class </code></pre> <p>Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional <code>.SetLink(string value)</code> method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).</p> <p>I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.</p>
[ { "answer_id": 162890, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "Public Sub SetLink(ByVal value as String)\n _link = new Uri(value)\nEnd Sub\n" }, { "answer_id": 162893, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "Uri URI String URI" }, { "answer_id": 162913, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "Public WriteOnly Property UriString() As String\n Set(ByVal value As String)\n m_Uri = new Uri(value)\n End Set\nEnd Property\n WriteOnly" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
162,886
<p>Does anyone know of an application or system out there for tracking changes (files added/removed, diffs on text files) to a <em>non-source controlled</em> directory over time? Something that would let you</p> <ol> <li><p>Take a snapshot of a certain directory tree at time A</p></li> <li><p>Come back at time period B and see what has changed</p></li> <li><p>Come back at time period C and see what's changed since time period A, and what's changed since time period B</p></li> </ol> <p>A source control repository isn't an option here. I want something that works on a directory structure that isn't under any kind of revision control. My group isn't in control of the servers or directory trees in question, but changes to those trees impact us and we'd like to keep track of them. The objects to "source control" are</p> <ol> <li><p>Objections to any kind of centralized repository that requires document authors to check-in, check-out.</p></li> <li><p>Objections to having to hand-roll/automate a bunch of tasks that can leverage a version control system's feature set</p></li> </ol> <p>I want a semi-mature package where people have spent some time thinking about the problem. If there's a version control system that's been built to handle this kind of thing, it applies. </p>
[ { "answer_id": 162980, "author": "Dickon Reed", "author_id": 22668, "author_profile": "https://Stackoverflow.com/users/22668", "pm_score": 3, "selected": true, "text": "hg commit -A -m \"automated snapshot\"" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
162,896
<p>I'm a Mac user and I've decided to learn Emacs. I've <a href="http://steve.yegge.googlepages.com/effective-emacs" rel="noreferrer">read</a> that to reduce hand strain and improve accuracy the <kbd>CTRL</kbd> and <kbd>CAPS LOCK</kbd> keys should be swapped. How do I do this in Leopard?</p> <p>Also, in Terminal I have to use the <kbd>ESC</kbd> key to invoke meta. Is there any way to get the alt/option key to invoke meta instead?</p> <p><strong>update:</strong> While the control key is much easier to hit now, the meta key is also used often enough that its position on my MacBook and Apple Keyboard also deserves attention. In fact, I find that the control key is actually easier to hit, so I've remapped my control key to act as a meta key. Does anyone have a better/more standard solution?</p>
[ { "answer_id": 19614725, "author": "lawlist", "author_id": 2112489, "author_profile": "https://Stackoverflow.com/users/2112489", "pm_score": 2, "selected": false, "text": "ns-win.el --with-ns init.el (define-key global-map [?\\s-,] 'customize)\n(define-key global-map [?\\s-'] 'next-multiframe-window)\n(define-key global-map [?\\s-`] 'other-frame)\n(define-key global-map [?\\s-~] 'ns-prev-frame)\n(define-key global-map [?\\s--] 'center-line)\n(define-key global-map [?\\s-:] 'ispell)\n(define-key global-map [?\\s-?] 'info)\n(define-key global-map [?\\s-^] 'kill-some-buffers)\n(define-key global-map [?\\s-&] 'kill-this-buffer)\n(define-key global-map [?\\s-C] 'ns-popup-color-panel)\n(define-key global-map [?\\s-D] 'dired)\n(define-key global-map [?\\s-E] 'edit-abbrevs)\n(define-key global-map [?\\s-L] 'shell-command)\n(define-key global-map [?\\s-M] 'manual-entry)\n(define-key global-map [?\\s-S] 'ns-write-file-using-panel)\n(define-key global-map [?\\s-a] 'mark-whole-buffer)\n(define-key global-map [?\\s-c] 'ns-copy-including-secondary)\n(define-key global-map [?\\s-d] 'isearch-repeat-backward)\n(define-key global-map [?\\s-e] 'isearch-yank-kill)\n(define-key global-map [?\\s-f] 'isearch-forward)\n(define-key global-map [?\\s-g] 'isearch-repeat-forward)\n(define-key global-map [?\\s-h] 'ns-do-hide-emacs)\n(define-key global-map [?\\s-H] 'ns-do-hide-others)\n(define-key global-map [?\\s-j] 'exchange-point-and-mark)\n(define-key global-map [?\\s-k] 'kill-this-buffer)\n(define-key global-map [?\\s-l] 'goto-line)\n(define-key global-map [?\\s-m] 'iconify-frame)\n(define-key global-map [?\\s-n] 'make-frame)\n(define-key global-map [?\\s-o] 'ns-open-file-using-panel)\n(define-key global-map [?\\s-p] 'ns-print-buffer)\n(define-key global-map [?\\s-q] 'save-buffers-kill-emacs)\n(define-key global-map [?\\s-s] 'save-buffer)\n(define-key global-map [?\\s-t] 'ns-popup-font-panel)\n(define-key global-map [?\\s-u] 'revert-buffer)\n(define-key global-map [?\\s-v] 'yank)\n(define-key global-map [?\\s-w] 'delete-frame)\n(define-key global-map [?\\s-x] 'kill-region)\n(define-key global-map [?\\s-y] 'ns-paste-secondary)\n(define-key global-map [?\\s-z] 'undo)\n(define-key global-map [?\\s-|] 'shell-command-on-region)\n(define-key global-map [s-kp-bar] 'shell-command-on-region)\n;; (as in Terminal.app)\n(define-key global-map [s-right] 'ns-next-frame)\n(define-key global-map [s-left] 'ns-prev-frame)\n\n(define-key global-map [home] 'beginning-of-buffer)\n(define-key global-map [end] 'end-of-buffer)\n(define-key global-map [kp-home] 'beginning-of-buffer)\n(define-key global-map [kp-end] 'end-of-buffer)\n(define-key global-map [kp-prior] 'scroll-down-command)\n(define-key global-map [kp-next] 'scroll-up-command)\n\n;; Allow shift-clicks to work similarly to under Nextstep.\n(define-key global-map [S-mouse-1] 'mouse-save-then-kill)\n(global-unset-key [S-down-mouse-1])\n" }, { "answer_id": 22002210, "author": "Lester Cheung", "author_id": 50774, "author_profile": "https://Stackoverflow.com/users/50774", "pm_score": 0, "selected": false, "text": "(custom-set-variables\n '(ns-alternate-modifier (quote super))\n '(ns-command-modifier (quote meta)))\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
162,897
<p>Given the following C function in a DLL:</p> <pre><code>char * GetDir(char* path ); </code></pre> <p>How would you P/Invoke this function into C# and marshal the char * properly. .NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.</p>
[ { "answer_id": 162922, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 4, "selected": false, "text": "[DllImport(\"your.dll\", CharSet = CharSet.Ansi)]\nstring GetDir(StringBuilder path);\n" }, { "answer_id": 163573, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 6, "selected": true, "text": "\n[DllImport(\"your.dll\", CharSet = CharSet.Ansi)]\nIntPtr GetDir(StringBuilder path);\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
162,911
<p>If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket. </p>
[ { "answer_id": 1146921, "author": "Antony Stubbs", "author_id": 105741, "author_profile": "https://Stackoverflow.com/users/105741", "pm_score": 5, "selected": true, "text": " component.add( new AbstractDefaultAjaxBehavior() {\n\n @Override\n protected void respond(AjaxRequestTarget target) {\n // your code here\n }\n\n @Override\n public void renderHead(IHeaderResponse response) {\n super.renderHead( response );\n response.renderOnDomReadyJavascript( getCallbackScript().toString() );\n }\n\n }\n" }, { "answer_id": 3572162, "author": "tetsuo", "author_id": 176897, "author_profile": "https://Stackoverflow.com/users/176897", "pm_score": 3, "selected": false, "text": "function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel)\n function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel)\n function callWicket() {\n var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });\n}\n $url$ abstractDefaultAjaxBehavior.getCallbackUrl() &foo=bar Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();\n String paramFoo = RequestCycle.get().getRequest().getParameter(\"foo\");\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23486/" ]
162,931
<p>I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.</p> <p>The closest I have been able to manage is this:</p> <pre><code>If IsNull({ValuationReport.YestPrice}) Then 'N/A' Else ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2) </code></pre> <p>However this represents negative numbers using a negative sign, not parentheses. </p> <p>I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?</p>
[ { "answer_id": 163019, "author": "Pyroglass", "author_id": 21760, "author_profile": "https://Stackoverflow.com/users/21760", "pm_score": 4, "selected": true, "text": "ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100)) CCur CCur(number) CCur(string) Replace (ToText(CCur({field})),\"$\" , \"\")" }, { "answer_id": 792254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then\n \"nd\"\nelse\n totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
162,936
<p>I'm writing a GUI in C#, Visual Studio 2008, using the Designer and WinForms. I've got a ComboBox control, and I'd like it to only allow to select from the provided options and not to accept a user-entered string. It doesn't appear to have a ReadOnly property, and disabling it hinders the readability of the control (as well as disallowing user-selection).</p>
[ { "answer_id": 163012, "author": "David Max", "author_id": 22284, "author_profile": "https://Stackoverflow.com/users/22284", "pm_score": 2, "selected": false, "text": "comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;\ncomboBox1.Items.AddRange(new object[] {\n \"One\",\n \"Two\",\n \"Three\",\n \"Four\"});\n" }, { "answer_id": 14066723, "author": "Isuru", "author_id": 1077789, "author_profile": "https://Stackoverflow.com/users/1077789", "pm_score": 2, "selected": false, "text": "private void combobox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n e.Handled = true;\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24529/" ]
162,941
<p>I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages. </p> <p>Basically I have three questions:</p> <ol> <li>Why use pointers over normal variables?</li> <li>When and where should I use pointers?</li> <li>How do you use pointers with arrays?</li> </ol>
[ { "answer_id": 162988, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 6, "selected": false, "text": "char hello[] = \"hello\";\n\nchar *p = hello;\n\nwhile (*p)\n{\n *p += 1; // increase the character by one\n\n p += 1; // move to the next spot\n}\n\nprintf(hello);\n ifmmp\n" }, { "answer_id": 163103, "author": "trshiv", "author_id": 21647, "author_profile": "https://Stackoverflow.com/users/21647", "pm_score": 6, "selected": false, "text": "public void doSomething()\n{\n int i = 10;\n doSomethingElse(i); // passes i by references since doSomethingElse() receives it\n // by reference, but the syntax makes it appear as if i is passed\n // by value\n}\n\npublic void doSomethingElse(int& i) // receives i as a reference\n{\n cout << i << endl;\n}\n public void doSomething()\n{\n int i = 10;\n doSomethingElse(&i);\n}\n\npublic void doSomethingElse(int* i)\n{\n cout << *i << endl;\n}\n" }, { "answer_id": 163304, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 4, "selected": false, "text": "unsigned char *pVideoMemory = (unsigned char *)0xA0000000;\n" }, { "answer_id": 163544, "author": "Tooony", "author_id": 23864, "author_profile": "https://Stackoverflow.com/users/23864", "pm_score": 8, "selected": false, "text": "sizeof char* a = \"Hello\";\nchar a[] = \"Hello\";\n printf(\"Second char is: %c\", a[1]);\n printf(\"Second char is: %c\", *(a+1));\n printf(\"Second char is: %s\", (a+1)); /* WRONG */\n char* a = \"Hello\";\nint b = 120;\nprintf(\"Second char is: %s\", b);\n char* x;\n/* Allocate 6 bytes of memory for me and point x to the first of them. */\nx = (char*) malloc(6);\nx[0] = 'H';\nx[1] = 'e';\nx[2] = 'l';\nx[3] = 'l';\nx[4] = 'o';\nx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", x, x);\n/* Delete the allocation (reservation) of the memory. */\n/* The char pointer x is still pointing to this address in memory though! */\nfree(x);\n/* Same as malloc but here the allocated space is filled with null characters!*/\nx = (char *) calloc(6, sizeof(x));\nx[0] = 'H';\nx[1] = 'e';\nx[2] = 'l';\nx[3] = 'l';\nx[4] = 'o';\nx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", x, x);\n/* And delete the allocation again... */\nfree(x);\n/* We can set the size at declaration time as well */\nchar xx[6];\nxx[0] = 'H';\nxx[1] = 'e';\nxx[2] = 'l';\nxx[3] = 'l';\nxx[4] = 'o';\nxx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", xx, xx);\n" }, { "answer_id": 16846059, "author": "Carl", "author_id": 13760, "author_profile": "https://Stackoverflow.com/users/13760", "pm_score": 5, "selected": false, "text": "MyType a; //let's ignore what MyType actually is right now.\na = modify(a); \n MyType *p = NULL; //empty pointer\nif(p)\n{\n //we never reach here, because the pointer points to nothing\n}\n//now, let's allocate some memory\np = new MyType[50000];\nif(p) //if the memory was allocated, this test will pass\n{\n //we can do something with our allocated array\n for(size_t i=0; i!=50000; i++)\n {\n MyType &v = *(p+i); //get a reference to the ith object\n //do something with it\n //...\n }\n delete[] p; //we're done. de-allocate the memory\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
162,960
<p>So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.</p> <p>From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files? </p>
[ { "answer_id": 162970, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 5, "selected": true, "text": "svn move <oldfile> <newfile>\n git mv <oldfile> <newfile> mv" }, { "answer_id": 162998, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 3, "selected": false, "text": "$ cvs rename old new\n$ cvs commit -m \"Renamed old to new\"\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4172/" ]
162,962
<p>When I run my Visual Studio Windows Forms application by clicking F5 (debug mode), after I click on the close button (which calls <code>Application.Exit()</code>), after a few seconds I get an error that says:</p> <blockquote> <p>cannot acess a disposed object: Object name 'SampleForm'.</p> </blockquote> <p>A bit of background, I have another thread that runs every x seconds.</p> <p>My guess is that when I close the application, and since it is still in debug mode, the other thread is still running and it tries to access something but since I close the application the form is disposed.</p> <p>Is this correct?</p> <p>Do I have to kill the background process thread in before I call <code>Application.Exit()</code>?</p> <p><b>Update</b></p> <p>Now when I call <code>thread.Abort()</code> before the call to <code>Application.Exit()</code> the application closes completely. Before, EVEN after I clicked on the close button, the debugger was still running (i.e. the stop button was not selected) so it must have been because the thread was still active).</p>
[ { "answer_id": 162972, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "do {\n\n // Crazy threading stuff here\n\n}while(_running);\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
162,969
<p>I'm developing a an eclipse plugin that uses an SWT interface. I need to display text, and within that text there needs to be links. The only two widgets that I've found that will allow me to include clickable links in text are Link and Browser. Browser, however, is overkill for my needs, and I couldn't properly customize the look of it. This only leaves the Link widget.</p> <p>The problem is I need the Link widget to inherit a gradient from the Composite in which it is in. It does this correctly, only when it is resized or scrolled the Link component flickers. The Link is the only component in which I have seen this effect.</p> <p>In an attempt to fix this I've tried manipulating other components into having clickable links, but I haven't found a good solution yet.</p> <p>Is there anyway to fix the flickering effect on the Link, or is there a different component which would support links?</p> <p>Thanks,</p> <p>Brian</p>
[ { "answer_id": 162972, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "do {\n\n // Crazy threading stuff here\n\n}while(_running);\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
162,986
<p>I have a class that looks like this</p> <pre><code>public class SomeClass { public SomeChildClass[] childArray; } </code></pre> <p>which will output XML from the XMLSerializer like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>But I want the XML to look like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass index=1&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass index=2&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>Where the index attribute is equal to the items position in the array.</p> <p>I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object.</p> <p>Is there some attribute i can add or some other way to automatically generate the index attribute for me?</p>
[ { "answer_id": 163134, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 3, "selected": true, "text": "[XmlAttribute(\"Index\")]\npublic int Order\n{ { get; set; } }\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3543/" ]
162,989
<p>How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports:</p> <pre><code>this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc"; this.reportViewer1.LocalReport.Refresh(); this.reportViewer1.RefreshReport(); </code></pre> <p>When this code executes, the original report remains visible in the report viewer.</p> <p>I have also tried using</p> <pre><code>LocalReport.LoadReportDefinition </code></pre> <p>but had the same result.</p>
[ { "answer_id": 167132, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 4, "selected": true, "text": "<ReportViewer>.Reset();\n <ReportViewer>.LocalReport.DataSources.Add( ... );\n" }, { "answer_id": 71563048, "author": "Mousa Abdulmaxod", "author_id": 11836637, "author_profile": "https://Stackoverflow.com/users/11836637", "pm_score": 0, "selected": false, "text": "//choose which report to load\n string reportEmbeddedResource = this.orderReportViewer.LocalReport.ReportEmbeddedResource;\n //remove the extention .rdlc\n reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));\n //remove name of current report ex: .invoice.rdlc\n reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));\n //clear current reportEmbeddedResource\n this.orderReportViewer.Reset();\n if (_retailReceip)\n {\n this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + \".PrintReceipt.rdlc\";\n }\n else\n {\n this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + \".PrintOrder.rdlc\";\n }\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5557/" ]
162,993
<p>I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines:</p> <pre><code>[System.ComponentModel.RunInstaller(true)] public class MyApplicationManagementInstaller : DefaultManagementInstaller { } </code></pre> <p>I gather the purpose of this installation is because the Windows WMI infrastructure needs to be aware of the structure of my WMI provider before it is used.</p> <p>My question is - when is this "installer" ran? MSDN says that the installer will be invoked "during installation of an assembly", but I am not sure what that means or when it would happen in the context of a class library containing a WMI provider.</p> <p>I was under the impression that this was an automated replacement for manually running <strong>InstallUtil.exe</strong> against the assembly containing the WMI provider, but changes I make to the provider are not recognised by the Windows WMI infrastructure unless I manually run InstallUtil from the command prompt. I can do this on my own machine during development, but if an application using the provider is deployed to other machines - what then?</p> <p>It seems that this RunInstaller / DefaultManagementInstaller combination is not working properly - correct?</p>
[ { "answer_id": 373748, "author": "David Gardiner", "author_id": 25702, "author_profile": "https://Stackoverflow.com/users/25702", "pm_score": 1, "selected": false, "text": " public static void Run( Type type )\n {\n // Register WMI stuff\n var installArgs = new[]\n {\n string.Format( \"//logfile={0}\", @\"c:\\Temp\\sample.InstallLog\" ), \"//LogToConsole=false\", \"//ShowCallStack\",\n type.Assembly.Location,\n };\n\n ManagedInstallerClass.InstallHelper( installArgs );\n }\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
163,004
<p>Say I have two tables I want to join. Categories:</p> <pre><code>id name ---------- 1 Cars 2 Games 3 Pencils </code></pre> <p>And items:</p> <pre><code>id categoryid itemname --------------------------- 1 1 Ford 2 1 BMW 3 1 VW 4 2 Tetris 5 2 Pong 6 3 Foobar Pencil Factory </code></pre> <p>I want a query that returns the category and the first (and only the first) itemname:</p> <pre><code>category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 1 Ford 2 Games 4 Tetris 3 Pencils 6 Foobar Pencil Factory </code></pre> <p>And is there a way I could get random results like:</p> <pre><code>category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 3 VW 2 Games 5 Pong 3 Pencils 6 Foobar Pencil Factory </code></pre> <p>Thanks!</p>
[ { "answer_id": 163051, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 0, "selected": false, "text": " select category.id, category.name, itemid, itemname\n inner join \n (select item.categoryid, item.id as itemid, item.name as itemname\n from item group by categoryid)\n on category.id = categoryid\n select category.id, category.name, itemid, itemname\ninner join \n (select item.categoryid, min(item.id) as itemid, item.name as itemname\n from items\n group by item.categoryid)\non category.id = categoryid\n" }, { "answer_id": 163087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "mysql> select * from categories c, items i\n -> where i.categoryid = c.id\n -> group by c.id;\n+------+---------+------+------------+----------------+\n| id | name | id | categoryid | name |\n+------+---------+------+------------+----------------+\n| 1 | Cars | 1 | 1 | Ford |\n| 2 | Games | 4 | 2 | Tetris |\n| 3 | Pencils | 6 | 3 | Pencil Factory |\n+------+---------+------+------------+----------------+\n3 rows in set (0.00 sec)\n" }, { "answer_id": 222707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select * \nfrom categories c, items i\nwhere i.categoryid = c.id\ngroup by c.id;\n select categories.id, categories.name, items.id, items.name\nfrom categories inner join\n items on items.categoryid = categories.id and \n items.id = (select min(items2.id) from items as items2 where items2.categoryid = category.id)\n select categories.id, categories.name, items.id, items.name\n from categories inner join\n items on items.categoryid = categories.id and \n items.id = (select items2.id from items as items2 where items2.categoryid = category.id order by rand() limit 1)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
163,009
<p>If I open a file using urllib2, like so:</p> <pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip') </code></pre> <p>Is there an easy way to get the file name other then parsing the original URL?</p> <p>EDIT: changed openfile to urlopen... not sure how that happened.</p> <p>EDIT2: I ended up using:</p> <pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0] </code></pre> <p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
[ { "answer_id": 163093, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "urllib2.urlopen openfile urllib2 urllib2.urlparse >>> from urllib2 import urlparse\n>>> print urlparse.urlsplit('http://example.com/somefile.zip')\n('http', 'example.com', '/somefile.zip', '', '')\n" }, { "answer_id": 163094, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 3, "selected": false, "text": "remotefile.headers['Content-Disposition']" }, { "answer_id": 163095, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "remotefile.info()['Content-Disposition'] urlparse.urlsplit >>> urlparse.urlsplit('http://example.com/somefile.zip')\n('http', 'example.com', '/somefile.zip', '', '')\n>>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')\n('http', 'example.com', '/somedir/somefile.zip', '', '')\n >>> 'http://example.com/somefile.zip'.split('/')[-1]\n'somefile.zip'\n>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]\n'somefile.zip'\n" }, { "answer_id": 163107, "author": "miracle2k", "author_id": 15677, "author_profile": "https://Stackoverflow.com/users/15677", "pm_score": 1, "selected": false, "text": "urlparse In [9]: urlparse.urlparse('http://example.com/somefile.zip')\nOut[9]: ('http', 'example.com', '/somefile.zip', '', '', '')\n" }, { "answer_id": 163108, "author": "user15453", "author_id": 15453, "author_profile": "https://Stackoverflow.com/users/15453", "pm_score": 0, "selected": false, "text": "import os,urllib2\nresp = urllib2.urlopen('http://www.example.com/index.html')\nmy_url = resp.geturl()\n\nos.path.split(my_url)[1]\n\n# 'index.html'\n" }, { "answer_id": 163111, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 1, "selected": false, "text": " url = 'http://example.com/somefile.zip'\nprint url.split('/')[-1]\n url = 'http://example.com/somefile.zip'\n" }, { "answer_id": 163202, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "[user@host]$ python\nPython 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) \nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> os.path.basename(\"http://example.com/somefile.zip\")\n'somefile.zip'\n>>> os.path.basename(\"http://example.com/somedir/somefile.zip\")\n'somefile.zip'\n>>> os.path.basename(\"http://example.com/somedir/somefile.zip?foo=bar\")\n'somefile.zip?foo=bar'\n" }, { "answer_id": 15733928, "author": "Filipe Correia", "author_id": 684253, "author_profile": "https://Stackoverflow.com/users/684253", "pm_score": 2, "selected": false, "text": "urlsplit url = 'http://example.com/somefile.zip'\nurlparse.urlsplit(url).path.split('/')[-1]\n" }, { "answer_id": 22053032, "author": "DoomedRaven", "author_id": 1294762, "author_profile": "https://Stackoverflow.com/users/1294762", "pm_score": 0, "selected": false, "text": "import requests\nfrom urllib import unquote\nfrom urlparse import urlparse\n\nsample = requests.get(url)\n\nif sample.status_code == 200:\n #has_key not work here, and this help avoid problem with names\n\n if filename == False:\n\n if 'content-disposition' in sample.headers.keys():\n filename = sample.headers['content-disposition'].split('filename=')[-1].replace('\"','').replace(';','')\n\n else:\n\n filename = urlparse(sample.url).query.split('/')[-1].split('=')[-1].split('&')[-1]\n\n if not filename:\n\n if url.split('/')[-1] != '':\n filename = sample.url.split('/')[-1].split('=')[-1].split('&')[-1]\n filename = unquote(filename)\n" }, { "answer_id": 29173617, "author": "TMF Wolfman", "author_id": 4695284, "author_profile": "https://Stackoverflow.com/users/4695284", "pm_score": 3, "selected": false, "text": "filename = url.split(\"?\")[0].split(\"/\")[-1]\n" }, { "answer_id": 30160719, "author": "Régis B.", "author_id": 356528, "author_profile": "https://Stackoverflow.com/users/356528", "pm_score": 2, "selected": false, "text": "os.path.basename result.url import os\nimport urllib2\nresult = urllib2.urlopen(url)\nreal_url = urllib2.urlparse.urlparse(result.url)\nfilename = os.path.basename(real_url.path)\n" }, { "answer_id": 32512647, "author": "Vovan Kuznetsov", "author_id": 4619036, "author_profile": "https://Stackoverflow.com/users/4619036", "pm_score": 0, "selected": false, "text": "In [26]: import re\nIn [27]: pat = re.compile('.+[\\/\\?#=]([\\w-]+\\.[\\w-]+(?:\\.[\\w-]+)?$)')\nIn [28]: test_set \n\n['http://www.google.com/a341.tar.gz',\n 'http://www.google.com/a341.gz',\n 'http://www.google.com/asdasd/aadssd.gz',\n 'http://www.google.com/asdasd?aadssd.gz',\n 'http://www.google.com/asdasd#blah.gz',\n 'http://www.google.com/asdasd?filename=xxxbl.gz']\n\nIn [30]: for url in test_set:\n ....: match = pat.match(url)\n ....: if match and match.groups():\n ....: print(match.groups()[0])\n ....: \n\na341.tar.gz\na341.gz\naadssd.gz\naadssd.gz\nblah.gz\nxxxbl.gz\n" }, { "answer_id": 36557581, "author": "Adam Nelson", "author_id": 26235, "author_profile": "https://Stackoverflow.com/users/26235", "pm_score": 0, "selected": false, "text": ">>> from pathlib import PurePosixPath\n>>> path = PurePosixPath('http://example.com/somefile.zip')\n>>> path.name\n'somefile.zip'\n>>> path = PurePosixPath('http://example.com/nested/somefile.zip')\n>>> path.name\n'somefile.zip'\n" }, { "answer_id": 36917997, "author": "Yth", "author_id": 6077892, "author_profile": "https://Stackoverflow.com/users/6077892", "pm_score": 2, "selected": false, "text": ">>> remotefile=urllib2.urlopen(url)\n>>> try:\n>>> filename=remotefile.info()['Content-Disposition']\n>>> except KeyError:\n>>> filename=os.path.basename(urllib2.urlparse.urlsplit(url).path)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ]
163,022
<p>I'd like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs that I haven't yet found.</p>
[ { "answer_id": 163089, "author": "ChronoPositron", "author_id": 19127, "author_profile": "https://Stackoverflow.com/users/19127", "pm_score": 1, "selected": false, "text": "[DllImport(\"Kernel32.dll\")]\nprivate static extern bool QueryPerformanceCounter(out long lpPerformanceCount);\n BOOL QueryPerformanceCounter( \n LARGE_INTEGER *lpPerformanceCount\n);\n" }, { "answer_id": 163096, "author": "quickcel", "author_id": 9129, "author_profile": "https://Stackoverflow.com/users/9129", "pm_score": 7, "selected": true, "text": "Dim sw As New Stopwatch()\nsw.Start()\n//Insert Code To Time\nsw.Stop()\nDim ms As Long = sw.ElapsedMilliseconds\nConsole.WriteLine(\"Total Seconds Elapsed: \" & ms / 1000)\n Stopwatch sw = new Stopwatch();\nforeach(MyStuff stuff in _listOfMyStuff)\n{\n sw.Start();\n stuff.DoCoolCalculation();\n sw.Stop();\n}\nConsole.WriteLine(\"Total calculation time: {0}\", sw.Elapsed);\n" }, { "answer_id": 163125, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": false, "text": "[System.Runtime.InteropServices.DllImport(\"Kernel32.dll\")]\npublic static extern bool QueryPerformanceCounter(out long perfcount);\n\n[System.Runtime.InteropServices.DllImport(\"Kernel32.dll\")]\npublic static extern bool QueryPerformanceFrequency(out long freq);\n #region Query Performance Counter\n/// <summary>\n/// Gets the current 'Ticks' on the performance counter\n/// </summary>\n/// <returns>Long indicating the number of ticks on the performance counter</returns>\npublic static long QueryPerformanceCounter()\n{\n long perfcount;\n QueryPerformanceCounter(out perfcount);\n return perfcount;\n}\n#endregion\n\n#region Query Performance Frequency\n/// <summary>\n/// Gets the number of performance counter ticks that occur every second\n/// </summary>\n/// <returns>The number of performance counter ticks that occur every second</returns>\npublic static long QueryPerformanceFrequency()\n{\n long freq;\n QueryPerformanceFrequency(out freq);\n return freq;\n}\n#endregion\n long startCount = PerformanceCounter.QueryPerformanceCounter();\n// DoStuff();\nlong stopCount = PerformanceCounter.QueryPerformanceCounter();\nlong elapsedCount = stopCount - startCount;\ndouble elapsedSeconds = (double)elapsedCount / PerformanceCounter.QueryPerformanceFrequency();\nMessageBox.Show(String.Format(\"Took {0} Seconds\", Math.Round(elapsedSeconds, 6).ToString()));\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2973/" ]
163,058
<p>In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.</p> <p>I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?</p>
[ { "answer_id": 163062, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 5, "selected": false, "text": "g++ #if defined(_M_X64) || defined(__amd64__)\n // code...\n#endif\n" }, { "answer_id": 164015, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "#ifdef _WIN64\n #ifdef WIN64\n" }, { "answer_id": 176667, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#ifdef _LP64\n" }, { "answer_id": 551215, "author": "flodin", "author_id": 66620, "author_profile": "https://Stackoverflow.com/users/66620", "pm_score": 4, "selected": true, "text": "sizeof(void*) == 8 sizeof(int) == 8" }, { "answer_id": 10151452, "author": "SameOldNick", "author_id": 533242, "author_profile": "https://Stackoverflow.com/users/533242", "pm_score": -1, "selected": false, "text": " if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SYSTEM\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment\"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) {\n LPSTR szArch = new CHAR[100];\n\n ZeroMemory(szArch, 100);\n\n if (RegQueryValueEx(hKey, _T(\"PROCESSOR_ARCHITECTURE\"), NULL, NULL, (LPBYTE)szArch, &dwSize) == ERROR_SUCCESS) {\n if (strcmp(szArch, \"AMD64\") == 0)\n this->nArchitecture = 64;\n else\n this->nArchitecture = 32;\n } else {\n this->nArchitecture = (sizeof(PVOID) == 4 ? 32 : 64);\n }\n\n RegCloseKey(hKey);\n }\n" }, { "answer_id": 32717129, "author": "DarkDust", "author_id": 400056, "author_profile": "https://Stackoverflow.com/users/400056", "pm_score": 5, "selected": false, "text": "// C\n#include <stdint.h>\n\n// C++\n#include <cstdint>\n\n#if INTPTR_MAX == INT64_MAX\n// 64-bit\n#elif INTPTR_MAX == INT32_MAX\n// 32-bit\n#else\n#error Unknown pointer size or missing size macros!\n#endif\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5861/" ]
163,071
<p>The <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="noreferrer">Law of Demeter</a> indicates that you should only speak to objects that you know about directly. That is, do not perform method chaining to talk to other objects. When you do so, you are establishing improper linkages with the intermediary objects, inappropriately <a href="http://en.wikipedia.org/wiki/Coupling_(computer_science)" rel="noreferrer">coupling</a> your code to other code.</p> <p>That's bad.</p> <p>The solution would be for the class you do know about to essentially expose simple wrappers that delegate the responsibility to the object it has the relationship with.</p> <p>That's good.</p> <p>But, that seems to result in the class having low <a href="http://en.wikipedia.org/wiki/Cohesion_(computer_science)" rel="noreferrer">cohesion</a>. No longer is it simply responsible for precisely what it does, but it also has the delegates that in a sense, making the code less cohesive by duplicating portions of the interface of its related object.</p> <p>That's bad.</p> <p>Does it really result in lowering cohesion? Is it the lesser of two evils?</p> <p>Is this one of those gray areas of development, where you can debate where the line is, or are there strong, principled ways of making a decision of where to draw the line and what criteria you can use to make that decision?</p>
[ { "answer_id": 163139, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": false, "text": "int price = customer.getOrder().getPrice();\n int price = customer.getOrderPrice();\n" }, { "answer_id": 163180, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 3, "selected": false, "text": "class Person Date Address Education Person Person Person" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10737/" ]
163,079
<p>Is there a tool to migrate an <a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> database to <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a> (both the structure and data)?</p>
[ { "answer_id": 163136, "author": "Nathan Clark", "author_id": 1331, "author_profile": "https://Stackoverflow.com/users/1331", "pm_score": 3, "selected": false, "text": ".dump" }, { "answer_id": 28151420, "author": "AlbanMar31", "author_id": 4459356, "author_profile": "https://Stackoverflow.com/users/4459356", "pm_score": 3, "selected": false, "text": "sqlite3 DB_name .dump > DB_name.sql\n" }, { "answer_id": 32948917, "author": "Krivers", "author_id": 1756072, "author_profile": "https://Stackoverflow.com/users/1756072", "pm_score": 4, "selected": false, "text": "USE [master]\nGO\nEXEC sp_addlinkedserver \n @server = 'OldSQLite', -- connection name\n @srvproduct = '', -- Can be blank but not NULL\n @provider = 'MSDASQL', \n @datasrc = 'SQLiteDNSName' -- name of the system DSN connection \nGO\n SELECT * INTO SQLServerDATA FROM openquery(SQLiteDNSName, 'select * from SQLiteData')\n" }, { "answer_id": 40463757, "author": "R.Alonso", "author_id": 3639720, "author_profile": "https://Stackoverflow.com/users/3639720", "pm_score": 0, "selected": false, "text": " public static Boolean SqLite2SqlServer(string sqlitePath, string connStringSqlServer)\n {\n String SqlInsert;\n int i;\n try\n {\n\n string sql = \"select * from sqlite_master where type = 'table' and name like 'YouTable in SQL'\";\n string password = null;\n string sql2run;\n string tabla;\n string sqliteConnString = CreateSQLiteConnectionString(sqlitePath, password);\n //sqliteConnString = \"data source=C:\\\\pro\\\\testconverter\\\\Origen\\\\FACTUNETWEB.DB;page size=4096;useutf16encoding=True\";\n\n using (SQLiteConnection sqconn = new SQLiteConnection(sqliteConnString))\n {\n\n\n\n sqconn.Open();\n\n SQLiteCommand command = new SQLiteCommand(sql, sqconn);\n SQLiteDataReader reader = command.ExecuteReader();\n\n SqlConnection conn = new SqlConnection(connStringSqlServer);\n conn.Open();\n while (reader.Read())\n {\n //Console.WriteLine(\"Name: \" + reader[\"name\"] + \"\\tScore: \" + reader[\"score\"]);\n sql2run = \"\" + reader[\"sql\"];\n tabla = \"\" + reader[\"name\"];\n\n /*\n sql2run = \"Drop table \" + tabla;\n SqlCommand cmd = new SqlCommand(sql2run, conn); \n cmd.ExecuteNonQuery();\n */\n\n\n\n sql2run = sql2run.Replace(\"COLLATE NOCASE\", \"\");\n sql2run = sql2run.Replace(\" NUM\", \" TEXT\");\n SqlCommand cmd2 = new SqlCommand(sql2run, conn);\n cmd2.ExecuteNonQuery();\n\n\n // insertar los datos.\n string sqlCmd = \"Select * From \" + tabla;\n SQLiteCommand cmd = new SQLiteCommand(sqlCmd, sqconn);\n SQLiteDataReader rs = cmd.ExecuteReader();\n String valor = \"\";\n String Valores = \"\";\n String Campos = \"\";\n String Campo = \"\";\n while (rs.Read())\n {\n SqlInsert = \"INSERT INTO \" + tabla;\n Campos = \"\";\n Valores = \"\";\n for ( i = 0; i < rs.FieldCount ; i++)\n {\n\n //valor = \"\" + rs.GetString(i);\n //valor = \"\" + rs.GetName(i);\n Campo = \"\" + rs.GetName(i);\n valor = \"\" + rs.GetValue(i);\n\n if (Valores != \"\")\n {\n Valores = Valores + ',';\n Campos = Campos + ',';\n }\n Valores = Valores + \"'\" + valor + \"'\";\n Campos = Campos + Campo;\n }\n SqlInsert = SqlInsert + \"(\" + Campos + \") Values (\" + Valores + \")\";\n SqlCommand cmdInsert = new SqlCommand(SqlInsert, conn);\n cmdInsert.ExecuteNonQuery();\n\n\n }\n\n\n }\n\n }\n return true;\n } //END TRY\n catch (Exception ex)\n {\n _log.Error(\"unexpected exception\", ex);\n\n throw;\n\n } // catch\n }\n" }, { "answer_id": 56662652, "author": "caopeng", "author_id": 1844537, "author_profile": "https://Stackoverflow.com/users/1844537", "pm_score": 0, "selected": false, "text": "adb root\nadb shell\ncd /data/com.xxx.package/databases/\nsqlite3 db_name .dump >dump.sql\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7793/" ]
163,092
<p>In Ruby you can easily set a default value for a variable </p> <pre><code>x ||= "default" </code></pre> <p>The above statement will set the value of x to "default" if x is nil or false</p> <p>Is there a similar shortcut in PHP or do I have to use the longer form:</p> <pre><code>$x = (isset($x))? $x : "default"; </code></pre> <p>Are there any easier ways to handle this in PHP?</p>
[ { "answer_id": 163123, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 3, "selected": false, "text": "isset($x) or $x = 'default';\n" }, { "answer_id": 163901, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 2, "selected": false, "text": "function default($value, $default) {\n return $value ? $value : $default;\n}\n// then use it like:\n$x=default($x, 'default');\n" }, { "answer_id": 4886395, "author": "igorw", "author_id": 289985, "author_profile": "https://Stackoverflow.com/users/289985", "pm_score": 6, "selected": false, "text": "$x = $x ?: 'default';\n" }, { "answer_id": 51987885, "author": "Machavity", "author_id": 2370483, "author_profile": "https://Stackoverflow.com/users/2370483", "pm_score": 4, "selected": false, "text": "// PHP version < 7.0, using a standard ternary\n$x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';\n// PHP version >= 7.0\n$x = $_GET['y'] ?? 'not set';\n" }, { "answer_id": 72278101, "author": "Roman", "author_id": 913761, "author_profile": "https://Stackoverflow.com/users/913761", "pm_score": 2, "selected": false, "text": "$x ??= \"default\";\n $x null" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
163,098
<p>I have several databases where the transaction log (.LDF) is many times larger than the database file (.MDF).</p> <p>What can I do to automatically shrink these or keep them from getting so large?</p>
[ { "answer_id": 163193, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 0, "selected": false, "text": "USE yourdabatase\nSELECT * FROM sysfiles\n FileID … \n1 1 24264 -1 1280 1048578 0 yourdabatase_Data D:\\MSSQL_Services\\Data\\yourdabatase_Data.MDF\n2 0 128 -1 1280 66 0 yourdabatase_Log D:\\MSSQL_Services\\Data\\yourdabatase_Log.LDF\n Checkpoint\nGO\nCheckpoint\nGO\n DUMP TRAN yourdabatase WITH no_log \nDBCC SHRINKFILE(2,1) /*(FileID , the new size = 1 Mb)*/\n" }, { "answer_id": 163218, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 4, "selected": true, "text": "use master\ngo\ndump transaction <YourDBName> with no_log\ngo\nuse <YourDBName>\ngo\nDBCC SHRINKFILE (<YourDBNameLogFileName>, 100) -- where 100 is the size you may want to shrink it to in MB, change it to your needs\ngo\n-- then you can call to check that all went fine\ndbcc checkdb(<YourDBName>)\n" }, { "answer_id": 163340, "author": "spinner_den_g", "author_id": 2605028, "author_profile": "https://Stackoverflow.com/users/2605028", "pm_score": 0, "selected": false, "text": "BACKUP LOG <CatalogName> with TRUNCATE_ONLY\nDBCC SHRINKDATABASE (<CatalogName>, 1)\nuse <CatalogName>\ngo\nDBCC SHRINKFILE(<CatalogName_logName>,1)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2926/" ]
163,104
<p>Is there any way for the main form to be able to intercept events firing on a subcontrol on a user control?</p> <p>I've got a custom user-control embedded in the main Form of my application. The control contains various subcontrols that manipulate data, which itself is displayed by other controls on the main form. What I'd like is if the main form could be somehow informed when the user changes subcontrols, so I could update the data and the corresponding display elsewhere.</p> <p>Right now, I am cheating. I have a delegate hooked up to the focus-leaving event of the subcontrols. This delegate changes a property of the user-control I'm not using elsewhere (in this cause, CausesValidation). I then have a delegate defined on the main form for when the CausesValidation property of the user control changes, which then directs the app to update the data and display.</p> <p>A problem arises because I also have a delegate set up for when focus leaves the user-control, because I need to validate the fields in the user-control before I can allow the user to do anything else. However, if the user is just switching between subcontrols, I don't want to validate, because they might not be done editing.</p> <p>Basically, I want the data to update when the user switches subcontrols OR leaves the user control, but not validate. When the user leaves the control, I want to update AND validate. Right now, leaving the user-control causes validation to fire twice.</p>
[ { "answer_id": 163255, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 5, "selected": true, "text": "UserControl UserControl1 UserControl TextBox1 UserControl ControlChanged UserControl TextBox1 TextChangeEvent ControlChanged Form1 UserControl1 UserControl1 MouseLeave ControlChanged ControlChanged UserControl" }, { "answer_id": 2540285, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 2, "selected": false, "text": "// CustomControl.cs\n// Assumes a Button 'myButton' has been added through the designer\n\n// we need a delegate definition to type our event\npublic delegate void ButtonClickHandler(object sender, EventArgs e);\n\n// declare the public event that other classes can subscribe to\npublic event ButtonClickHandler ButtonClickEvent;\n\n// wire up the internal button click event to trigger our custom event\nthis.myButton.Click += new System.EventHandler(this.myButton_Click);\npublic void myButton_Click(object sender, EventArgs e)\n{\n if (ButtonClickEvent != null)\n {\n ButtonClickEvent(sender, e);\n }\n}\n // CustomForm.cs\n// Assumes a CustomControl 'myCustomControl' has been added through the desinger\nthis.myCustomControl.ButtonClickEvent += new System.EventHandler(this.myCustomControl_ButtonClickEvent);\nmyCustomControl_ButtonClickEvent(object sender, EventArgs e)\n{\n // do something with the newly bubbled event\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24529/" ]
163,162
<p>I am trying to use the <code>Directory.GetFiles()</code> method to retrieve a list of files of multiple types, such as <code>mp3</code>'s and <code>jpg</code>'s. I have tried both of the following with no luck:</p> <pre><code>Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories); Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories); </code></pre> <p>Is there a way to do this in one call?</p>
[ { "answer_id": 163203, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 3, "selected": false, "text": "List<string> _searchPatternList = new List<string>();\n ...\n List<string> fileList = new List<string>();\n foreach ( string ext in _searchPatternList )\n {\n foreach ( string subFile in Directory.GetFiles( folderName, ext )\n {\n fileList.Add( subFile );\n }\n }\n\n // Sort alpabetically\n fileList.Sort();\n\n // Add files to the file browser control \n foreach ( string fileName in fileList )\n {\n ...;\n }\n" }, { "answer_id": 163220, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 10, "selected": true, "text": "var files = Directory.EnumerateFiles(\"C:\\\\path\", \"*.*\", SearchOption.AllDirectories)\n .Where(s => s.EndsWith(\".mp3\") || s.EndsWith(\".jpg\"));\n var files = Directory.GetFiles(\"C:\\\\path\", \"*.*\", SearchOption.AllDirectories)\n .Where(s => s.EndsWith(\".mp3\") || s.EndsWith(\".jpg\"));\n" }, { "answer_id": 163505, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "private void getFiles(string path)\n{\n foreach (string s in Array.FindAll(Directory.GetFiles(path, \"*\", SearchOption.AllDirectories), predicate_FileMatch))\n {\n Debug.Print(s);\n }\n}\n\nprivate bool predicate_FileMatch(string fileName)\n{\n if (fileName.EndsWith(\".mp3\"))\n return true;\n if (fileName.EndsWith(\".jpg\"))\n return true;\n return false;\n}\n" }, { "answer_id": 2945136, "author": "Alexander Popov", "author_id": 246473, "author_profile": "https://Stackoverflow.com/users/246473", "pm_score": 2, "selected": false, "text": "private string[] FindFiles(string directory, string filters, SearchOption searchOption)\n{\n if (!Directory.Exists(directory)) return new string[] { };\n\n var include = (from filter in filters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim());\n var exclude = (from filter in include where filter.Contains(@\"!\") select filter);\n\n include = include.Except(exclude);\n\n if (include.Count() == 0) include = new string[] { \"*\" };\n\n var rxfilters = from filter in exclude select string.Format(\"^{0}$\", filter.Replace(\"!\", \"\").Replace(\".\", @\"\\.\").Replace(\"*\", \".*\").Replace(\"?\", \".\"));\n Regex regex = new Regex(string.Join(\"|\", rxfilters.ToArray()));\n\n List<Thread> workers = new List<Thread>();\n List<string> files = new List<string>();\n\n foreach (string filter in include)\n {\n Thread worker = new Thread(\n new ThreadStart(\n delegate\n {\n string[] allfiles = Directory.GetFiles(directory, filter, searchOption);\n if (exclude.Count() > 0)\n {\n lock (files)\n files.AddRange(allfiles.Where(p => !regex.Match(p).Success));\n }\n else\n {\n lock (files)\n files.AddRange(allfiles);\n }\n }\n ));\n\n workers.Add(worker);\n\n worker.Start();\n }\n\n foreach (Thread worker in workers)\n {\n worker.Join();\n }\n\n return files.ToArray();\n\n}\n foreach (string file in FindFiles(@\"D:\\628.2.11\", @\"!*.config, !*.js\", SearchOption.AllDirectories))\n {\n Console.WriteLine(file);\n }\n" }, { "answer_id": 3707149, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 3, "selected": false, "text": "var set = new HashSet<string> { \".mp3\", \".jpg\" };\n Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories)\n .Where(f => set.Contains(\n new FileInfo(f).Extension,\n StringComparer.OrdinalIgnoreCase));\n from file in Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories)\nfrom ext in set\nwhere String.Equals(ext, new FileInfo(file).Extension, StringComparison.OrdinalIgnoreCase)\nselect file;\n" }, { "answer_id": 3740401, "author": "Rajeesh Kuthuparakkal", "author_id": 451211, "author_profile": "https://Stackoverflow.com/users/451211", "pm_score": 3, "selected": false, "text": "List<string> FileList = new List<string>();\nDirectoryInfo di = new DirectoryInfo(\"C:\\\\DirName\");\n\nIEnumerable<FileInfo> fileList = di.GetFiles(\"*.*\");\n\n//Create the query\nIEnumerable<FileInfo> fileQuery = from file in fileList\n where (file.Extension.ToLower() == \".jpg\" || file.Extension.ToLower() == \".png\")\n orderby file.LastWriteTime\n select file;\n\nforeach (System.IO.FileInfo fi in fileQuery)\n{\n fi.Attributes = FileAttributes.Normal;\n FileList.Add(fi.FullName);\n}\n" }, { "answer_id": 4617227, "author": "jnoreiga", "author_id": 516492, "author_profile": "https://Stackoverflow.com/users/516492", "pm_score": 5, "selected": false, "text": "string supportedExtensions = \"*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08\";\nforeach (string imageFile in Directory.GetFiles(_tempDirectory, \"*.*\", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))\n{\n //do work here\n}\n" }, { "answer_id": 8280070, "author": "eduardomozart", "author_id": 1031340, "author_profile": "https://Stackoverflow.com/users/1031340", "pm_score": 3, "selected": false, "text": ".Where .CaB .cab string[] ext = new string[2] { \"*.CAB\", \"*.MSU\" };\n\nforeach (string found in ext)\n{\n string[] extracted = Directory.GetFiles(\"C:\\\\test\", found, System.IO.SearchOption.AllDirectories);\n\n foreach (string file in extracted)\n {\n Console.WriteLine(file);\n }\n}\n" }, { "answer_id": 8363526, "author": "Dave Rael", "author_id": 490500, "author_profile": "https://Stackoverflow.com/users/490500", "pm_score": 4, "selected": false, "text": "var files = Directory.GetFiles(\"C:\\\\path\", \"*.mp3\", SearchOption.AllDirectories).Union(Directory.GetFiles(\"C:\\\\path\", \"*.jpg\", SearchOption.AllDirectories));\n GetFiles()" }, { "answer_id": 8466982, "author": "Albert", "author_id": 182888, "author_profile": "https://Stackoverflow.com/users/182888", "pm_score": 6, "selected": false, "text": "private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption)\n{\n return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray();\n}\n" }, { "answer_id": 8516496, "author": "A.Ramazani", "author_id": 1099337, "author_profile": "https://Stackoverflow.com/users/1099337", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Returns the names of files in a specified directories that match the specified patterns using LINQ\n/// </summary>\n/// <param name=\"srcDirs\">The directories to seach</param>\n/// <param name=\"searchPatterns\">the list of search patterns</param>\n/// <param name=\"searchOption\"></param>\n/// <returns>The list of files that match the specified pattern</returns>\npublic static string[] GetFilesUsingLINQ(string[] srcDirs,\n string[] searchPatterns,\n SearchOption searchOption = SearchOption.AllDirectories)\n{\n var r = from dir in srcDirs\n from searchPattern in searchPatterns\n from f in Directory.GetFiles(dir, searchPattern, searchOption)\n select f;\n\n return r.ToArray();\n}\n" }, { "answer_id": 9984667, "author": "Evado", "author_id": 1309151, "author_profile": "https://Stackoverflow.com/users/1309151", "pm_score": 2, "selected": false, "text": "string myExtensions=\".jpg.mp3\";\n\nstring[] files=System.IO.Directory.GetFiles(\"C:\\myfolder\");\n\nforeach(string file in files)\n{\n if(myExtensions.ToLower().contains(System.IO.Path.GetExtension(s).ToLower()))\n {\n //this file has passed, do something with this file\n\n }\n}\n" }, { "answer_id": 12927028, "author": "Icehunter", "author_id": 1751967, "author_profile": "https://Stackoverflow.com/users/1751967", "pm_score": 4, "selected": false, "text": "var files = Directory.GetFiles(\"path_to_files\").Where(file => Regex.IsMatch(file, @\"^.+\\.(wav|mp3|txt)$\"));\n" }, { "answer_id": 13719160, "author": "Quispie", "author_id": 1758886, "author_profile": "https://Stackoverflow.com/users/1758886", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Get all files with a specific extension\n/// </summary>\n/// <param name=\"extensionsToCompare\">string list of all the extensions</param>\n/// <param name=\"Location\">string of the location</param>\n/// <returns>array of all the files with the specific extensions</returns>\npublic string[] GetFiles(List<string> extensionsToCompare, string Location)\n{\n List<string> files = new List<string>();\n foreach (string file in Directory.GetFiles(Location))\n {\n if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);\n }\n files.Sort();\n return files.ToArray();\n}\n Directory.Getfiles() string[] images = GetFiles(new List<string>{\"jpg\", \"png\", \"gif\"}, \"imageFolder\");\n /// <summary>\n /// Get the file with a specific name and extension\n /// </summary>\n /// <param name=\"filename\">the name of the file to find</param>\n /// <param name=\"extensionsToCompare\">string list of all the extensions</param>\n /// <param name=\"Location\">string of the location</param>\n /// <returns>file with the requested filename</returns>\n public string GetFile( string filename, List<string> extensionsToCompare, string Location)\n {\n foreach (string file in Directory.GetFiles(Location))\n {\n if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &&& file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename) \n return file;\n }\n return \"\";\n }\n string image = GetFile(\"imagename\", new List<string>{\"jpg\", \"png\", \"gif\"}, \"imageFolder\");\n" }, { "answer_id": 15571040, "author": "Bas1l", "author_id": 2029962, "author_profile": "https://Stackoverflow.com/users/2029962", "pm_score": 4, "selected": false, "text": "string[] filters = new[]{\"*.jpg\", \"*.png\", \"*.gif\"};\nstring[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();\n" }, { "answer_id": 16101684, "author": "Nilesh Padhiyar", "author_id": 2298661, "author_profile": "https://Stackoverflow.com/users/2298661", "pm_score": 3, "selected": false, "text": "DirectoryInfo directory = new DirectoryInfo(Server.MapPath(\"~/Contents/\"));\n\n//Using Union\n\nFileInfo[] files = directory.GetFiles(\"*.xlsx\")\n .Union(directory\n .GetFiles(\"*.csv\"))\n .ToArray();\n" }, { "answer_id": 19961761, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 5, "selected": false, "text": "var exts = new[] { \"mp3\", \"jpg\" };\n public IEnumerable<string> FilterFiles(string path, params string[] exts) {\n return\n Directory\n .EnumerateFiles(path, \"*.*\")\n .Where(file => exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));\n}\n Directory.EnumerateFiles .EndsWith(\"aspx\", StringComparison.OrdinalIgnoreCase) .ToLower().EndsWith(\"aspx\") EnumerateFiles public IEnumerable<string> FilterFiles(string path, params string[] exts) {\n return \n exts.Select(x => \"*.\" + x) // turn into globs\n .SelectMany(x => \n Directory.EnumerateFiles(path, x)\n );\n}\n exts = new[] {\"*.mp3\", \"*.jpg\"} Perf" }, { "answer_id": 22947900, "author": "user3512661", "author_id": 3512661, "author_profile": "https://Stackoverflow.com/users/3512661", "pm_score": 1, "selected": false, "text": "vector <string> extensions = { \"*.mp4\", \"*.avi\", \"*.flv\" };\nfor (int i = 0; i < extensions.size(); ++i)\n{\n String^ ext = gcnew String(extensions[i].c_str());;\n String^ path = \"C:\\\\Users\\\\Eric\\\\Videos\";\n array<String^>^files = Directory::GetFiles(path,ext);\n Console::WriteLine(ext);\n cout << \" \" << (files->Length) << endl;\n}\n" }, { "answer_id": 25643193, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 3, "selected": false, "text": "public static List<string> GetFilez(string path, System.IO.SearchOption opt, params string[] patterns)\n{\n List<string> filez = new List<string>();\n foreach (string pattern in patterns)\n {\n filez.AddRange(\n System.IO.Directory.GetFiles(path, pattern, opt)\n );\n }\n\n\n // filez.Sort(); // Optional\n return filez; // Optional: .ToArray()\n}\n foreach (string fn in GetFilez(path\n , System.IO.SearchOption.AllDirectories\n , \"*.xml\", \"*.xml.rels\", \"*.rels\"))\n{}\n" }, { "answer_id": 30381302, "author": "MattyMerrix", "author_id": 3416222, "author_profile": "https://Stackoverflow.com/users/3416222", "pm_score": 2, "selected": false, "text": "string[] filesPNG = Directory.GetFiles(path, \"*.png\");\nstring[] filesJPG = Directory.GetFiles(path, \"*.jpg\");\nstring[] filesJPEG = Directory.GetFiles(path, \"*.jpeg\");\n\nint totalArraySizeAll = filesPNG.Length + filesJPG.Length + filesJPEG.Length;\nList<string> filesAll = new List<string>(totalArraySizeAll);\nfilesAll.AddRange(filesPNG);\nfilesAll.AddRange(filesJPG);\nfilesAll.AddRange(filesJPEG);\n" }, { "answer_id": 45012513, "author": "elle0087", "author_id": 3061212, "author_profile": "https://Stackoverflow.com/users/3061212", "pm_score": 1, "selected": false, "text": "String[] ext = \"*.ext1|*.ext2\".Split('|');\n\n List<String> files = new List<String>();\n foreach (String tmp in ext)\n {\n files.AddRange(Directory.GetFiles(dir, tmp, SearchOption.AllDirectories));\n }\n" }, { "answer_id": 48805134, "author": "Crusha K. Rool", "author_id": 7024019, "author_profile": "https://Stackoverflow.com/users/7024019", "pm_score": 3, "selected": false, "text": "Microsoft.VisualBasic.FileIO.FileSystem.GetFiles(\"C:\\\\path\", Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, new string[] {\"*.mp3\", \"*.jpg\"});\n My.Computer.FileSystem.GetFiles(\"C:\\path\", FileIO.SearchOption.SearchAllSubDirectories, {\"*.mp3\", \"*.jpg\"})\n Directory.EnumerateFiles()" }, { "answer_id": 62342701, "author": "JohnnBlade", "author_id": 588189, "author_profile": "https://Stackoverflow.com/users/588189", "pm_score": 2, "selected": false, "text": "var allowedFileExtensions = \".csv,.txt\";\n\n\nvar files = Directory.EnumerateFiles(@\"C:\\MyFolder\", \"*.*\", SearchOption.TopDirectoryOnly)\n .Where(s => allowedFileExtensions.IndexOf(Path.GetExtension(s)) > -1).ToArray(); \n" }, { "answer_id": 72497345, "author": "hossein sedighian", "author_id": 10143546, "author_profile": "https://Stackoverflow.com/users/10143546", "pm_score": 0, "selected": false, "text": "public static class Collectables {\n public static List<System.IO.FileInfo> FilesViaPattern(this System.IO.DirectoryInfo fldr, string pattern) {\n var filter = pattern.Split(\" \");\n return fldr.GetFiles( \"*.*\", System.IO.SearchOption.AllDirectories)\n .Where(l => filter.Any(k => l.Name.EndsWith(k))).ToList();\n }\n}\n new System.IO.DirectoryInfo(\"c:\\\\test\").FilesViaPattern(\"txt doc any.extension\");\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
163,183
<p>I'm encountering some peculiarities with LINQ to SQL.</p> <p>With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this:</p> <pre><code> var list = dataContext.MyLists.Single(x =&gt; x.ID == myId); var items = from i in list.MyItems select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query:</p> <pre><code> var items = from i in dataContext.MyLists select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>The first one runs fine, yet the second query yields a: </p> <p><em>Could not translate expression '...' into SQL and could not treat it as a local expression.</em></p> <p>If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values.</p> <p>Any ideas?</p> <p>Anthony</p>
[ { "answer_id": 163261, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description, \n item.CompleteDate, item.DueDate })\n .AsEnumerable() // Don't do the next bit in the DB\n .Select(item => new { item.ID, item.Sector, item.Description,\n CompleteDate = FormatDate(CompleteDate),\n DueDate = FormatDate(DueDate) });\n\n\nstatic string FormatDate(DateTime? date)\n{\n return date.HasValue ? date.Value.ToShortDateString() : \"\"\n}\n" }, { "answer_id": 163502, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 2, "selected": false, "text": " var items = from aList in dataContext.MyLists\n from i in aList.MyItems // Access the items in a list\n where aList.ID == myId // Use only the single desired list\n select\n new\n {\n i.ID,\n i.Sector,\n i.Description,\n CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : \"\",\n DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : \"\"\n };\n" }, { "answer_id": 2208024, "author": "rotary_engine", "author_id": 248869, "author_profile": "https://Stackoverflow.com/users/248869", "pm_score": 1, "selected": false, "text": "ToShortDateString()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
163,184
<p>I need to convert inline css style attributes to their HTML tag equivelants. The solution I have works but runs VERY slowly using the Microsoft .Net Regex namespace and long documents (~40 pages of html). I've tried several variations but with no useful results. I've done a little wrapping around executing the expressions but in the end it's just the built-in regex Replace method that gets called.</p> <p>I'm sure I'm abusing the greediness of the regex but I'm not sure of a way around it to achieve what I want using a single regex.</p> <p>I want to be able to run the following unit tests:</p> <pre><code>[Test] public void TestCleanReplacesFontWeightWithB() { string html = "&lt;font style=\"font-weight:bold\"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } [Test] public void TestCleanReplacesMultipleAttributesFontWeightWithB() { string html = "&lt;font style=\"font-weight:bold; color: blue; \"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } [Test] public void TestCleanReplaceAttributesBoldAndUnderlineWithHtml() { string html = "&lt;span style=\"font-weight:bold; color: blue; text-decoration: underline; \"&gt;Bold Text&lt;/span&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;u&gt;&lt;b&gt;Bold Text&lt;/b&gt;&lt;/u&gt;", html); } [Test] public void TestCleanReplaceAttributesBoldUnderlineAndItalicWithHtml() { string html = "&lt;span style=\"font-weight:bold; color: blue; font-style: italic; text-decoration: underline; \"&gt;Bold Text&lt;/span&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;u&gt;&lt;b&gt;&lt;i&gt;Bold Text&lt;/i&gt;&lt;/b&gt;&lt;/u&gt;", html); } [Test] public void TestCleanReplacesFontWeightWithSpaceWithB() { string html = "&lt;font size=\"10\" style=\"font-weight: bold\"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } </code></pre> <p>The regular expresion I am using to achieve this logic works but is VERY slow. The regex in the c# code looks like this:</p> <pre><code>public static IReplacePattern IncludeInlineItalicToITag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?font-style:\\s*italic[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;i&gt;$3&lt;/i&gt;&lt;/$2&gt;"); } public static IReplacePattern IncludeInlineBoldToBTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?font-weight:\\s*bold[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;b&gt;$3&lt;/b&gt;&lt;/$2&gt;"); } public static IReplacePattern IncludeInlineUnderlineToUTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?text-decoration:\\s*underline[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;u&gt;$3&lt;/u&gt;&lt;/$2&gt;"); } </code></pre>
[ { "answer_id": 163211, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "span font .\\*? [^>]\\*? .\\*? [^<]\\*?" }, { "answer_id": 163316, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<font style=\"font-weight: bold;\"> text1 <font color=\"blue\"> text2 </font> text3 </font>\n <b> text1 <font color=\"blue\"> text2 </b> text3 </font>\n (?<N>content) would push N onto a stack if content matches\n(?<-N>content) would pop N from the stack, if content matches.\n(?(N)yes|no) would match \"yes\" if N is on the stack, otherwise \"no\".\n" }, { "answer_id": 179920, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "\"(<(span|font) .*?style=\\\".*?font-style:\\\\s*italic[^>]*>)(.*?)</\\\\2>\", \"$1<i>$3</i></$2>\"\n \"(<span .*?style=\\\".*?font-style:\\\\s*italic[^>]*>)(.*?)</span>\", \"$1<i>$2</i></span>\"\n\"(<font .*?style=\\\".*?font-style:\\\\s*italic[^>]*>)(.*?)</font>\", \"$1<i>$2</i></font>\"\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
163,207
<p>I need to call a method that accepts a stream argument. The method loads text into the stream, which would normally be a file. I'd like to simply populate a string with the contents of the stream, instead of writing it to a file. How do I do this?</p>
[ { "answer_id": 163226, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": false, "text": "StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nCallYourMethodWhichWritesToYourStream(sw);\nreturn sb.ToString();\n" }, { "answer_id": 163233, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 4, "selected": true, "text": "using (MemoryStream ms = new MemoryStream())\nusing (StreamReader sr = new StreamReader(ms))\n{\n // pass the memory stream to method\n ms.Seek(0, SeekOrigin.Begin); // added from itsmatt\n string s = sr.ReadToEnd();\n}\n" }, { "answer_id": 163249, "author": "Tom", "author_id": 24227, "author_profile": "https://Stackoverflow.com/users/24227", "pm_score": 0, "selected": false, "text": "string s = \"Wahoo!\";\nint n = 452;\n\nusing( Stream stream = new MemoryStream() ) {\n // Write to the stream\n\n byte[] bytes1 = UnicodeEncoding.Unicode.GetBytes(s);\n byte[] bytes2 = BitConverter.GetBytes(n);\n stream.Write(bytes1, 0, bytes1.Length);\n stream.Write(bytes2, 0, bytes2.Length);\n" }, { "answer_id": 163329, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "MemoryStream ms = new MemoryStream();\nYourFunc(ms);\nms.Seek(0, SeekOrigin.Begin);\nStreamReader sr = new StreamReader(ms);\nstring mystring = sr.ReadToEnd();\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
163,246
<p>In Oracle, I can re-create a view with a single statement, as shown here:</p> <pre><code>CREATE OR REPLACE VIEW MY_VIEW AS SELECT SOME_FIELD FROM SOME_TABLE WHERE SOME_CONDITIONS </code></pre> <p>As the syntax implies, this will drop the old view and re-create it with whatever definition I've given.</p> <p>Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing?</p>
[ { "answer_id": 163283, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 3, "selected": false, "text": "if exists (select * from dbo.sysobjects\n where id = object_id(N'dbo.MyView') and\n OBJECTPROPERTY(id, N'IsView') = 1)\ndrop view dbo.MyView\ngo\ncreate view dbo.MyView [...]\n" }, { "answer_id": 939067, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 4, "selected": false, "text": "IF OBJECT_ID('[dbo].[myView]') IS NOT NULL\nDROP VIEW [dbo].[myView]\nGO\nCREATE VIEW [dbo].[myView]\nAS\n CREATE PROCEDURE dbo.DropView\n@ASchema VARCHAR(100),\n@AView VARCHAR(100)\nAS\nBEGIN\n DECLARE @sql VARCHAR(1000);\n IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL\n BEGIN\n SET @sql = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';\n EXEC(@sql);\n END \nEND\n EXEC dbo.DropView 'mySchema', 'myView'\nGO\nCREATE View myView\n...\nGO\n" }, { "answer_id": 5184901, "author": "john.da.costa", "author_id": 138921, "author_profile": "https://Stackoverflow.com/users/138921", "pm_score": 8, "selected": true, "text": "IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]'))\n EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'\nGO\n\nALTER VIEW [dbo].[vw_myView]\nAS\nSELECT 'This is a code which should be replaced by the real code for your view' as [real_code]\nGO\n" }, { "answer_id": 33443738, "author": "Justin Dearing", "author_id": 95195, "author_profile": "https://Stackoverflow.com/users/95195", "pm_score": 3, "selected": false, "text": "DROP TABLE IF EXISTS [foo];\n" }, { "answer_id": 40707436, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 6, "selected": false, "text": "SQL Server 2016 SP1+ CREATE OR ALTER VIEW CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] \n[ WITH <view_attribute> [ ,...n ] ] \nAS select_statement \n[ WITH CHECK OPTION ] \n[ ; ]\n" }, { "answer_id": 47393102, "author": "Lex", "author_id": 5228885, "author_profile": "https://Stackoverflow.com/users/5228885", "pm_score": 2, "selected": false, "text": "USE MSSQLTipsDemo \nGO\nCREATE OR ALTER PROC CreateOrAlterDemo\nAS\nBEGIN\nSELECT TOP 10 * FROM [dbo].[CountryInfoNew]\nEND\nGO\n" }, { "answer_id": 54666187, "author": "MovGP0", "author_id": 601990, "author_profile": "https://Stackoverflow.com/users/601990", "pm_score": 2, "selected": false, "text": "CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...\n DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';\n\nIF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')\n-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL\nBEGIN EXEC('CREATE ' + @script) END\nELSE\nBEGIN EXEC('ALTER ' + @script) END\n IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')\n-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL\nBEGIN \n DROP VIEW [VW_NAMEOFVIEW];\nEND\n\nCREATE VIEW [VW_NAMEOFVIEW] AS ...\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
163,302
<p>I'm trying to have the modrewrite rules skip the directory <code>vip</code>. I've tried a number of things as you can see below, but to no avail.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / #RewriteRule ^vip$ - [PT] RewriteRule ^vip/.$ - [PT] #RewriteCond %{REQUEST_URI} !/vip RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>How do I get modrewrite to entirely ignore the <code>/vip/</code> directory so that all requests pass directly to the folder?</p> <h3>Update:</h3> <p>As points of clarity:</p> <ul> <li>It's hosted on Dreamhost</li> <li>The folders are within a wordpress directory</li> <li>the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important</li> </ul>
[ { "answer_id": 163401, "author": "Peter Howe", "author_id": 24106, "author_profile": "https://Stackoverflow.com/users/24106", "pm_score": -1, "selected": false, "text": "RewriteRule ^/vip/(.*)$ /$1?%{QUERY_STRING} [L]\n" }, { "answer_id": 163530, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 7, "selected": false, "text": "RewriteRule ^vip - [L,NC] \n vip - L NC vip ^vip$ vip vip/ vip/index.html $ ^vip(/|$) vip-page.html" }, { "answer_id": 163855, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "RewriteEngine off\n" }, { "answer_id": 273704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n" }, { "answer_id": 2664755, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 2, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n ErrorDocument 401 /misc/myerror.html\nErrorDocument 403 /misc/myerror.html\n" }, { "answer_id": 3435332, "author": "Cody A. Ray", "author_id": 337735, "author_profile": "https://Stackoverflow.com/users/337735", "pm_score": 3, "selected": false, "text": "ErrorDocument 401 /misc/myerror.html\nErrorDocument 403 /misc/myerror.html\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n\n# END WordPress\n" }, { "answer_id": 5136622, "author": "Pat", "author_id": 636920, "author_profile": "https://Stackoverflow.com/users/636920", "pm_score": 2, "selected": false, "text": "RewriteRule ^vip - [L,NC]\n ErrorDocument 404 /page-not-found.html\n\nRewriteEngine on\n\nRewriteRule ^vip - [L,NC]\n\nAddType application/x-httpd-php .html .htm\n\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d \n\netc\n" }, { "answer_id": 13633771, "author": "Gokul Muralidharan", "author_id": 1618137, "author_profile": "https://Stackoverflow.com/users/1618137", "pm_score": 2, "selected": false, "text": "RewriteCond %{REQUEST_URI} !^pilot/ \n" }, { "answer_id": 18157129, "author": "brentonstrine", "author_id": 925897, "author_profile": "https://Stackoverflow.com/users/925897", "pm_score": 3, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n -f -d .htaccess vip ErrorDocument 401 /err.txt\nErrorDocument 403 /err.txt\n RewriteCond %{REQUEST_FILENAME} !-f" }, { "answer_id": 26497821, "author": "carlaron", "author_id": 4167867, "author_profile": "https://Stackoverflow.com/users/4167867", "pm_score": 2, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n ErrorDocument 401 /err.txt\nErrorDocument 403 /err.txt\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24557/" ]
163,311
<p>I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS</p>
[ { "answer_id": 163325, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 2, "selected": false, "text": "DateTime startDate;\nDateTime endDate;\n\nDateTime currentDate = startDate;\nList<DateTime> dates = new List<DateTime> ();\n\nwhile (true)\n{\n dates.Add (currentDate);\n if (currentDate.Equals (endDate)) break;\n currentDate = currentDate.AddDays (1);\n}\n" }, { "answer_id": 163348, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": true, "text": "DateTime RangeStartDate,RangeEndDate; //Init as necessary\nDateTime CalendarStartDate,CalendarEndDate; //Init as necessary\nDateTime CurrentDate = CalendarStartDate;\n\nString CSSClass;\n\nwhile (CurrentDate != CalendarEndDate)\n{\n if(CurrentDate >= RangeStartDate && CurrentDate <= RangeEndDate)\n {\n CSSClass= \"InRange\";\n } \n else\n {\n CSSClass = \"OutOfRange\";\n }\n //Code For rendering calendar goes here\n currentDate = currentDate.AddDays (1);\n}\n" }, { "answer_id": 163353, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 2, "selected": false, "text": "IEnumerable<DateTime> RangeDays(DateTime RangeStart, DateTime RangeEnd) {\n DateTime EndDate = RangeEnd.Date;\n\n for (DateTime WorkDate = RangeStart.Date; WorkDate <= EndDate; WorkDate = WorkDate.AddDays(1)) {\n yield return WorkDate;\n }\n\n yield break;\n}\n" }, { "answer_id": 163423, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "// inclusive\nvar allDates = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(i => startDate.AddDays(i));\n\n// exclusive\nvar allDates = Enumerable.Range(1, (endDate - startDate).Days).Select(i => startDate.AddDays(i));\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
163,336
<p>Say for example you just queried a database and you recieved this 2D array.</p> <pre><code>$results = array( array('id' =&gt; 1, 'name' =&gt; 'red' , 'spin' =&gt; 1), array('id' =&gt; 2, 'name' =&gt; 'green', 'spin' =&gt; -1), array('id' =&gt; 3, 'name' =&gt; 'blue' , 'spin' =&gt; .5) ); </code></pre> <p>I often find myself writing loops like this.</p> <pre><code>foreach($results as $result) $names[] = $result['name']; </code></pre> <p>My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.</p> <p>Here is a more generic example of getting every field.</p> <pre><code>foreach($results as $result) foreach($result as $key =&gt; $value) $fields[$key][] = $value; </code></pre>
[ { "answer_id": 163491, "author": "inxilpro", "author_id": 12549, "author_profile": "https://Stackoverflow.com/users/12549", "pm_score": 4, "selected": false, "text": "function array_column($array, $column)\n{\n $ret = array();\n foreach ($array as $row) $ret[] = $row[$column];\n return $ret;\n}\n" }, { "answer_id": 164045, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 0, "selected": false, "text": "$results = array(\n array('id' => 1, 'name' => 'red' , 'spin' => 1),\n array('id' => 2, 'name' => 'green', 'spin' => -1),\n array('id' => 3, 'name' => 'blue' , 'spin' => .5)\n);\n$name = array_uintersect_uassoc( $results, array('name' => 'value') , 0, \"cmpKey\");\nprint_r($name);\n\n//////////////////////////////////////////////////\n// FUNCTIONS\n//////////////////////////////////////////////////\nfunction cmpKey($key1, $key2) {\n if ($key1 == $key2) {\n return 0;\n } else {\n return -1;\n }\n}\n" }, { "answer_id": 169242, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 2, "selected": false, "text": "array_map" }, { "answer_id": 13561591, "author": "Alexey Petushkov", "author_id": 1258965, "author_profile": "https://Stackoverflow.com/users/1258965", "pm_score": 3, "selected": false, "text": "$names = array_map(function ($v){ return $v['name']; }, $results);\n" }, { "answer_id": 15555791, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 6, "selected": true, "text": "$records = array(\n array(\n 'id' => 2135,\n 'first_name' => 'John',\n 'last_name' => 'Doe'\n ),\n array(\n 'id' => 3245,\n 'first_name' => 'Sally',\n 'last_name' => 'Smith'\n ),\n array(\n 'id' => 5342,\n 'first_name' => 'Jane',\n 'last_name' => 'Jones'\n ),\n array(\n 'id' => 5623,\n 'first_name' => 'Peter',\n 'last_name' => 'Doe'\n )\n);\n\n\n$firstNames = array_column($records, 'first_name');\nprint_r($firstNames);\n Array\n(\n [0] => John\n [1] => Sally\n [2] => Jane\n [3] => Peter\n)\n" }, { "answer_id": 15645399, "author": "yokototo", "author_id": 2213030, "author_profile": "https://Stackoverflow.com/users/2213030", "pm_score": 0, "selected": false, "text": "$tmp = array_flip($names);\n$names = array_keys($tmp);\n" }, { "answer_id": 19188062, "author": "MirroredFate", "author_id": 771665, "author_profile": "https://Stackoverflow.com/users/771665", "pm_score": 2, "selected": false, "text": "PHP5.5 array_column function array_column($array, $column){\n $a2 = array();\n array_map(function ($a1) use ($column, &$a2){\n array_push($a2, $a1[$column]);\n }, $array);\n return $a2;\n}\n" }, { "answer_id": 24616520, "author": "JohnK", "author_id": 1431728, "author_profile": "https://Stackoverflow.com/users/1431728", "pm_score": 1, "selected": false, "text": "array_column()" }, { "answer_id": 25239265, "author": "Keshav Kalra", "author_id": 1746436, "author_profile": "https://Stackoverflow.com/users/1746436", "pm_score": 0, "selected": false, "text": "if(!function_exists('array_column')) {\n function array_column($element_name) {\n $ele = array_map(function($element) {\n return $element[$element_name];\n }, $a);\n return $ele;\n }\n}\n" }, { "answer_id": 70503573, "author": "Juan Carlos Constantine", "author_id": 3083631, "author_profile": "https://Stackoverflow.com/users/3083631", "pm_score": 0, "selected": false, "text": " function transpose(array $array): array\n {\n $out = array();\n foreach ($array as $rowkey => $row) {\n foreach ($row as $colkey => $col) {\n $out[$colkey][$rowkey] = $col;\n }\n }\n return $out;\n }\n\n function filter_columns(array $arr, string ...$columns): array\n {\n return array_intersect_key($arr, array_flip($columns));\n }\n $results = array(\n array('id' => 1, 'name' => 'red' , 'spin' => 1),\n array('id' => 2, 'name' => 'green', 'spin' => -1),\n array('id' => 3, 'name' => 'blue' , 'spin' => .5)\n);\n\n var_dump(filter_columns(transpose($results),'name'));\n var_dump(filter_columns(transpose($results),'id','name'));\n var_dump(filter_columns(transpose($results),'id','spin'));\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17919/" ]
163,355
<p>I'm on SQL Server 2005 and I am getting an error which I am pretty sure should not be getting.</p> <pre><code>Msg 512, Level 16, State 1, Procedure spGetSavedSearchesByAdminUser, Line 8 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , &gt;, &gt;= or when the subquery is used as an expression. </code></pre> <p>I am following the example# B on <a href="http://msdn.microsoft.com/en-us/library/ms177682(SQL.90).aspx" rel="nofollow noreferrer">this</a> MSDN link.</p> <p>My stored proc code is as follows. I can simplify it for the sake of this post if you request so:</p> <pre><code>ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] @strUserName varchar(50) ,@bitQuickSearch bit = 0 AS BEGIN SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName] FROM [tblAdminSearches] WHERE strUserName = @strUserName AND strSearchTypeCode IN ( CASE @bitQuickSearch WHEN 1 THEN 'Quick' ELSE (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes) END ) ORDER BY strSearchName END </code></pre> <p>I have checked there is no datatype mismatch between the resultset from the subquery and the strSearchTypeCode the subquery result is compared with.</p> <p>I see no reason why this should not work. If you have any clues then please let me know.</p>
[ { "answer_id": 163371, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "WHERE strUserName = @strUserName AND (\n (@bitQuickSearch = 1 AND strSearchTypeCode = 'Quick')\n OR\n (strSearchTypeCode IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes))\n)\n WHERE strUserName = @strUserName \n AND strSearchTypeCode IN (\n SELECT CASE @bitQuickSearch WHEN 1 THEN 'Quick' ELSE strSearchTypeCode END\n FROM tblAdvanceSearchTypes\n )\n" }, { "answer_id": 163373, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "SELECT strSearchTypeCode FROM tblAdvanceSearchTypes\n SELECT TOP 1 strSearchTypeCode FROM tblAdvanceSearchTypes\n" }, { "answer_id": 163377, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 3, "selected": true, "text": "ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] \n @strUserName varchar(50) \n ,@bitQuickSearch bit = 0\nAS\n\nBEGIN\n\n SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName]\n FROM [tblAdminSearches] \n\n WHERE \n strUserName = @strUserName\n AND \n strSearchTypeCode \n IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes where @bitQuickSearch=0\n UNION\n SELECT 'Quick' AS strSearchTypeCode WHERE @bitQuickSearch=1)\n\n ORDER BY strSearchName\nEND\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262613/" ]
163,360
<p>I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java <code>String</code> flavor and pasted it into Java code, it does not work. The following class prints <code>false</code>: </p> <pre><code>public class RegexFoo { public static void main(String[] args) { String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&amp;@#/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#/%=~_|]"; String text = "http://google.com"; System.out.println(IsMatch(text,regex)); } private static boolean IsMatch(String s, String pattern) { try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(s); return matcher.matches(); } catch (RuntimeException e) { return false; } } } </code></pre> <p>Does anyone know what I am doing wrong?</p>
[ { "answer_id": 163398, "author": "TomC", "author_id": 13183, "author_profile": "https://Stackoverflow.com/users/13183", "pm_score": 8, "selected": true, "text": "String regex = \"^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]\";\n String regex = \"\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]\";\n String regex = \"<\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>\"; // matches <http://google.com>\n\nString regex = \"<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>\"; // does not match <http://google.com>\n" }, { "answer_id": 163410, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 6, "selected": false, "text": "java.net.URL URL url = new URL(stringURL);\n MalformedURLException" }, { "answer_id": 163539, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 2, "selected": false, "text": "String regex = \"\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]\";\n String regex = \"<\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>\"; // matches <http://google.com>\n\nString regex = \"<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>\"; // does not match <http://google.com>\n" }, { "answer_id": 14426010, "author": "Fuad Efendi", "author_id": 1748983, "author_profile": "https://Stackoverflow.com/users/1748983", "pm_score": 2, "selected": false, "text": "pattern = Pattern.compile(\"[A-Za-z0-9](([_\\\\.\\\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\\\.\\\\-]?[a-zA-Z0-9]+)*)\\\\.([A-Za-z]{2,})\", Pattern.CASE_INSENSITIVE);\n\n\"Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna\");\n\"@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.\";\n" }, { "answer_id": 18915455, "author": "Kamil Lelonek", "author_id": 1313175, "author_profile": "https://Stackoverflow.com/users/1313175", "pm_score": 7, "selected": false, "text": "android.util.Patterns.WEB_URL.matcher(linkUrl).matches();\n Patterns /*\n * Copyright (C) 2007 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage android.util;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * Commonly used regular expression patterns.\n */\npublic class Patterns {\n /**\n * Regular expression to match all IANA top-level domains.\n * List accurate as of 2011/07/18. List taken from:\n * http://data.iana.org/TLD/tlds-alpha-by-domain.txt\n * This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py\n *\n * @deprecated Due to the recent profileration of gTLDs, this API is\n * expected to become out-of-date very quickly. Therefore it is now\n * deprecated.\n */\n @Deprecated\n public static final String TOP_LEVEL_DOMAIN_STR =\n \"((aero|arpa|asia|a[cdefgilmnoqrstuwxz])\"\n + \"|(biz|b[abdefghijmnorstvwyz])\"\n + \"|(cat|com|coop|c[acdfghiklmnoruvxyz])\"\n + \"|d[ejkmoz]\"\n + \"|(edu|e[cegrstu])\"\n + \"|f[ijkmor]\"\n + \"|(gov|g[abdefghilmnpqrstuwy])\"\n + \"|h[kmnrtu]\"\n + \"|(info|int|i[delmnoqrst])\"\n + \"|(jobs|j[emop])\"\n + \"|k[eghimnprwyz]\"\n + \"|l[abcikrstuvy]\"\n + \"|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])\"\n + \"|(name|net|n[acefgilopruz])\"\n + \"|(org|om)\"\n + \"|(pro|p[aefghklmnrstwy])\"\n + \"|qa\"\n + \"|r[eosuw]\"\n + \"|s[abcdeghijklmnortuvyz]\"\n + \"|(tel|travel|t[cdfghjklmnoprtvwz])\"\n + \"|u[agksyz]\"\n + \"|v[aceginu]\"\n + \"|w[fs]\"\n + \"|(\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae|\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435|\\u0440\\u0444|\\u0441\\u0440\\u0431|\\u05d8\\u05e2\\u05e1\\u05d8|\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\\u06cc|\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631|\\u0627\\u0644\\u0627\\u0631\\u062f\\u0646|\\u0627\\u0644\\u062c\\u0632\\u0627\\u0626\\u0631|\\u0627\\u0644\\u0633\\u0639\\u0648\\u062f\\u064a\\u0629|\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628|\\u0627\\u0645\\u0627\\u0631\\u0627\\u062a|\\u0628\\u06be\\u0627\\u0631\\u062a|\\u062a\\u0648\\u0646\\u0633|\\u0633\\u0648\\u0631\\u064a\\u0629|\\u0641\\u0644\\u0633\\u0637\\u064a\\u0646|\\u0642\\u0637\\u0631|\\u0645\\u0635\\u0631|\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e|\\u092d\\u093e\\u0930\\u0924|\\u09ad\\u09be\\u09b0\\u09a4|\\u0a2d\\u0a3e\\u0a30\\u0a24|\\u0aad\\u0abe\\u0ab0\\u0aa4|\\u0b87\\u0ba8\\u0bcd\\u0ba4\\u0bbf\\u0baf\\u0bbe|\\u0b87\\u0bb2\\u0b99\\u0bcd\\u0b95\\u0bc8|\\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0baa\\u0bcd\\u0baa\\u0bc2\\u0bb0\\u0bcd|\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8|\\u0c2d\\u0c3e\\u0c30\\u0c24\\u0c4d|\\u0dbd\\u0d82\\u0d9a\\u0dcf|\\u0e44\\u0e17\\u0e22|\\u30c6\\u30b9\\u30c8|\\u4e2d\\u56fd|\\u4e2d\\u570b|\\u53f0\\u6e7e|\\u53f0\\u7063|\\u65b0\\u52a0\\u5761|\\u6d4b\\u8bd5|\\u6e2c\\u8a66|\\u9999\\u6e2f|\\ud14c\\uc2a4\\ud2b8|\\ud55c\\uad6d|xn\\\\-\\\\-0zwm56d|xn\\\\-\\\\-11b5bs3a9aj6g|xn\\\\-\\\\-3e0b707e|xn\\\\-\\\\-45brj9c|xn\\\\-\\\\-80akhbyknj4f|xn\\\\-\\\\-90a3ac|xn\\\\-\\\\-9t4b11yi5a|xn\\\\-\\\\-clchc0ea0b2g2a9gcd|xn\\\\-\\\\-deba0ad|xn\\\\-\\\\-fiqs8s|xn\\\\-\\\\-fiqz9s|xn\\\\-\\\\-fpcrj9c3d|xn\\\\-\\\\-fzc2c9e2c|xn\\\\-\\\\-g6w251d|xn\\\\-\\\\-gecrj9c|xn\\\\-\\\\-h2brj9c|xn\\\\-\\\\-hgbk6aj7f53bba|xn\\\\-\\\\-hlcj6aya9esc7a|xn\\\\-\\\\-j6w193g|xn\\\\-\\\\-jxalpdlp|xn\\\\-\\\\-kgbechtv|xn\\\\-\\\\-kprw13d|xn\\\\-\\\\-kpry57d|xn\\\\-\\\\-lgbbat1ad8j|xn\\\\-\\\\-mgbaam7a8h|xn\\\\-\\\\-mgbayh7gpa|xn\\\\-\\\\-mgbbh1a71e|xn\\\\-\\\\-mgbc0a9azcg|xn\\\\-\\\\-mgberp4a5d4ar|xn\\\\-\\\\-o3cw4h|xn\\\\-\\\\-ogbpf8fl|xn\\\\-\\\\-p1ai|xn\\\\-\\\\-pgbs0dh|xn\\\\-\\\\-s9brj9c|xn\\\\-\\\\-wgbh1c|xn\\\\-\\\\-wgbl6a|xn\\\\-\\\\-xkc2al3hye2a|xn\\\\-\\\\-xkc2dl3a5ee0h|xn\\\\-\\\\-yfro4i67o|xn\\\\-\\\\-ygbi2ammx|xn\\\\-\\\\-zckzah|xxx)\"\n + \"|y[et]\"\n + \"|z[amw])\";\n\n /**\n * Regular expression pattern to match all IANA top-level domains.\n * @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.\n */\n @Deprecated\n public static final Pattern TOP_LEVEL_DOMAIN =\n Pattern.compile(TOP_LEVEL_DOMAIN_STR);\n\n /**\n * Regular expression to match all IANA top-level domains for WEB_URL.\n * List accurate as of 2011/07/18. List taken from:\n * http://data.iana.org/TLD/tlds-alpha-by-domain.txt\n * This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py\n *\n * @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.\n */\n @Deprecated\n public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =\n \"(?:\"\n + \"(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])\"\n + \"|(?:biz|b[abdefghijmnorstvwyz])\"\n + \"|(?:cat|com|coop|c[acdfghiklmnoruvxyz])\"\n + \"|d[ejkmoz]\"\n + \"|(?:edu|e[cegrstu])\"\n + \"|f[ijkmor]\"\n + \"|(?:gov|g[abdefghilmnpqrstuwy])\"\n + \"|h[kmnrtu]\"\n + \"|(?:info|int|i[delmnoqrst])\"\n + \"|(?:jobs|j[emop])\"\n + \"|k[eghimnprwyz]\"\n + \"|l[abcikrstuvy]\"\n + \"|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])\"\n + \"|(?:name|net|n[acefgilopruz])\"\n + \"|(?:org|om)\"\n + \"|(?:pro|p[aefghklmnrstwy])\"\n + \"|qa\"\n + \"|r[eosuw]\"\n + \"|s[abcdeghijklmnortuvyz]\"\n + \"|(?:tel|travel|t[cdfghjklmnoprtvwz])\"\n + \"|u[agksyz]\"\n + \"|v[aceginu]\"\n + \"|w[fs]\"\n + \"|(?:\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae|\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435|\\u0440\\u0444|\\u0441\\u0440\\u0431|\\u05d8\\u05e2\\u05e1\\u05d8|\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\\u06cc|\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631|\\u0627\\u0644\\u0627\\u0631\\u062f\\u0646|\\u0627\\u0644\\u062c\\u0632\\u0627\\u0626\\u0631|\\u0627\\u0644\\u0633\\u0639\\u0648\\u062f\\u064a\\u0629|\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628|\\u0627\\u0645\\u0627\\u0631\\u0627\\u062a|\\u0628\\u06be\\u0627\\u0631\\u062a|\\u062a\\u0648\\u0646\\u0633|\\u0633\\u0648\\u0631\\u064a\\u0629|\\u0641\\u0644\\u0633\\u0637\\u064a\\u0646|\\u0642\\u0637\\u0631|\\u0645\\u0635\\u0631|\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e|\\u092d\\u093e\\u0930\\u0924|\\u09ad\\u09be\\u09b0\\u09a4|\\u0a2d\\u0a3e\\u0a30\\u0a24|\\u0aad\\u0abe\\u0ab0\\u0aa4|\\u0b87\\u0ba8\\u0bcd\\u0ba4\\u0bbf\\u0baf\\u0bbe|\\u0b87\\u0bb2\\u0b99\\u0bcd\\u0b95\\u0bc8|\\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0baa\\u0bcd\\u0baa\\u0bc2\\u0bb0\\u0bcd|\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8|\\u0c2d\\u0c3e\\u0c30\\u0c24\\u0c4d|\\u0dbd\\u0d82\\u0d9a\\u0dcf|\\u0e44\\u0e17\\u0e22|\\u30c6\\u30b9\\u30c8|\\u4e2d\\u56fd|\\u4e2d\\u570b|\\u53f0\\u6e7e|\\u53f0\\u7063|\\u65b0\\u52a0\\u5761|\\u6d4b\\u8bd5|\\u6e2c\\u8a66|\\u9999\\u6e2f|\\ud14c\\uc2a4\\ud2b8|\\ud55c\\uad6d|xn\\\\-\\\\-0zwm56d|xn\\\\-\\\\-11b5bs3a9aj6g|xn\\\\-\\\\-3e0b707e|xn\\\\-\\\\-45brj9c|xn\\\\-\\\\-80akhbyknj4f|xn\\\\-\\\\-90a3ac|xn\\\\-\\\\-9t4b11yi5a|xn\\\\-\\\\-clchc0ea0b2g2a9gcd|xn\\\\-\\\\-deba0ad|xn\\\\-\\\\-fiqs8s|xn\\\\-\\\\-fiqz9s|xn\\\\-\\\\-fpcrj9c3d|xn\\\\-\\\\-fzc2c9e2c|xn\\\\-\\\\-g6w251d|xn\\\\-\\\\-gecrj9c|xn\\\\-\\\\-h2brj9c|xn\\\\-\\\\-hgbk6aj7f53bba|xn\\\\-\\\\-hlcj6aya9esc7a|xn\\\\-\\\\-j6w193g|xn\\\\-\\\\-jxalpdlp|xn\\\\-\\\\-kgbechtv|xn\\\\-\\\\-kprw13d|xn\\\\-\\\\-kpry57d|xn\\\\-\\\\-lgbbat1ad8j|xn\\\\-\\\\-mgbaam7a8h|xn\\\\-\\\\-mgbayh7gpa|xn\\\\-\\\\-mgbbh1a71e|xn\\\\-\\\\-mgbc0a9azcg|xn\\\\-\\\\-mgberp4a5d4ar|xn\\\\-\\\\-o3cw4h|xn\\\\-\\\\-ogbpf8fl|xn\\\\-\\\\-p1ai|xn\\\\-\\\\-pgbs0dh|xn\\\\-\\\\-s9brj9c|xn\\\\-\\\\-wgbh1c|xn\\\\-\\\\-wgbl6a|xn\\\\-\\\\-xkc2al3hye2a|xn\\\\-\\\\-xkc2dl3a5ee0h|xn\\\\-\\\\-yfro4i67o|xn\\\\-\\\\-ygbi2ammx|xn\\\\-\\\\-zckzah|xxx)\"\n + \"|y[et]\"\n + \"|z[amw]))\";\n\n /**\n * Good characters for Internationalized Resource Identifiers (IRI).\n * This comprises most common used Unicode characters allowed in IRI\n * as detailed in RFC 3987.\n * Specifically, those two byte Unicode characters are not included.\n */\n public static final String GOOD_IRI_CHAR =\n \"a-zA-Z0-9\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\";\n\n public static final Pattern IP_ADDRESS\n = Pattern.compile(\n \"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\\\.(25[0-5]|2[0-4]\"\n + \"[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(25[0-5]|2[0-4][0-9]|[0-1]\"\n + \"[0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}\"\n + \"|[1-9][0-9]|[0-9]))\");\n\n /**\n * RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.\n */\n private static final String IRI\n = \"[\" + GOOD_IRI_CHAR + \"]([\" + GOOD_IRI_CHAR + \"\\\\-]{0,61}[\" + GOOD_IRI_CHAR + \"]){0,1}\";\n\n private static final String GOOD_GTLD_CHAR =\n \"a-zA-Z\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\";\n private static final String GTLD = \"[\" + GOOD_GTLD_CHAR + \"]{2,63}\";\n private static final String HOST_NAME = \"(\" + IRI + \"\\\\.)+\" + GTLD;\n\n public static final Pattern DOMAIN_NAME\n = Pattern.compile(\"(\" + HOST_NAME + \"|\" + IP_ADDRESS + \")\");\n\n /**\n * Regular expression pattern to match most part of RFC 3987\n * Internationalized URLs, aka IRIs. Commonly used Unicode characters are\n * added.\n */\n public static final Pattern WEB_URL = Pattern.compile(\n \"((?:(http|https|Http|Https|rtsp|Rtsp):\\\\/\\\\/(?:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\"\n + \"\\\\,\\\\;\\\\?\\\\&\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,64}(?:\\\\:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\"\n + \"\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\;\\\\?\\\\&\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,25})?\\\\@)?)?\"\n + \"(?:\" + DOMAIN_NAME + \")\"\n + \"(?:\\\\:\\\\d{1,5})?)\" // plus option port number\n + \"(\\\\/(?:(?:[\" + GOOD_IRI_CHAR + \"\\\\;\\\\/\\\\?\\\\:\\\\@\\\\&\\\\=\\\\#\\\\~\" // plus option query params\n + \"\\\\-\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\_])|(?:\\\\%[a-fA-F0-9]{2}))*)?\"\n + \"(?:\\\\b|$)\"); // and finally, a word boundary or end of\n // input. This is to stop foo.sure from\n // matching as foo.su\n\n public static final Pattern EMAIL_ADDRESS\n = Pattern.compile(\n \"[a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+]{1,256}\" +\n \"\\\\@\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}\" +\n \"(\" +\n \"\\\\.\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,25}\" +\n \")+\"\n );\n\n /**\n * This pattern is intended for searching for things that look like they\n * might be phone numbers in arbitrary text, not for validating whether\n * something is in fact a phone number. It will miss many things that\n * are legitimate phone numbers.\n *\n * <p> The pattern matches the following:\n * <ul>\n * <li>Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes\n * may follow.\n * <li>Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.\n * <li>A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.\n * </ul>\n */\n public static final Pattern PHONE\n = Pattern.compile( // sdd = space, dot, or dash\n \"(\\\\+[0-9]+[\\\\- \\\\.]*)?\" // +<digits><sdd>*\n + \"(\\\\([0-9]+\\\\)[\\\\- \\\\.]*)?\" // (<digits>)<sdd>*\n + \"([0-9][0-9\\\\- \\\\.]+[0-9])\"); // <digit><digit|sdd>+<digit>\n\n /**\n * Convenience method to take all of the non-null matching groups in a\n * regex Matcher and return them as a concatenated string.\n *\n * @param matcher The Matcher object from which grouped text will\n * be extracted\n *\n * @return A String comprising all of the non-null matched\n * groups concatenated together\n */\n public static final String concatGroups(Matcher matcher) {\n StringBuilder b = new StringBuilder();\n final int numGroups = matcher.groupCount();\n\n for (int i = 1; i <= numGroups; i++) {\n String s = matcher.group(i);\n\n if (s != null) {\n b.append(s);\n }\n }\n\n return b.toString();\n }\n\n /**\n * Convenience method to return only the digits and plus signs\n * in the matching string.\n *\n * @param matcher The Matcher object from which digits and plus will\n * be extracted\n *\n * @return A String comprising all of the digits and plus in\n * the match\n */\n public static final String digitsAndPlusOnly(Matcher matcher) {\n StringBuilder buffer = new StringBuilder();\n String matchingRegion = matcher.group();\n\n for (int i = 0, size = matchingRegion.length(); i < size; i++) {\n char character = matchingRegion.charAt(i);\n\n if (character == '+' || Character.isDigit(character)) {\n buffer.append(character);\n }\n }\n return buffer.toString();\n }\n\n /**\n * Do not create this static utility class.\n */\n private Patterns() {}\n}\n" }, { "answer_id": 37069466, "author": "Cavaleiro", "author_id": 716861, "author_profile": "https://Stackoverflow.com/users/716861", "pm_score": 2, "selected": false, "text": "String[] schemes = {\"http\",\"https\"}.\nUrlValidator urlValidator = new UrlValidator(schemes);\nif (urlValidator.isValid(\"ftp://foo.bar.com/\")) {\n System.out.println(\"url is valid\");\n} else {\n System.out.println(\"url is invalid\");\n}\n\nprints \"url is invalid\"\n UrlValidator urlValidator = new UrlValidator();\nif (urlValidator.isValid(\"ftp://foo.bar.com/\")) {\n System.out.println(\"url is valid\");\n} else {\n System.out.println(\"url is invalid\");\n}\n" }, { "answer_id": 56560145, "author": "Abhiraj", "author_id": 11636196, "author_profile": "https://Stackoverflow.com/users/11636196", "pm_score": 2, "selected": false, "text": "((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\\.[a-zA-Z]+\n" }, { "answer_id": 66136090, "author": "Rabah LEKHEBASSENE", "author_id": 7201292, "author_profile": "https://Stackoverflow.com/users/7201292", "pm_score": 0, "selected": false, "text": "^(?>(?<protocol>[[:alpha:]]+(?>\\:[[:alpha:]]+)*)\\:\\/\\/)?(?<host>(?>[[:alnum:]]|[-_.])+)(?>\\:(?<port>[[:digit:]]+))?(?<path>\\/(?>[[:alnum:]]|[-_.\\/])*)?(?>\\?(?<request>(?>[[:alnum:]]+=[[:alnum:]]+)(?>\\&(?>[[:alnum:]]+=[[:alnum:]]+))*))?$\n jdbc:hsqldb:hsql://localhost:91/index.\n" }, { "answer_id": 68759694, "author": "Blas Albir", "author_id": 15795723, "author_profile": "https://Stackoverflow.com/users/15795723", "pm_score": 0, "selected": false, "text": "regex = “((http|https)://)(www.)?” \n+ “[a-zA-Z0-9@:%._\\\\+~#?&//=]{2,256}\\\\.[a-z]” \n+ “{2,6}\\\\b([-a-zA-Z0-9@:%._\\\\+~#?&//=]*)”\n // Java program to check URL is valid or not\n// using Regular Expression\n \nimport java.util.regex.*;\n \nclass GFG {\n \n // Function to validate URL\n // using regular expression\n public static boolean\n isValidURL(String url)\n {\n // Regex to check valid URL\n String regex = \"((http|https)://)(www.)?\"\n + \"[a-zA-Z0-9@:%._\\\\+~#?&//=]\"\n + \"{2,256}\\\\.[a-z]\"\n + \"{2,6}\\\\b([-a-zA-Z0-9@:%\"\n + \"._\\\\+~#?&//=]*)\";\n \n // Compile the ReGex\n Pattern p = Pattern.compile(regex);\n \n // If the string is empty\n // return false\n if (url == null) {\n return false;\n }\n \n // Find match between given string\n // and regular expression\n // using Pattern.matcher()\n Matcher m = p.matcher(url);\n \n // Return if the string\n // matched the ReGex\n return m.matches();\n }\n \n // Driver code\n public static void main(String args[])\n {\n String url\n = \"https://www.superDev.org\";\n if (isValidURL(url) == true) {\n System.out.println(\"Yes\");\n }\n else\n System.out.println(\"NO\");\n }\n}\n # Python3 program to check\n# URL is valid or not\n# using regular expression\nimport re\n \n# Function to validate URL\n# using regular expression\ndef isValidURL(str):\n \n # Regex to check valid URL\n regex = (\"((http|https)://)(www.)?\" +\n \"[a-zA-Z0-9@:%._\\\\+~#?&//=]\" +\n \"{2,256}\\\\.[a-z]\" +\n \"{2,6}\\\\b([-a-zA-Z0-9@:%\" +\n \"._\\\\+~#?&//=]*)\")\n \n # Compile the ReGex\n p = re.compile(regex)\n \n # If the string is empty\n # return false\n if (str == None):\n return False\n \n # Return if the string\n # matched the ReGex\n if(re.search(p, str)):\n return True\n else:\n return False\n \n# Driver code\n \n# Test Case 1:\nurl = \"https://www.superDev.org\"\n \nif(isValidURL(url) == True):\n print(\"Yes\")\nelse:\n print(\"No\")\n \n" }, { "answer_id": 71153620, "author": "alexrnov", "author_id": 12787936, "author_profile": "https://Stackoverflow.com/users/12787936", "pm_score": 0, "selected": false, "text": "String regex = \"(https?://|www\\\\.)[-a-zA-Z0-9+&@#/%?=~_|!:.;]*[-a-zA-Z0-9+&@#/%=~_|]\";\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
163,363
<p>I have monthly sales figures stored in separate sheets. I would like to create a plot of sales for multiple products per month. Each product would be represented in a different colored line on the same chart with each month running along the x axis.</p> <p>What is the best way to create a single line chart that pulls from the same relative cells on multiple sheets?</p>
[ { "answer_id": 4172905, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "Sub createAllGraphs()\n\nConst chartWidth As Integer = 260\nConst chartHeight As Integer = 200\n\n\n\n\nIf Sheets.Count = 1 Then\n Sheets.Add , Sheets(1)\n Sheets(2).Name = \"AllCharts\"\nElseIf Sheets(\"AllCharts\").ChartObjects.Count > 0 Then\n Sheets(\"AllCharts\").ChartObjects.Delete\nEnd If\nDim c As Variant\nDim c2 As Variant\nDim cs As Object\nSet cs = Sheets(\"AllCharts\")\nDim s As Object\nSet s = Sheets(1)\n\nDim i As Integer\n\n\nDim chartX As Integer\nDim chartY As Integer\n\nDim r As Integer\nr = 2\n\nDim curA As String\ncurA = s.Range(\"A\" & r)\nDim curB As String\nDim curC As String\nDim startR As Integer\nstartR = 2\n\nDim lastTime As Boolean\nlastTime = False\n\nDo While s.Range(\"A\" & r) <> \"\"\n\n If curC <> s.Range(\"C\" & r) Then\n\n If r <> 2 Then\nseriesAdd:\n c.SeriesCollection.Add s.Range(\"D\" & startR & \":E\" & (r - 1)), , False, True\n c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range(\"C\" & startR), \"Â\", \"\")\n c.SeriesCollection(c.SeriesCollection.Count).XValues = \"='\" & s.Name & \"'!$D$\" & startR & \":$D$\" & (r - 1)\n c.SeriesCollection(c.SeriesCollection.Count).Values = \"='\" & s.Name & \"'!$E$\" & startR & \":$E$\" & (r - 1)\n c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True\n c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select\n c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:=\"='\" & s.Name & \"'!$F$\" & startR & \":$F$\" & (r - 1), minusvalues:=\"='\" & s.Name & \"'!$F$\" & startR & \":$F$\" & (r - 1)\n c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0\n\n c2.SeriesCollection.Add s.Range(\"D\" & startR & \":D\" & (r - 1) & \",G\" & startR & \":G\" & (r - 1)), , False, True\n c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range(\"C\" & startR), \"Â\", \"\")\n c2.SeriesCollection(c2.SeriesCollection.Count).XValues = \"='\" & s.Name & \"'!$D$\" & startR & \":$D$\" & (r - 1)\n c2.SeriesCollection(c2.SeriesCollection.Count).Values = \"='\" & s.Name & \"'!$G$\" & startR & \":$G$\" & (r - 1)\n c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True\n c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select\n c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:=\"='\" & s.Name & \"'!$H$\" & startR & \":$H$\" & (r - 1), minusvalues:=\"='\" & s.Name & \"'!$H$\" & startR & \":$H$\" & (r - 1)\n c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0\n If lastTime = True Then GoTo postLoop\n End If\n\n If curB <> s.Range(\"B\" & r).Value Then\n\n If curA <> s.Range(\"A\" & r).Value Then\n chartX = chartX + chartWidth * 2\n chartY = 0\n curA = s.Range(\"A\" & r)\n End If\n\n Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)\n Set c = c.Chart\n c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range(\"B\" & r), \"Â\", \"\") & \" \" & s.Range(\"A\" & r), s.Range(\"D1\"), s.Range(\"E1\")\n\n Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)\n Set c2 = c2.Chart\n c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range(\"B\" & r), \"Â\", \"\") & \" \" & s.Range(\"A\" & r) & \" (%)\", s.Range(\"D1\"), s.Range(\"G1\")\n\n chartY = chartY + chartHeight\n curB = s.Range(\"B\" & r)\n curC = s.Range(\"C\" & r)\n End If\n\n curC = s.Range(\"C\" & r)\n startR = r\n End If\n\n If s.Range(\"A\" & r) <> \"\" Then oneMoreTime = False ' end the loop for real this time\n r = r + 1\nLoop\n\nlastTime = True\nGoTo seriesAdd\npostLoop:\ncs.Activate\n\nEnd Sub\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
163,365
<p>Let's say that for some reason you need to write a macro: <code>MACRO(X,Y)</code>. <strong>(Let's assume there's a good reason you can't use an inline function.)</strong> You want this macro to emulate a call to a function with no return value.</p> <hr> <h3>Example 1: This should work as expected.</h3> <pre><code>if (x &gt; y) MACRO(x, y); do_something(); </code></pre> <h3>Example 2: This should not result in a compiler error.</h3> <pre><code>if (x &gt; y) MACRO(x, y); else MACRO(y - x, x - y); </code></pre> <h3>Example 3: This should <em>not</em> compile.</h3> <pre><code>do_something(); MACRO(x, y) do_something(); </code></pre> <hr> <p>The naïve way to write the macro is like this:</p> <pre><code>#define MACRO(X,Y) \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; </code></pre> <p>This is a very bad solution which fails all three examples, and I shouldn't need to explain why.</p> <p><strong>Ignore what the macro actually does, that's not the point.</strong></p> <hr> <p>Now, the way I most often see macros written is to enclose them in curly braces, like this:</p> <pre><code>#define MACRO(X,Y) \ { \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; \ } </code></pre> <p>This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon.</p> <hr> <p>Is there a way to write a macro so that it pass all three examples?</p> <hr> <p><i>Note: I am submitting my own answer as part of the <a href="https://stackoverflow.com/questions/162246/is-stack-overflow-appropriate-for-sharing-knowledge-tips-tricks-and-interesting">accepted way of sharing a tip</a>, but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)</i></p>
[ { "answer_id": 163366, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 6, "selected": false, "text": "#define MACRO(X,Y) \\\ndo { \\\n cout << \"1st arg is:\" << (X) << endl; \\\n cout << \"2nd arg is:\" << (Y) << endl; \\\n cout << \"Sum is:\" << ((X)+(Y)) << endl; \\\n} while (0)\n" }, { "answer_id": 163404, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 3, "selected": false, "text": " #define MACRO(...) do { ... } while(false)\n" }, { "answer_id": 163415, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 0, "selected": false, "text": "#define MACRO(X,Y) \\\ncout << \"1st arg is:\" << (X) << endl; \\\ncout << \"2nd arg is:\" << (Y) << endl; \\\ncout << \"Sum is:\" << ((X)+(Y)) << endl\n if (x > y) {\n MACRO(x, y);\n}\ndo_something();\n if (x > y) {\n MACRO(x, y);\n} else {\n MACRO(y - x, x - y);\n}\n do_something();\nMACRO(x, y)\ndo_something();\n" }, { "answer_id": 163417, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 7, "selected": true, "text": "#define MACRO(X,Y) \\\n ( \\\n (cout << \"1st arg is:\" << (X) << endl), \\\n (cout << \"2nd arg is:\" << (Y) << endl), \\\n (cout << \"3rd arg is:\" << ((X) + (Y)) << endl), \\\n (void)0 \\\n )\n (void)0 void MACRO(a++, b++) a b" }, { "answer_id": 163482, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "macro( read_int(file1), read_int(file2) );\n" }, { "answer_id": 163636, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": false, "text": "auto #include <iostream>\nusing namespace std;\n\nint foo( int & i ) { return i *= 10; }\nint bar( int & i ) { return i *= 100; }\n\n#define BADMACRO( X, Y ) do { \\\n cout << \"X=\" << (X) << \", Y=\" << (Y) << \", X+Y=\" << ((X)+(Y)) << endl; \\\n } while (0)\n\n#define MACRO( X, Y ) do { \\\n int x = X; int y = Y; \\\n cout << \"X=\" << x << \", Y=\" << y << \", X+Y=\" << ( x + y ) << endl; \\\n } while (0)\n\nint main() {\n int a = 1; int b = 1;\n BADMACRO( foo(a), bar(b) );\n a = 1; b = 1;\n MACRO( foo(a), bar(b) );\n return 0;\n}\n" }, { "answer_id": 165031, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 4, "selected": false, "text": "#define MACRO(X,Y) \\\ndo { \\\n auto MACRO_tmp_1 = (X); \\\n auto MACRO_tmp_2 = (Y); \\\n using std::cout; \\\n using std::endl; \\\n cout << \"1st arg is:\" << (MACRO_tmp_1) << endl; \\\n cout << \"2nd arg is:\" << (MACRO_tmp_2) << endl; \\\n cout << \"Sum is:\" << (MACRO_tmp_1 + MACRO_tmp_2) << endl; \\\n} while(0)\n" }, { "answer_id": 8590661, "author": "ofavre", "author_id": 508831, "author_profile": "https://Stackoverflow.com/users/508831", "pm_score": 4, "selected": false, "text": "libc6 /usr/include/x86_64-linux-gnu/bits/byteswap.h auto (expr,expr) {} #define MACRO(X,Y) \\\n ( \\\n { \\\n register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \\\n std::cout << \"1st arg is:\" << __x << std::endl; \\\n std::cout << \"2nd arg is:\" << __y << std::endl; \\\n std::cout << \"Sum is:\" << (__x + __y) << std::endl; \\\n __x + __y; \\\n } \\\n )\n register X Y __x + __y; void(); rvalue g++ -pedantic warning: ISO C++ forbids braced-groups within expressions [-pedantic]\n g++ (__extension__ OLD_WHOLE_MACRO_CONTENT_HERE) #define MACRO(X,Y) \\\n (__extension__ ( \\\n { \\\n register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \\\n std::cout << \"1st arg is:\" << __x << std::endl; \\\n std::cout << \"2nd arg is:\" << __y << std::endl; \\\n std::cout << \"Sum is:\" << (__x + __y) << std::endl; \\\n __x + __y; \\\n } \\\n ))\n __typeof__ #define MACRO(X,Y) \\\n (__extension__ ( \\\n { \\\n __typeof__(X) __x = (X); \\\n __typeof__(Y) __y = (Y); \\\n std::cout << \"1st arg is:\" << __x << std::endl; \\\n std::cout << \"2nd arg is:\" << __y << std::endl; \\\n std::cout << \"Sum is:\" << (__x + __y) << std::endl; \\\n __x + __y; \\\n } \\\n ))\n gcc register warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]\n" }, { "answer_id": 40423852, "author": "Quentin", "author_id": 3233393, "author_profile": "https://Stackoverflow.com/users/3233393", "pm_score": 4, "selected": false, "text": "#define MACRO(X,Y) \\\n [&](x_, y_) { \\\n cout << \"1st arg is:\" << x_ << endl; \\\n cout << \"2nd arg is:\" << y_ << endl; \\\n cout << \"Sum is:\" << (x_ + y_) << endl; \\\n }((X), (Y))\n void" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
163,382
<p>I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?</p> <pre><code>public class Test { public static void main(String args[]) { Test t = new Test(); t.testT(null); } public &lt;T extends Test&gt; void testT(Class&lt;T&gt; type) { Class&lt;T&gt; testType = type == null ? Test.class : type; //Error here System.out.println(testType); } } </code></pre> <p><code>Type mismatch: cannot convert from Class&lt;capture#1-of ? extends Test&gt; to Class&lt;T&gt;</code></p> <p>By casting <code>Test.class</code> to <code>Class&lt;T&gt;</code> this compiles with an <code>Unchecked cast</code> warning and runs perfectly.</p>
[ { "answer_id": 163406, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 1, "selected": false, "text": "public class Test {\n public static void main(String args[]) {\n Test t = new Test();\n t.testT(null);\n }\n\n public <T extends Test> void testT(Class<T> type) {\n Class<T> testClass = Test.class;\n System.out.println(testClass);\n }\n}\n\n\nTest.java:10: incompatible types\nfound : java.lang.Class<Test>\nrequired: java.lang.Class<T>\n Class<T> testClass = Test.class;\n" }, { "answer_id": 163413, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 6, "selected": true, "text": "Class<? extends Test> testType = type == null ? Test.class : type;\n Number public <T extends Number> void testNumber(final Class<T> type)\n testNumber(Integer.class);\ntestNumber(Number.class);\n testNumber(String.class);\n Class<Number> numberClass = Number.class;\nClass<Integer> integerClass = numberClass;\n Type mismatch: cannot convert from Class<Number> to Class<Integer> Integer Number Number anumber = new Long(0);\nInteger another = anumber;\n Number Integer Number Number Long Integer Type mismatch: cannot convert from Number to Integer T testNumber(Integer.class) T Integer Class<? extends Number> wildcard = numberClass;\n Class<? extends Number> Number Number" }, { "answer_id": 165246, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "public class SubTest extends Test {\n public static void main(String args[]) {\n Test t = new Test();\n t.testT(new SubTest());\n }\n}\n testT <T> SubTest testType Class<SubTest> Test.class Class<Test> Class<SubTest> testType Class<? extends Test> Class<T>" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
163,389
<p>I have a web application where users enter arbitrary sql queries for later batch processing. We want to validate the syntax of the query without actually executing it. Some of the queries will take a long time, which is why we don't want to execute them. I'm using Oracle's dbms_sql.parse to do this.</p> <p>However, I now have a situation where I need to know the number and type of the result set columns. Is there a way to do this without actually executing the query? That is, to have Oracle parse the query and tell me what the result datatypes/names will be returned when the query is actually executed? I'm using Oracle 10g and and it's a Java 1.5/Servlet 2.4 application.</p> <p>Edit: The users who enter the queries are already users on the database. They authenticate to my app with their database credentials and the queries are executed using those credentials. Therefore they can't put in any query that they couldn't run by just connecting with sqlplus.</p>
[ { "answer_id": 163483, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "import java.sql.*;\n. . .\nConnection conn;\n. . .\nPreparedStatement ps = conn.prepareStatement(\"SELECT * FROM foo\");\nResultSetMetadata rsmd = ps.getMetaData();\nint numberOfColumns = rsmd.getColumnCount();\n" }, { "answer_id": 450336, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 2, "selected": false, "text": "DECLARE \n lv_stat varchar2(100) := 'select blah blah blah';\n lv_cur INTEGER;\n lv_col_cnt INTEGER;\n lv_desc DBMS_SQL.desc_tab;\nBEGIN\n DBMS_SQL.parse(lv_cur,lv_stat,DBMS_SQL.NATIVE);\n DBMS_SQL.describe_columns(lv_cur,lv_col_cnt,lv_desc);\n FOR ndx in lv_desc.FIRST .. lv_desc.LAST LOOP\n DBMS_OUTPUT.PUT_LINE(lv_desc(ndx).col_name ||' '||lv_desc(ndx).col_type);\n END LOOP;\nEND;\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6479/" ]
163,400
<p>I'm working on an upgrade for an existing database that was designed without any of the code to implement the design being considered. Now I've hit a brick wall in terms of implementing the database design in code. I'm certain whether its a problem with the design of the database or if I'm simply not seeing the correct solution on how to what needs to be done. </p> <p>The basic logic stipulates the following:</p> <ol> <li>Users access the online trainings by way of Seats. Users can have multiple Seats.</li> <li>Seats are purchased by companies and have a many-to-many relationship with Products.</li> <li>A Product has a many-to-many relationship with Modules.</li> <li>A Module has a many-to-many relationship with Lessons.</li> <li>Lessons are the end users access for their training.</li> <li>To muddy the waters, for one reason or another some Users have multiple Seats that contain the same Products. </li> <li>Certification takes place on a per Product basis, not on a per Seat basis.</li> <li>Users have a many-to-many relationship with lessons that stores their current status or score for the lesson.</li> <li>Users certify for a Product when they complete all of the Lessons in all of the Modules for the Product.</li> <li>It is also significant to know when all Lessons for a particular Module are completed by a User.</li> <li>Some Seats will be for ReCertification meaning that Users that previously certified for a Product can sign up and take a recertification exam.</li> <li>Due to Rule 11, Users can and will have multiple Certification records.</li> <li>Edit: When a User completes a Lesson (scores better than 80%) then the User has (according to the current business logic) completed the Lesson for all Products and all Seats that contain the Lesson. </ol> <p>The trouble that I keep running into with the current design and the business logic as I've more or less described it is that I can't find a way to effectively tie whether a user has certified for a particular product and seat vs when they have not. I keep hitting snags trying to establish which Products under which Seats have been certified for the User and which haven't. Part of the problem is because if they are currently registered for multiple of the same Product under different Seats, then I have to count the Product only once.</p> <p>Below is a copy of the portion of the schema that's involved. Any suggestions on how to improve the design or draw the association in code would be appreciated. In case it matters, this site is built on the LAMPP stack.</p> <p>You can view the relevant portion of the database schema here: <a href="http://lpsoftware.com/problem_db_structure.png" rel="nofollow noreferrer"><a href="http://lpsoftware.com/problem_db_structure.png" rel="nofollow noreferrer">http://lpsoftware.com/problem_db_structure.png</a></a></p>
[ { "answer_id": 163846, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "CREATE TABLE lessonstatus_rtab (\n user_id INT NOT NULL,\n seat_id INT NOT NULL,\n lesson_id INT NOT NULL REFERENCES lesson_rtab,\n accessdate TIMESTAMP,\n score NUMERIC(5,2) NOT NULL DEFAULT 0,\n PRIMARY KEY (user_id, seat_id, lesson_id),\n FOREIGN KEY (user_id, seat_id) REFERENCES user_seat_rtab (user_id, seat_id)\n);\n SELECT p.name, us.user_id, us.seat_id, COUNT(l.id) = COUNT(lu.lesson_id) AS is_certified\nFROM user_seat_rtab AS us\n JOIN seat_rtab AS s ON (s.id = us.seat_id)\n JOIN product_seat_rtab AS ps ON (ps.seat_id = s.id)\n JOIN product_rtab AS p ON (p.id = ps.product_id)\n JOIN product_module_rtab AS pm ON (pm.product_id = p.id)\n JOIN module_rtab AS m ON (m.id = pm.module_id)\n JOIN module_lesson_rtab AS ml ON (ml.module_id = m.id)\n JOIN lesson_rtab AS l ON (l.id = ml.lesson_id)\n LEFT OUTER JOIN lessonstatus_rtab AS lu \n ON (lu.lesson_id = l.id AND lu.user_id = us.user_id \n AND lu.seat_id = us.seat_id AND lu.score > 0.50)\nGROUP BY p.id, us.user_id, us.seat_id;\n" }, { "answer_id": 166869, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 0, "selected": false, "text": "DROP TABLE user_seat_rtab;\nRENAME TABLE certification_rtab TO something_different;\n ALTER TABLE user_seat_rtab \n DROP PRIMARY KEY;\n ADD COLUMN product_id int(10) unsigned NOT NULL;\n ADD CONSTRAINT pk_user_seat_product PRIMARY KEY (user_id, seat_id, product_id);\n ADD CONSTRAINT fk_product_user_seat FOREIGN KEY (product_id) REFERENCES product_rtab(id) ON DELETE RESTRICT;\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178/" ]
163,407
<p>Is there a way to use Enum values inside a JSP without using scriptlets.</p> <p>e.g. </p> <pre><code>package com.example; public enum Direction { ASC, DESC } </code></pre> <p>so in the JSP I want to do something like this</p> <pre><code>&lt;c:if test="${foo.direction ==&lt;% com.example.Direction.ASC %&gt;}"&gt;... </code></pre>
[ { "answer_id": 163431, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 6, "selected": true, "text": "\n<%@ page import=\"com.example.Direction\" %>\n...\n<p>Direction is <%=foo.direction.getFriendlyName()%></p>\n<% if (foo.direction == Direction.ASC) { %>\n<p>That means you're going to heaven!</p>\n<% } %>\n" }, { "answer_id": 10073363, "author": "Arnoud", "author_id": 494494, "author_profile": "https://Stackoverflow.com/users/494494", "pm_score": 2, "selected": false, "text": "<c:if test=\"${foo.direction == 'ASC'}\">...\n" }, { "answer_id": 48703347, "author": "Mohammed Aslam", "author_id": 866576, "author_profile": "https://Stackoverflow.com/users/866576", "pm_score": 3, "selected": false, "text": "<c:set var=\"ASC\" value=\"<%=Direction.ASC%>\"/>\n<c:if test=\"${foo.direction == ASC}\"></c:if>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332/" ]
163,420
<p>I am trying to print an existing file to PDF programmatically in Visual Basic 2008.</p> <p>Our current relevant assets are: Visual Studio 2008 Professional Adobe Acrobat Professional 8.0</p> <p>I thought about getting a sdk like ITextSharp, but it seem like overkill for what I am trying to do especially since we have the full version of Adobe. </p> <p>Is there a relatively simple bit of code to print to a PDF printer (and of course assign it to print to a specific location) or will it require a the use of another library to print to pdf?</p> <hr> <p>I want to print a previosly created document to a pdf file. In this case it a .snp file that I want to make into a .pdf file, but I think the logic would be the same for any file type.</p> <hr> <p>I just tried the above shell execute, and it will not perform the way I want it to. as it prompts me as to where I want to print and still does not print where I want it to (multiple locations), which is crucial as we create a lot of the same named PDF files (with different data within the PDF and placed in corresponding client folders) </p> <hr> <p>The current process is:</p> <ul> <li>Go to \\report server\client1 </li> <li>create pdf files of all the snp documents in the folder by hand </li> <li>copy the pdf to \\website reports\client1</li> <li>then repeat for all 100+ clients takes roughly two hours to complete and verify</li> </ul> <p>I know this can be done better but I have only been here three months and there were other pressing concerns that were a lot more immediate. I also was not expecting something that looks this trivial to be that hard to code.</p>
[ { "answer_id": 164314, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 2, "selected": false, "text": "'PDF_WILDCARD = \"*.pdf\"\n'PrnName = \"Adobe PDF\"\nSub PrintToPDF(ReportName As String, TempPath As String, _\n OutputName As String, OutputDir As String, _\n Optional RPTOrientation As Integer = 1)\n\n Dim rpt As Report\n Dim NewFileName As String, TempFileName As String\n\n '--- Printer Set Up ---\n DoCmd.OpenReport ReportName, View:=acViewPreview, WindowMode:=acHidden\n Set rpt = Reports(ReportName)\n Set rpt.Printer = Application.Printers(PrnName)\n\n 'Set up orientation\n If RPTOrientation = 1 Then\n rpt.Printer.Orientation = acPRORPortrait\n Else\n rpt.Printer.Orientation = acPRORLandscape\n End If\n\n '--- Print ---\n 'Print (open) and close the actual report without saving changes\n DoCmd.OpenReport ReportName, View:=acViewNormal, WindowMode:=acHidden\n\n ' Wait until file is fully created\n Call waitForFile(TempPath, ReportName & PDF_EXT)\n\n 'DoCmd.Close acReport, ReportName, acSaveNo\n DoCmd.Close acReport, ReportName\n\n TempFileName = TempPath & ReportName & PDF_EXT 'default pdf file name\n NewFileName = OutputDir & OutputName & PDF_EXT 'new file name\n\n 'Trap errors caused by COM interface\n On Error GoTo Err_File\n FileCopy TempFileName, NewFileName\n\n 'Delete all PDFs in the TempPath\n '(which is why you should assign it to a pdf directory)\n On Error GoTo Err_File\n Kill TempPath & PDF_WILDCARD\n\nExit_pdfTest:\n Set rpt = Nothing\n Exit Sub\n\nErr_File: ' Error-handling routine while copying file\n Select Case Err.Number ' Evaluate error number.\n Case 53, 70 ' \"Permission denied\" and \"File Not Found\" msgs\n ' Wait 3 seconds.\n Debug.Print \"Error \" & Err.Number & \": \" & Err.Description & vbCr & \"Please wait a few seconds and click OK\", vbInformation, \"Copy File Command\"\n Call sleep(2, False)\n Resume\n Case Else\n MsgBox Err.Number & \": \" & Err.Description\n Resume Exit_pdfTest\n End Select\n\n Resume\n\nEnd Sub\n\n\n\nSub waitForFile(ByVal pathName As String, ByVal tempfile As String)\n With Application.FileSearch\n .NewSearch\n .LookIn = pathName\n .SearchSubFolders = True\n .filename = tempfile\n .MatchTextExactly = True\n '.FileType = msoFileTypeAllFiles\n End With\n Do While True\n With Application.FileSearch\n If .Execute() > 0 Then\n Exit Do\n End If\n End With\n Loop\nEnd Sub\n\n\n\nPublic Sub sleep(seconds As Single, EventEnable As Boolean)\n On Error GoTo errSleep\n Dim oldTimer As Single\n\n oldTimer = Timer\n Do While (Timer - oldTimer) < seconds\n If EventEnable Then DoEvents\n Loop\n\nerrSleep:\n Err.Clear\nEnd Sub\n" }, { "answer_id": 35310006, "author": "Makhi Ngubane", "author_id": 5267309, "author_profile": "https://Stackoverflow.com/users/5267309", "pm_score": -1, "selected": false, "text": "Imports System.Drawing.Printing\nImports System.Reflection\nImports System.Runtime.InteropServices\nPublic Class Form1\nPrivate Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n Dim pkInstalledPrinters As String\n\n ' Find all printers installed\n For Each pkInstalledPrinters In _\n PrinterSettings.InstalledPrinters\n printList.Items.Add(pkInstalledPrinters)\n Next pkInstalledPrinters\n\n ' Set the combo to the first printer in the list\n If printList.Items.Count > 0 Then\n printList.SelectedItem = 0\n End If\n End Sub\nPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n Try\n\n Dim pathToExecutable As String = \"AcroRd32.exe\"\n Dim sReport = \" \" 'pdf file that you want to print\n 'Dim SPrinter = \"HP9F77AW (HP Officejet 7610 series)\" 'Name Of printer\n Dim SPrinter As String\n SPrinter = printList.SelectedItem\n 'MessageBox.Show(SPrinter)\n Dim starter As New ProcessStartInfo(pathToExecutable, \"/t \"\"\" + sReport + \"\"\" \"\"\" + SPrinter + \"\"\"\")\n Dim Process As New Process()\n Process.StartInfo = starter\n Process.Start()\n Process.WaitForExit(10000)\n Process.Kill()\n Process.Close()\n Catch ex As Exception\n MessageBox.Show(ex.Message) 'just in case if something goes wrong then we can suppress the programm and investigate\n End Try\nEnd Sub\nEnd Class\n" }, { "answer_id": 44762027, "author": "tim.baker", "author_id": 1082555, "author_profile": "https://Stackoverflow.com/users/1082555", "pm_score": -1, "selected": false, "text": " Dim psi As New ProcessStartInfo\n psi.FileName = \"C:\\Users\\User\\file_to_print.pdf\"\n psi.Verb = \"print\"\n Process.Start(psi)\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5578/" ]
163,432
<p>I am using Borland Builder C++. I have a memory leak and I know it must be because of this class I created, but I am not sure how to fix it. Please look at my code-- any ideas would be greatly appreciated!</p> <p>Here's the .h file:</p> <pre><code>#ifndef HeaderH #define HeaderH #include &lt;vcl.h&gt; #include &lt;string&gt; using std::string; class Header { public: //File Header char FileTitle[31]; char OriginatorName[16]; //Image Header char ImageDateTime[15]; char ImageCordsRep[2]; char ImageGeoLocation[61]; NitfHeader(double latitude, double longitude, double altitude, double heading); ~NitfHeader(); void SetHeader(char * date, char * time, double location[4][2]); private: void ConvertToDegMinSec (double angle, AnsiString &amp; s, bool IsLongitude); AnsiString ImageDate; AnsiString ImageTime; AnsiString Latitude_d; AnsiString Longitude_d; double Latitude; double Longitude; double Heading; double Altitude; }; </code></pre> <p>And here is some of the .cpp file:</p> <pre><code>void Header::SetHeader(char * date, char * time, double location[4][2]){ //File Header strcpy(FileTitle,"Cannon Powershot A640"); strcpy(OperatorName,"Camera Operator"); //Image Header //Image Date and Time ImageDate = AnsiString(date); ImageTime = AnsiString(time); AnsiString secstr = AnsiString(ImageTime.SubString(7,2)); AnsiString rounder = AnsiString(ImageDate.SubString(10,1)); int seconds = secstr.ToInt(); //Round off seconds - will this be necessary with format hh:mm:ss in text file? if (rounder.ToInt() &gt; 4) { seconds++; } AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2) + ImageTime.SubString(4,2) + AnsiString(seconds); strcpy(ImageDateTime,dateTime.c_str()); //Image Coordinates Representation strcpy(ImageCordsRep,"G"); //Image Geographic Location AnsiString lat; AnsiString lon; AnsiString locationlat_d; AnsiString locationlon_d; AnsiString corner; for (int i = 0; i &lt; 4; i++){ ConvertToDegMinSec(location[i][0],lat,false); ConvertToDegMinSec(location[i][1],lon,true); if(location[i][0] &lt; 0){ locationlat_d = 'S'; ConvertToDegMinSec(-location[i][0],lat,false); }else if(location[i][0] &gt; 0){ locationlat_d = 'N'; }else locationlat_d = ' '; if(location[i][1] &lt; 0){ locationlon_d = 'W'; ConvertToDegMinSec(-location[i][1],lon,true); }else if(location[i][1] &gt; 0){ locationlon_d = 'E'; }else locationlon_d = ' '; corner += lat + locationlat_d + lon + locationlon_d; } strcpy(ImageGeoLocation,corner.c_str()); } </code></pre> <p>Now when I use the class in main, basically I just create a pointer:</p> <pre><code>Header * header = new Header; header-&gt;SetHeader(t[5],t[6],corners-&gt;location); char * imageLocation = header-&gt;ImageGeoLocation; //do something with imageLocation delete header; </code></pre> <p>Where corners->location is a string from another class, and t[5] and t[6] are both strings. The problem is that imageLocation doesn't contain what is expected, and often just garbage. I have read a lot about memory leaks and pointers, but I am still very new to programming and some of it is quite confusing. Any suggestions would be fabulous!!</p>
[ { "answer_id": 163438, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "main new delete Header main Header header; new delete header;" }, { "answer_id": 163466, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": true, "text": "char ImageCordsRep[1]; strcpy(ImageCordsRep,\"G\");" }, { "answer_id": 163469, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 0, "selected": false, "text": "Header * header = new Header;\nheader->SetHeader(t[5],t[6],corners->location);\nchar * imageLocation = header->ImageGeoLocation;\n" }, { "answer_id": 163486, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 1, "selected": false, "text": "Header * header = new Header;\nheader->SetHeader(t[5],t[6],corners->location);\nchar * imageLocation = header->ImageGeoLocation;\ndelete header;\nprintf(\"ImageLocation is %s\", imageLocation);\n" }, { "answer_id": 163551, "author": "Shishiree", "author_id": 23970, "author_profile": "https://Stackoverflow.com/users/23970", "pm_score": 0, "selected": false, "text": " AnsiString fileType (\"*.jpg\");\n AnsiString path = f + fileType;\n WIN32_FIND_DATA fd;\n HANDLE hFindJpg = FindFirstFile(path.c_str(),&fd);\n\n //Find all images in folder\n TStringList * imageNames = new TStringList;\n\n if (hFindJpg != INVALID_HANDLE_VALUE) {\n do{\n\n if(!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){\n image = AnsiString(fd.cFileName);\n imageNames->Add(image);\n\n jpgFileCount++;\n }\n\n }while(FindNextFile(hFindJpg,&fd));\n }else ShowMessage (\"Cannot find images.\");\n\n FindClose(hFindJpg);\n //char * imageLocation = header->ImageGeoLocation; //as expected\nImage1->Picture->LoadFromFile(imageNames->Strings[j]);\nchar * imageLocation = header->ImageGeoLocation; //puts name of jpg file in imageLocation\n" }, { "answer_id": 163620, "author": "Shishiree", "author_id": 23970, "author_profile": "https://Stackoverflow.com/users/23970", "pm_score": 1, "selected": false, "text": "strcpy() strncpy()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23970/" ]
163,434
<p>There's a school of thought that null values should not be allowed in a relational database. That is, a table's attribute (column) should not allow null values. Coming from a software development background, I really don't understand this. It seems that if null is valid within the context of the attribute, then it should be allowed. This is very common in Java where object references are often null. Not having an extensive database experience, I wonder if I'm missing something here.</p>
[ { "answer_id": 163456, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": false, "text": "NULL NUM_CHILDREN NULL NUM_CHILDREN NULL NUM_CHILDREN NULL" }, { "answer_id": 163510, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 3, "selected": false, "text": "CREATE TABLE Customer (ID int PRIMARY KEY, Name varchar(100) NOT NULL, Address varchar(200) NOT NULL);\nCREATE TABLE CustomerPhone (ID int PRIMARY KEY, Phone varchar(20) NOT NULL, CONSTRAINT FK_CustomerPhone_Customer FOREIGN KEY (ID) REFERENCES Customer (ID));\n" }, { "answer_id": 163523, "author": "Liam Westley", "author_id": 23497, "author_profile": "https://Stackoverflow.com/users/23497", "pm_score": 2, "selected": false, "text": " SELECT FullName = COALESCE(FirstName + ' ', '') + COALESCE(MiddleName+ ' ', '') + COALESCE(FamilyName, '') FROM Person\n" }, { "answer_id": 777883, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "''" }, { "answer_id": 778125, "author": "Andomar", "author_id": 50552, "author_profile": "https://Stackoverflow.com/users/50552", "pm_score": 3, "selected": false, "text": "where bitfield in (1,0)\n select * from mytable\nwhere id not in (select id from excludetable)\n select * from mytable\nwhere id <> NULL and id <> 1\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
163,484
<p>Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely.</p> <p>Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT?</p> <p><strong>Basically, I want to do this without modifying any code, just changing compiler or Windows options.</strong></p> <p>Thanks!</p> <p><a href="http://img519.imageshack.us/img519/853/snapshotbu1.png" rel="nofollow noreferrer" title="Microsoft Visual C++ Debug Library ASSERT">Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png</a></p>
[ { "answer_id": 163561, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": true, "text": "// For custom assert and trace handling with WebDbg\n#ifdef _DEBUG\nCDebugReportHook g_ReportHook;\n#endif\n" }, { "answer_id": 2469460, "author": "MartinP", "author_id": 243879, "author_profile": "https://Stackoverflow.com/users/243879", "pm_score": 0, "selected": false, "text": "_CrtDbgReport _CrtSetReportHook()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5355/" ]
163,492
<p>Wondering if it would ever be useful to index every possible state of an application using some reference keys...</p> <p>Meaning, say we have a program that starts, has only so many possible outcomes, say 8.</p> <p>but if each outcome is attained through stepping through many more logic states, and in between each branch is considered to be a state and is mapped to a key.</p> <p>It could take a lot of memory in large programs but if we could access a key directly (the key could be based on time or depth of logic), then we could instantly traverse through any of the possible situations without having to start the whole process over again with fresh data.</p> <p>Think of it like a tree where the nodes with no children are final outcomes, and every branch between a node and it's parents or children is a 'state', each one keyed differently. So while there are only 8 leaves, or final outcomes of the process, there could be many 'states' depending on how deep the logic goes down the tree before running out of children.</p> <p>Maybe for simulations, but it would take a ton of memory.</p>
[ { "answer_id": 163812, "author": "andy", "author_id": 21482, "author_profile": "https://Stackoverflow.com/users/21482", "pm_score": 1, "selected": false, "text": "for (int i=0; i < 100; i++)\n some_function();\n" }, { "answer_id": 736899, "author": "Triynko", "author_id": 88409, "author_profile": "https://Stackoverflow.com/users/88409", "pm_score": 1, "selected": true, "text": "(2)*(program state size)*(number of initial states)" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
163,497
<p>Is it possible to run a ruby application as a Windows Service? I see that there is a related question which discusses running a <a href="https://stackoverflow.com/questions/25530/best-method-to-run-a-java-application-as-a-nix-daemon-or-windows-service">Java Application as a Windows Service</a>, how can you do this with a Ruby application?</p>
[ { "answer_id": 164365, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 4, "selected": false, "text": "Service.create( :service_name => 'some_service',\n :host => nil,\n :service_type => Service::WIN32_OWN_PROCESS,\n :description => 'A custom service I wrote just for fun',\n :start_type => Service::AUTO_START,\n :error_control => Service::ERROR_NORMAL,\n :binary_path_name => 'c:\\usr\\ruby\\bin\\rubyw.exe -C c:\\tmp\\ bar.rb',\n :load_order_group => 'Network',\n :dependencies => ['W32Time','Schedule'],\n :display_name => 'This is some service' )\n LOG_FILE = 'C:\\\\test.log'\n\nbegin\n require \"rubygems\"\n require 'win32/daemon'\n\n include Win32\n\n class DemoDaemon < Daemon\n\n def service_main\n while running?\n sleep 10\n File.open(\"c:\\\\test.log\", \"a\"){ |f| f.puts \"Service is running #{Time.now}\" } \n end\n end \n\n def service_stop\n File.open(\"c:\\\\test.log\", \"a\"){ |f| f.puts \"***Service stopped #{Time.now}\" }\n exit! \n end\n end\n\n DemoDaemon.mainloop\nrescue Exception => err\n File.open(LOG_FILE,'a+'){ |f| f.puts \" ***Daemon failure #{Time.now} err=#{err} \" }\n raise\nend \n require \"rubygems\"\nrequire \"win32/service\"\n include Win32\n\n\n\n # Create a new service\n Service.create('some_service', nil,\n :service_type => Service::WIN32_OWN_PROCESS,\n :description => 'A custom service I wrote just for fun',\n :start_type => Service::AUTO_START,\n :error_control => Service::ERROR_NORMAL,\n :binary_path_name => 'c:\\usr\\ruby\\bin\\rubyw.exe -C c:\\tmp\\ bar.rb',\n :load_order_group => 'Network',\n :dependencies => ['W32Time','Schedule'],\n \n :display_name => 'This is some service'\n )\n ruby register_bar.rb sc start some_service\n require \"rubygems\"\n require \"win32/service\"\n include Win32\n \n Service.delete(\"some_service\")\n" }, { "answer_id": 14479107, "author": "raubarede", "author_id": 357487, "author_profile": "https://Stackoverflow.com/users/357487", "pm_score": 2, "selected": false, "text": "#####################################################################\n# runneur.rb : service which run (continuously) a process\n# 'do only one simple thing, but do it well'\n#####################################################################\n# Usage:\n# .... duplicate this file : it will be the core-service....\n# .... modify constantes in beginning of this script....\n# .... modify stop_sub_process() at end of this script for clean stop of sub-application..\n#\n# > ruby runneur.rb install foo ; foo==name of service, \n# > ruby runneur.rb uninstall foo\n# > type d:\\deamon.log\" ; runneur traces\n# > type d:\\d.log ; service traces\n#\n#####################################################################\nclass String; def to_dos() self.tr('/','\\\\') end end\nclass String; def from_dos() self.tr('\\\\','/') end end\n\nrubyexe=\"d:/usr/Ruby/ruby19/bin/rubyw.exe\".to_dos\n\n# example with spawn of a ruby process...\n\nSERVICE_SCRIPT=\"D:/usr/Ruby/local/text.rb\"\nSERVICE_DIR=\"D:/usr/Ruby/local\".to_dos\nSERVICE_LOG=\"d:/d.log\".to_dos # log of stdout/stderr of sub-process\nRUNNEUR_LOG=\"d:/deamon.log\" # log of runneur\n\nLCMD=[rubyexe,SERVICE_SCRIPT] # service will do system('ruby text.rb')\nSLEEP_INTER_RUN=4 # at each dead of sub-process, wait n seconds before rerun\n\n################### Installation / Desintallation ###################\nif ARGV[0]\n require 'win32/service'\n include Win32\n\n name= \"\"+(ARGV[1] || $0.split('.')[0])\n if ARGV[0]==\"install\"\n path = \"#{File.dirname(File.expand_path($0))}/#{$0}\".tr('/', '\\\\')\n cmd = rubyexe + \" \" + path\n print \"Service #{name} installed with\\n cmd=#{cmd} ? \" ; rep=$stdin.gets.chomp\n exit! if rep !~ /[yo]/i\n\n Service.new(\n :service_name => name,\n :display_name => name,\n :description => \"Run of #{File.basename(SERVICE_SCRIPT.from_dos)} at #{SERVICE_DIR}\",\n :binary_path_name => cmd,\n :start_type => Service::AUTO_START,\n :service_type => Service::WIN32_OWN_PROCESS | Service::INTERACTIVE_PROCESS\n )\n puts \"Service #{name} installed\"\n Service.start(name, nil)\n sleep(3)\n while Service.status(name).current_state != 'running'\n puts 'One moment...' + Service.status(name).current_state\n sleep 1\n end\n while Service.status(name).current_state != 'running'\n puts ' One moment...' + Service.status(name).current_state\n sleep 1\n end\n puts 'Service ' + name+ ' started' \n elsif ARGV[0]==\"desinstall\" || ARGV[0]==\"uninstall\"\n if Service.status(name).current_state != 'stopped'\n Service.stop(name)\n while Service.status(name).current_state != 'stopped'\n puts 'One moment...' + Service.status(name).current_state\n sleep 1\n end\n end\n Service.delete(name)\n puts \"Service #{name} stopped and uninstalled\"\n\n else\n puts \"Usage:\\n > ruby #{$0} install|desinstall [service-name]\"\n end \n exit!\nend\n\n#################################################################\n# service runneur : service code \n#################################################################\nrequire 'win32/daemon'\ninclude Win32\n\nThread.abort_on_exception=true\nclass Daemon\n def initialize\n @state='stopped'\n super\n log(\"******************** Runneur #{File.basename(SERVICE_SCRIPT)} Service start ***********************\")\n end\n def log(*t)\n txt= block_given?() ? (yield() rescue '?') : t.join(\" \")\n File.open(RUNNEUR_LOG, \"a\"){ |f| f.puts \"%26s | %s\" % [Time.now,txt] } rescue nil\n end\n def service_pause\n #put activity in pause\n @state='pause'\n stop_sub_process\n log { \"service is paused\" }\n end\n def service_resume\n #quit activity from pause\n @state='run'\n log { \"service is resumes\" }\n end\n def service_interrogate\n # respond to quistion status\n log { \"service is interogate\" }\n end\n def service_shutdown \n # stop activities before shutdown\n log { \"service is stoped for shutdown\" }\n end\n\n def service_init\n log { \"service is starting\" }\n end\n def service_main\n @state='run'\n while running?\n begin\n if @state=='run'\n log { \"starting subprocess #{LCMD.join(' ')} in #{SERVICE_DIR}\" }\n @pid=::Process.spawn(*LCMD,{\n chdir: SERVICE_DIR, \n out: SERVICE_LOG, err: :out\n }) \n log { \"sub-process is running : #{@pid}\" }\n a=::Process.waitpid(@pid)\n @pid=nil\n log { \"sub-process is dead (#{a.inspect})\" }\n sleep(SLEEP_INTER_RUN) if @state=='run'\n else\n sleep 3\n log { \"service is sleeping\" } if @state!='run'\n end\n rescue Exception => e\n log { e.to_s + \" \" + e.backtrace.join(\"\\n \")}\n sleep 4\n end\n end\n end\n\n def service_stop\n @state='stopped'\n stop_sub_process\n log { \"service is stoped\" }\n exit!\n end\n def stop_sub_process\n ::Process.kill(\"KILL\",@pid) if @pid\n @pid=nil\n end\nend\n\nDaemon.mainloop\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
163,507
<p>Definition of variables in use:</p> <pre><code>Guid fldProId = (Guid)ffdPro.GetProperty("FieldId"); string fldProValue = (string)ffdPro.GetProperty("FieldValue"); FormFieldDef fmProFldDef = new FormFieldDef(); fmProFldDef.Key = fldProId; fmProFldDef.Retrieve(); string fldProName = (string)fmProFldDef.GetProperty("FieldName"); string fldProType = (string)fmProFldDef.GetProperty("FieldType"); </code></pre> <p>Lines giving the problem (specifically line 4 (hTxtBox.Text = ...)):</p> <pre><code>if (fldProType.ToLower() == "textbox") { Label hTxtBox = (Label)findControl(fldProName); hTxtBox.Text = fldProValue; } </code></pre> <p>All data is gathered from the database correctly, however the label goes screwy. Any ideas?</p>
[ { "answer_id": 163521, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 0, "selected": false, "text": "Label hTxtBox = (Label)findControl(fldProName);\n string fldProName = (string)fmProFldDef.GetProperty(\"FieldName\");\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24565/" ]
163,531
<p>I am creating an installer for an ASP.Net website using WiX. How do you set the ASP.Net version in IIS using WiX?</p>
[ { "answer_id": 163706, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "aspnet_regiis.exe -s W3SVC/1/ROOT/SampleApp1" }, { "answer_id": 200438, "author": "thijs", "author_id": 26796, "author_profile": "https://Stackoverflow.com/users/26796", "pm_score": 6, "selected": true, "text": "<Property Id=\"FRAMEWORKROOT\">\n <RegistrySearch Id=\"FrameworkRootDir\" Root=\"HKLM\"\n Key=\"SOFTWARE\\Microsoft\\.NETFramework\" \n Type=\"directory\" Name=\"InstallRoot\" />\n</Property>\n <!-- Create and configure the virtual directory and application. -->\n<Component Id='WebVirtualDirComponent' Guid='{GUID}' Permanent='no'>\n <iis:WebVirtualDir Id='WebVirtualDir' Alias='YourAlias' Directory='InstallDir' WebSite='DefaultWebSite' DirProperties='DirProperties'>\n <iis:WebApplication Id='WebApplication' Name='YourAppName' WebAppPool='AppPool'>\n <!-- Required to run the application under the .net 2.0 framework -->\n <iis:WebApplicationExtension Extension=\"config\" CheckPath=\"yes\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" />\n <iis:WebApplicationExtension Extension=\"resx\" CheckPath=\"yes\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" />\n <iis:WebApplicationExtension Extension=\"svc\" CheckPath=\"no\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" />\n </iis:WebApplication>\n </iis:WebVirtualDir>\n</Component>\n <RegistrySearch Id=\"FrameworkRootDir\" Root=\"HKLM\"\n Key=\"SOFTWARE\\Microsoft\\.NETFramework\" \n Type=\"directory\" \n Name=\"InstallRoot\" Win64='yes' />\n" }, { "answer_id": 923508, "author": "johnburns320", "author_id": 81005, "author_profile": "https://Stackoverflow.com/users/81005", "pm_score": 4, "selected": false, "text": " <Property Id=\"FRAMEWORKBASEPATH\">\n <RegistrySearch Id=\"FindFrameworkDir\" Root=\"HKLM\" Key=\"SOFTWARE\\Microsoft\\.NETFramework\" Name=\"InstallRoot\" Type=\"raw\"/>\n </Property>\n <Property Id=\"ASPNETREGIIS\" >\n <DirectorySearch Path=\"[FRAMEWORKBASEPATH]\" Depth=\"4\" Id=\"FindAspNetRegIis\">\n <FileSearch Name=\"aspnet_regiis.exe\" MinVersion=\"2.0.5\"/>\n </DirectorySearch>\n </Property>\n\n <CustomAction Id=\"MakeWepApp20\" Directory=\"TARGETDIR\" ExeCommand=\"[ASPNETREGIIS] -norestart -s W3SVC/[WEBSITEID]/ROOT/[VIRTUALDIR]\" Return=\"check\"/>\n\n <InstallExecuteSequence>\n <Custom Action=\"MakeWepApp20\" After=\"InstallFinalize\">ASPNETREGIIS AND NOT Installed</Custom>\n </InstallExecuteSequence>\n" }, { "answer_id": 1374002, "author": "uli78", "author_id": 61434, "author_profile": "https://Stackoverflow.com/users/61434", "pm_score": 3, "selected": false, "text": "<iis:WebServiceExtension Id=\"ExtensionASP2\" Group=\"ASP.NET v2.0.50727\" Allow=\"yes\" File=\"[NETFRAMEWORK20INSTALLROOTDIR]aspnet_isapi.dll\" Description=\"ASP.NET v2.0.50727\"/>\n" }, { "answer_id": 9665684, "author": "Rory MacLeod", "author_id": 1016, "author_profile": "https://Stackoverflow.com/users/1016", "pm_score": 2, "selected": false, "text": "aspnet_regiis aspnet_regiis <Fragment>\n <!-- Use the properties in Wix instead of doing your own registry search. -->\n <PropertyRef Id=\"IISMAJORVERSION\"/>\n <PropertyRef Id=\"NETFRAMEWORK40FULL\"/>\n <PropertyRef Id=\"NETFRAMEWORK40FULLINSTALLROOTDIR\"/>\n\n <!-- The code I'm using is intended for IIS6 and above, and it needs .NET 4 to be\n installed. -->\n <Condition Message=\"This application requires the .NET Framework 4.0. Please install the required version of the .NET Framework, then run this installer again.\">\n <![CDATA[Installed OR (NETFRAMEWORK40FULL)]]>\n </Condition>\n <Condition Message=\"This application requires Windows Server 2003 and Internet Information Services 6.0 or better.\">\n <![CDATA[Installed OR (VersionNT >= 502)]]>\n </Condition>\n\n <!-- Populates the command line for CAQuietExec. IISWEBSITEID and IISVDIRNAME \n could be set to default values, passed in by the user, or set in your installer's \n UI. -->\n <CustomAction Id=\"ConfigureIis60AspNetCommand\" Property=\"ConfigureIis60AspNet\"\n Execute=\"immediate\"\n Value=\"&quot;[NETFRAMEWORK40FULLINSTALLROOTDIR]aspnet_regiis.exe&quot; -norestart -s &quot;W3SVC/[IISWEBSITEID]/ROOT/[IISVDIRNAME]&quot;\" />\n <CustomAction Id=\"ConfigureIis60AspNet\" BinaryKey=\"WixCA\" DllEntry=\"CAQuietExec\" \n Execute=\"deferred\" Return=\"check\" Impersonate=\"no\"/>\n <InstallExecuteSequence>\n <Custom Action=\"ConfigureIis60AspNetCommand\" After=\"CostFinalize\"/>\n\n <!-- Runs the aspnet_regiis command immediately after Wix configures IIS. \n The condition shown here assumes you have a selectable feature in your \n installer with the ID \"WebAppFeature\" that contains your web components. The \n command will not be run if that feature is not being installed, or if IIS is \n not version 6. It *will* run if the application is being repaired. \n\n SKIPCONFIGUREIIS is a property defined by Wix that causes it to skip the IIS\n configuration. -->\n <Custom Action=\"ConfigureIis60AspNet\" After=\"ConfigureIIs\" Overridable=\"yes\">\n <![CDATA[((&WebAppFeature = 3) OR (REINSTALL AND (!WebAppFeature = 3))) \n AND (NOT SKIPCONFIGUREIIS) AND (IISMAJORVERSION = \"#6\")]]>\n </Custom>\n </InstallExecuteSequence>\n <UI>\n <ProgressText Action=\"ConfigureIis60AspNetCommand\"\n >Configuring ASP.NET</ProgressText>\n <ProgressText Action=\"ConfigureIis60AspNet\"\n >Configuring ASP.NET</ProgressText>\n </UI>\n\n</Fragment>\n" }, { "answer_id": 10628243, "author": "LCarter", "author_id": 688126, "author_profile": "https://Stackoverflow.com/users/688126", "pm_score": 1, "selected": false, "text": "<iis:WebServiceExtension Id=\"AMS_AppPool\" Name=\"AccountManagementSVC1\" Identity=\"other\" ManagedPipelineMode=\"integrated\" ManagedRuntimeVersion=\"v4.0\" User=\"AMS_AppPoolUser\" RecycleMinutes=\"120\" />\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
163,535
<p>In implementing my first significant script using jquery I needed to find a specific web-control on the page. Since I work with DotNetNuke, there is no guaranteeing the controls ClientID since the container control may change from site to site. I ended up using an attribute selector that looks for an ID that ends with the control's server ID.</p> <pre><code>$("select[id$='cboPanes']") </code></pre> <p>This seems like it might not be the best method. Is there another way to do this?</p> <hr> <p>@Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others.</p> <p>@toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed.</p> <hr> <p>@Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others.</p> <p>@toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed.</p>
[ { "answer_id": 163566, "author": "toohool", "author_id": 14334, "author_profile": "https://Stackoverflow.com/users/14334", "pm_score": 3, "selected": false, "text": "$(\"#<%= cboPanes.ClientID %>\")\n" }, { "answer_id": 165572, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "<head>\n <script type=\"text/javascript>\n var cboPanesID = <%= cboPanes.ClientID %>;\n </script>\n\n <!-- this JS import references cboPanesID variable declared above -->\n <script src=\"jquery.plugin.js\"></script>\n</head>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820/" ]
163,537
<p>I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.</p>
[ { "answer_id": 163558, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 4, "selected": true, "text": "Log Log.LogMessage(\"My message\");\n" }, { "answer_id": 823680, "author": "si618", "author_id": 44540, "author_profile": "https://Stackoverflow.com/users/44540", "pm_score": 1, "selected": false, "text": "public static void Log(ITask task, string message, MessageImportance importance)\n{\n try\n {\n BuildMessageEventArgs args = new BuildMessageEventArgs(message, string.Empty, \n task.ToString(), importance);\n task.BuildEngine.LogMessageEvent(args);\n }\n catch (NullReferenceException)\n {\n // Don't throw as task and BuildEngine will be null in unit test.\n }\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
163,538
<p>I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?</p>
[ { "answer_id": 163543, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 9, "selected": true, "text": "Assert Debug.Assert" }, { "answer_id": 163555, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 3, "selected": false, "text": "Debug.Assert(x > 2)" }, { "answer_id": 163568, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 5, "selected": false, "text": "Debug.Assert(someObject != null, \"someObject is null! this could totally be a bug!\");\n" }, { "answer_id": 41432168, "author": "Serge Voloshenko", "author_id": 5771669, "author_profile": "https://Stackoverflow.com/users/5771669", "pm_score": 4, "selected": false, "text": "Assert() Trace Debug Debug.Assert() Trace.Assert() int i = 1 + 3;\n // Debug.Assert method in Debug mode fails, since i == 4\n Debug.Assert(i == 3);\n Debug.WriteLine(i == 3, \"i is equal to 3\");\n\n // Trace.Assert method in Release mode is not failing.\n Trace.Assert(i == 4);\n Trace.WriteLine(i == 4, \"i is equla to 4\");\n\n Console.WriteLine(\"Press a key to continue...\");\n Console.ReadLine();\n Debug.Assert Trace.Assert() (i == 4) WriteLine()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
163,542
<p>If I do the following:</p> <pre><code>import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' </code></pre> <p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
[ { "answer_id": 163556, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": false, "text": ">>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)\n>>> p.stdin.write(b'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n') #expects a bytes type object\n>>> p.communicate()[0]\n'four\\nfive\\n'\n>>> p.stdin.close()\n" }, { "answer_id": 165662, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 10, "selected": true, "text": "Popen.communicate() pipe = os.popen(cmd, 'w', bufsize)\n # ==>\n pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin\n from subprocess import Popen, PIPE, STDOUT\n\np = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) \ngrep_stdout = p.communicate(input=b'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')[0]\nprint(grep_stdout.decode())\n# -> four\n# -> five\n# ->\n encoding subprocess.run #!/usr/bin/env python3\nfrom subprocess import run, PIPE\n\np = run(['grep', 'f'], stdout=PIPE,\n input='one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n', encoding='ascii')\nprint(p.returncode)\n# -> 0\nprint(p.stdout)\n# -> four\n# -> five\n# -> \n" }, { "answer_id": 732822, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) \np.stdin.write('one\\n')\ntime.sleep(0.5)\np.stdin.write('two\\n')\ntime.sleep(0.5)\np.stdin.write('three\\n')\ntime.sleep(0.5)\ntestresult = p.communicate()[0]\ntime.sleep(0.5)\nprint(testresult)\n" }, { "answer_id": 10134899, "author": "Michael Waddell", "author_id": 1238190, "author_profile": "https://Stackoverflow.com/users/1238190", "pm_score": 4, "selected": false, "text": "from subprocess import Popen, PIPE\nfrom tempfile import SpooledTemporaryFile as tempfile\nf = tempfile()\nf.write('one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')\nf.seek(0)\nprint Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()\nf.close()\n" }, { "answer_id": 17109481, "author": "Lucien Hercaud", "author_id": 2486227, "author_profile": "https://Stackoverflow.com/users/2486227", "pm_score": 3, "selected": false, "text": "\"\"\"\nEx: Dialog (2-way) with a Popen()\n\"\"\"\n\np = subprocess.Popen('Your Command Here',\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n stdin=PIPE,\n shell=True,\n bufsize=0)\np.stdin.write('START\\n')\nout = p.stdout.readline()\nwhile out:\n line = out\n line = line.rstrip(\"\\n\")\n\n if \"WHATEVER1\" in line:\n pr = 1\n p.stdin.write('DO 1\\n')\n out = p.stdout.readline()\n continue\n\n if \"WHATEVER2\" in line:\n pr = 2\n p.stdin.write('DO 2\\n')\n out = p.stdout.readline()\n continue\n\"\"\"\n..........\n\"\"\"\n\nout = p.stdout.readline()\n\np.wait()\n" }, { "answer_id": 23740991, "author": "Lord Henry Wotton", "author_id": 2426246, "author_profile": "https://Stackoverflow.com/users/2426246", "pm_score": 3, "selected": false, "text": "Popen.communicate(input=s) s s stdin File \"/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py\", line 1130, in _execute_child\n self.pid = os.fork()\nOSError: [Errno 12] Cannot allocate memory" }, { "answer_id": 24982453, "author": "qed", "author_id": 562222, "author_profile": "https://Stackoverflow.com/users/562222", "pm_score": 4, "selected": false, "text": "p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)\nout, err = p.communicate(input='one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n'.encode())\nprint(out)\n" }, { "answer_id": 33482438, "author": "Graham Christensen", "author_id": 637129, "author_profile": "https://Stackoverflow.com/users/637129", "pm_score": 5, "selected": false, "text": "read, write = os.pipe()\nos.write(write, \"stdin input here\")\nos.close(write)\n\nsubprocess.check_call(['your-command'], stdin=read)\n" }, { "answer_id": 41036665, "author": "Flimm", "author_id": 247696, "author_profile": "https://Stackoverflow.com/users/247696", "pm_score": 5, "selected": false, "text": "input stdin output_bytes = subprocess.check_output(\n [\"sed\", \"s/foo/bar/\"],\n input=b\"foo\",\n)\n check_output run call check_call text=True check_output bytes output_string = subprocess.check_output(\n [\"sed\", \"s/foo/bar/\"],\n input=\"foo\",\n text=True,\n)\n" }, { "answer_id": 59495980, "author": "Boris Verkhovskiy", "author_id": 3064538, "author_profile": "https://Stackoverflow.com/users/3064538", "pm_score": 3, "selected": false, "text": "my_data = \"whatever you want\\nshould match this f\"\nsubprocess.run([\"grep\", \"f\"], text=True, input=my_data)\n capture_output=True text=True universal_newlines=True subprocess.run([\"grep\", \"f\"], universal_newlines=True, input=my_data)\n" }, { "answer_id": 66754162, "author": "Ben DeMott", "author_id": 294253, "author_profile": "https://Stackoverflow.com/users/294253", "pm_score": 2, "selected": false, "text": "grep expect pexpect import pexpect\nchild = pexpect.spawn('grep f', timeout=10)\nchild.sendline('text to match')\nprint(child.before)\n ftp import pexpect\nchild = pexpect.spawn ('ftp ftp.openbsd.org')\nchild.expect ('Name .*: ')\nchild.sendline ('anonymous')\nchild.expect ('Password:')\nchild.sendline ('noah@example.com')\nchild.expect ('ftp> ')\nchild.sendline ('ls /pub/OpenBSD/')\nchild.expect ('ftp> ')\nprint child.before # Print the result of the ls command.\nchild.interact() # Give control of the child to the user.\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
163,550
<p>Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that <code>WriteLine()</code> can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code:</p> <pre><code>StreamWriter sw = new StreamWriter(pathToFile); foreach (GridViewRow record in gv_Records.Rows) { string recordInfo = "recordInformation"; sw.WriteLine(recordInfo); } </code></pre>
[ { "answer_id": 163594, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "using (StreamWriter writer = new StreamWriter(@\"somefile.txt\"))\n{\n // ...\n writer.WriteLine(largeAmountsOfData);\n // ...\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
163,552
<p>I have seen <a href="https://stackoverflow.com/questions/87030/where-to-find-java-6-jssejce-source-code">Where to find Java 6 JSSE/JCE Source Code?</a> and asked the question myself <a href="https://stackoverflow.com/questions/150849/how-to-get-jrejdk-with-matching-source">How to get JRE/JDK with matching source?</a> but I don't either of these was specific enough to get the answer I was really after, so I'm going to try a way more specific version of the question.</p> <p>Basically the problem that I am trying to solve is that I would like to be able to use my Eclipse debugger on Windows and step into the Java SSL classes (JSSE) to help me debug SSL issues as well as to just understand the SSL process better. BTW I am familiar with (and use) the javax.net.debug=ssl|all system property to get SSL tracing and, while this is very helpful, I'd still like to be able to step through that pesky code.</p> <p>So what I think I specifically need is:</p> <ol> <li>An executable JRE / JDK implementation (not wanting to build one)...</li> <li>That runs on my Windows platform (XP)...</li> <li>That includes source...</li> <li>And that source includes the SSL "bits" (JSSE, etc.)...</li> <li>And ideally the SSL implementation is Sun's or the OpenJDK version.</li> </ol> <p>I think the closest thing (as noted in PW's answer <a href="https://stackoverflow.com/questions/87030/where-to-find-java-6-jssejce-source-code#87106">StackOverflow: 87106</a>) is the OpenJDK source openjdk-6-src-b12-28_aug_2008.tar.gz found at <a href="http://download.java.net/openjdk/jdk6/" rel="noreferrer">OpenJDK 6 Source Release</a>, but I'm not sure there's a matching executable JDK / JRE for that that would run on Windows.</p>
[ { "answer_id": 5479171, "author": "Dolda2000", "author_id": 134252, "author_profile": "https://Stackoverflow.com/users/134252", "pm_score": 0, "selected": false, "text": "apt-get source openjdk-6 jdk/src/share/classes/javax/net/ssl" }, { "answer_id": 9645563, "author": "Peter", "author_id": 777443, "author_profile": "https://Stackoverflow.com/users/777443", "pm_score": 1, "selected": false, "text": " java.security.Provider provider = new javaxt.ssl.SSLProvider();\n java.security.Security.addProvider(provider);\n SSLContext sslc = SSLContext.getInstance(\"TLS\", \"SSLProvider\");\n" }, { "answer_id": 50742779, "author": "tkr", "author_id": 3779090, "author_profile": "https://Stackoverflow.com/users/3779090", "pm_score": 0, "selected": false, "text": "apt-get install openjdk-8-source\n\ncd tmp\n\nunzip /usr/lib/jvm/openjdk-8/src.zip \"sun/security/*\"\n\nzip -r jsse-src sun \n jsse-src.zip /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/" }, { "answer_id": 51535345, "author": "Teocci", "author_id": 5372008, "author_profile": "https://Stackoverflow.com/users/5372008", "pm_score": 1, "selected": false, "text": "java -version\n java version \"1.8.0_181\"\nJava(TM) SE Runtime Environment (build 1.8.0_181-b13)\nJava HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)\n classes src version=jdk8u\nnode=0cb452d66676\nmkdir ~/temp\ncd ~/temp\nwget http://hg.openjdk.java.net/$version/$version/jdk/archive/$node.zip/src/share/classes/\nunzip $node.zip -d $version-$node\ncd jdk-$node/src/share/classes/\nzip -r $version-$node-src.zip .\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505846/" ]
163,562
<p>I'm looking for some kind of text-parser for ASP.NET that can make HTML from some style of text that uses a special format. Like in Wiki's there is some special syntax for headings and such. I have tried to look on google, but I did not found anything for .NET.</p> <p>Do someone know about a library for .NET that can parse the text to HTML wiki-style? I't don't have to be the same syntax as a Wiki? If no, how whould be the best way to design such a system your self?</p> <p>Thanks in advance</p>
[ { "answer_id": 197281, "author": "Cody Hatch", "author_id": 17086, "author_profile": "https://Stackoverflow.com/users/17086", "pm_score": 2, "selected": false, "text": "*italics* **bold** _italics_ *bold* 3. Test1\n2. Test2\n1. Test3 \n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11559/" ]
163,563
<p>I have an issue - </p> <p>The javascript <code>Date("mm-dd-yyyy")</code> constructor doesn't work for FF. It works fine for IE.</p> <ul> <li>IE : <code>new Date("04-02-2008")</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> <li>FF2 : <code>new Date("04-02-2008")</code> => <code>Invalid Date</code> </li> </ul> <p>So lets try another constructor. Trying this constructor <code>Date("yyyy", "mm", "dd")</code></p> <ul> <li>IE : <code>new Date("2008", "04", "02");</code> => <code>"Fri May 2 00:00:00 EDT 2008"</code></li> <li>FF : <code>new Date("2008", "04", "02");</code> => <code>"Fri May 2 00:00:00 EDT 2008"</code></li> <li>IE : <code>new Date("2008", "03", "02");</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> <li>FF : <code>new Date("2008", "03", "02");</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> </ul> <p>So the <code>Date("yyyy", "mm", "dd")</code> constructor uses an index of <code>0</code> to represent January. </p> <p>Has anyone dealt with this?<br> There must be a better way than subtracting 1 from the months.</p>
[ { "answer_id": 163584, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 7, "selected": true, "text": "month new Date(\"04/02/2008\");\n new Date(2008, 3, 2);\n" }, { "answer_id": 164821, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 1, "selected": false, "text": "var myDate = \"2008,03,02\".split(\",\");\nvar theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \nalert(theDate);\n" }, { "answer_id": 744134, "author": "joedotnot", "author_id": 90259, "author_profile": "https://Stackoverflow.com/users/90259", "pm_score": 4, "selected": false, "text": "var myDateArray = \"2008-03-02\".split(\"-\");\nvar theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]); \nalert(theDate);\n" }, { "answer_id": 5550829, "author": "Frank", "author_id": 692733, "author_profile": "https://Stackoverflow.com/users/692733", "pm_score": 2, "selected": false, "text": "var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \n myDate[1]-1 myDate[2]" }, { "answer_id": 11523950, "author": "Constantine M", "author_id": 733971, "author_profile": "https://Stackoverflow.com/users/733971", "pm_score": 2, "selected": false, "text": "var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \n new Date(\"2012\", \"11\", \"57\") // Date {Sat Jan 26 2013 00:00:00 GMT+0530 (IST)}\n new Date(\"2012\", \"11\", \"57\", \"57\") //Date {Mon Jan 28 2013 09:00:00 GMT+0530 (IST)}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7617/" ]
163,569
<p>I have a Flex application that calls a function which searches a large document collection. Depending on the search term, the user may want to stop the request from flex. </p> <p>I’d like to not only stop the flex application from expecting the request, but also stop the CFC request. Is this possible? What’s the best approach for doing this?</p>
[ { "answer_id": 163790, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "<cfabort/> <cfsetting requesttimeout=\"0\"/>" }, { "answer_id": 163821, "author": "Dan Cramer", "author_id": 3274, "author_profile": "https://Stackoverflow.com/users/3274", "pm_score": 1, "selected": false, "text": "<cfthread>" }, { "answer_id": 180145, "author": "Dan Roberts", "author_id": 8345, "author_profile": "https://Stackoverflow.com/users/8345", "pm_score": 3, "selected": true, "text": "<cffunction name=\"createProcess\" output=\"false\">\n <cfset var id = createUUID()>\n <cfset application.processInfo[id] = {\n progress = 0,\n kill = false\n }>\n <cfreturn id />\n</cffunction>\n <cffunction name=\"getProcessProgress\" output=\"false\">\n <cfargument name=\"processID\" required=\"true\">\n <cfreturn application.processInfo[arguments.processID].progress />\n</cffunction>\n\n<cffunction name=\"killProcess\" output=\"false\">\n <cfargument name=\"processID\" required=\"true\">\n <cfset application.processInfo[arguments.processID].kill = true />\n</cffunction>\n <cffunction name=\"shouldKillProcess\" output=\"false\">\n <cfargument name=\"processID\" required=\"true\">\n <cfreturn application.processInfo[arguments.processID].kill />\n</cffunction>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24563/" ]
163,591
<p>In the GNOME Terminal, Bash does smart auto-completion. For example</p> <pre><code>apt-get in&lt;TAB&gt; </code></pre> <p>becomes</p> <pre><code>apt-get install </code></pre> <p>In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source <code>/etc/bash_completion</code>. The above example sticks as <code>in</code> or auto-completes with a filename in the current directory rather than a valid <code>apt-get</code> command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in <code>shell-mode</code>?</p>
[ { "answer_id": 220960, "author": "Steve Lacey", "author_id": 11077, "author_profile": "https://Stackoverflow.com/users/11077", "pm_score": 4, "selected": false, "text": "(global-set-key \"\\M-\\r\" 'shell-resync-dirs)\n" }, { "answer_id": 28618762, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 3, "selected": false, "text": "M-x term term-mode eshell zsh .inputrc # I like this!\nset editing-mode emacs\n\n# Don't strip characters to 7 bits when reading.\nset input-meta on\n\n# Allow iso-latin1 characters to be inserted rather than converted to\n# prefix-meta sequences.\nset convert-meta off\n\n# Display characters with the eighth bit set directly rather than as\n# meta-prefixed characters.\nset output-meta on\n\n# Ignore hidden files.\nset match-hidden-files off\n\n# Ignore case (on/off).\nset completion-ignore-case on\n\nset completion-query-items 100\n\n# First tab suggests ambiguous variants.\nset show-all-if-ambiguous on\n\n# Replace common prefix with ...\nset completion-prefix-display-length 1\n\nset skip-completed-text off\n\n# If set to 'on', completed directory names have a slash appended. The default is 'on'.\nset mark-directories on\nset mark-symlinked-directories on\n\n# If set to 'on', a character denoting a file's type is appended to the\n# filename when listing possible completions. The default is 'off'.\nset visible-stats on\n\nset horizontal-scroll-mode off\n\n$if Bash\n\"\\C-x\\C-e\": edit-and-execute-command\n$endif\n\n# Define my favorite Emacs key bindings.\n\"\\C-@\": set-mark\n\"\\C-w\": kill-region\n\"\\M-w\": copy-region-as-kill\n\n# Ctrl+Left/Right to move by whole words.\n\"\\e[1;5C\": forward-word\n\"\\e[1;5D\": backward-word\n# Same with Shift pressed.\n\"\\e[1;6C\": forward-word\n\"\\e[1;6D\": backward-word\n\n# Ctrl+Backspace/Delete to delete whole words.\n\"\\e[3;5~\": kill-word\n\"\\C-_\": backward-kill-word\n\n# UP/DOWN filter history by typed string as prefix.\n\"\\e[A\": history-search-backward\n\"\\C-p\": history-search-backward\n\"\\eOA\": history-search-backward\n\"\\e[B\": history-search-forward\n\"\\C-n\": history-search-forward\n\"\\eOB\": history-search-forward\n\n# Bind 'Shift+TAB' to complete as in Python TAB was need for another purpose.\n\"\\e[Z\": complete\n# Cycling possible completion forward and backward in place.\n\"\\e[1;3C\": menu-complete # M-Right\n\"\\e[1;3D\": menu-complete-backward # M-Left\n\"\\e[1;5I\": menu-complete # C-TAB\n .bashrc ~/.bash_history set -o emacs\n\nif [[ $- == *i* ]]; then\n bind '\"\\e/\": dabbrev-expand'\n bind '\"\\ee\": edit-and-execute-command'\nfi\n .emacs (setq term-buffer-maximum-size (lsh 1 14))\n\n(eval-after-load 'term\n '(progn\n (defun my-term-send-delete-word-forward () (interactive) (term-send-raw-string \"\\ed\"))\n (defun my-term-send-delete-word-backward () (interactive) (term-send-raw-string \"\\e\\C-h\"))\n (define-key term-raw-map [C-delete] 'my-term-send-delete-word-forward)\n (define-key term-raw-map [C-backspace] 'my-term-send-delete-word-backward)\n (defun my-term-send-forward-word () (interactive) (term-send-raw-string \"\\ef\"))\n (defun my-term-send-backward-word () (interactive) (term-send-raw-string \"\\eb\"))\n (define-key term-raw-map [C-left] 'my-term-send-backward-word)\n (define-key term-raw-map [C-right] 'my-term-send-forward-word)\n (defun my-term-send-m-right () (interactive) (term-send-raw-string \"\\e[1;3C\"))\n (defun my-term-send-m-left () (interactive) (term-send-raw-string \"\\e[1;3D\"))\n (define-key term-raw-map [M-right] 'my-term-send-m-right)\n (define-key term-raw-map [M-left] 'my-term-send-m-left)\n ))\n\n(defun my-term-mode-hook ()\n (goto-address-mode 1))\n(add-hook 'term-mode-hook #'my-term-mode-hook)\n C-x o (unless\n (ignore-errors\n (require 'ido)\n (ido-mode 1)\n (global-set-key [?\\s-d] #'ido-dired)\n (global-set-key [?\\s-f] #'ido-find-file)\n t)\n (global-set-key [?\\s-d] #'dired)\n (global-set-key [?\\s-f] #'find-file))\n\n(defun my--kill-this-buffer-maybe-switch-to-next ()\n \"Kill current buffer. Switch to next buffer if previous command\nwas switching to next buffer or this command itself allowing\nsequential closing of uninteresting buffers.\"\n (interactive)\n (let ( (cmd last-command) )\n (kill-buffer (current-buffer))\n (when (memq cmd (list 'next-buffer this-command))\n (next-buffer))))\n(global-set-key [s-delete] 'my--kill-this-buffer-maybe-switch-to-next)\n(defun my--backward-other-window ()\n (interactive)\n (other-window -1))\n(global-set-key [s-up] #'my--backward-other-window)\n(global-set-key [s-down] #'other-window)\n(global-set-key [s-tab] 'other-window)\n super term-raw-map super Win .xmodmaprc ! To load this config run:\n! $ xmodmap .xmodmaprc\n\n! Win key.\nclear mod3\nclear mod4\n\nkeycode 133 = Super_L\nkeycode 134 = Hyper_R\nadd mod3 = Super_L\nadd mod4 = Hyper_R\n C-c C-j C-c C-k Shift-Insert xterm" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
163,603
<p>I have a web application written using CherryPy, which is run locally on <code>127.0.0.1:4321</code>. We use mod-rewrite and mod-proxy to have Apache act as a reverse proxy; Apache also handles our SSL encryption and may eventually be used to transfer all of our static content.</p> <p>This all works just fine for small workloads. However, I recently used <code>urllib2</code> to write a stress-testing script that would simulate a workload of 100 clients. After some time, each client gets a 503 error from Apache, indicating that Apache cannot connect to <code>127.0.0.1:4321</code>. CherryPy is functioning properly, but my Apache error log reveals lines like the following:</p> <p><code>[Thu Oct 02 12:55:44 2008] [error] (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : proxy: HTTP: attempt to connect to 127.0.0.1:4321 (*) failed</code></p> <p>Googling for this error reveals that Apache has probably run out of socket file descriptors. Since I only have 100 clients running, this implies that the connections are not being closed, either between my <code>urllib2</code> connection and Apache (I am definitely calling <code>.close()</code> on the return value of <code>urlopen</code>), or between Apache and CherryPy.</p> <p>I've confirmed that my <code>urllib2</code> request is sending an HTTP <code>Connection: close</code> header, although Apache is configured with <code>KeepAlive On</code> if that matters.</p> <p>In case it matters, I'm using Python 2.5, Apache 2.2, CherryPy 3.0.3, and the server is running on Windows Server 2003.</p> <p>So what's my next step to stop this problem?</p>
[ { "answer_id": 164769, "author": "fumanchu", "author_id": 23692, "author_profile": "https://Stackoverflow.com/users/23692", "pm_score": 4, "selected": true, "text": "SetEnv proxy-nokeepalive 1" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
163,604
<p>I'm trying to select a random 10% sampling from a small table. I thought I'd just use the RAND() function and select those rows where the random number is less than 0.10:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND() &lt; 0.10 </code></pre> <p>But I soon discovered that RAND() always returns the same number! Reminds me of this <a href="http://xkcd.com/221/" rel="nofollow noreferrer">xkcd cartoon</a>.</p> <p><img src="https://imgs.xkcd.com/comics/random_number.png"></p> <p>OK, no problem, the RAND function takes a seed value. I will be running this query periodically, and I want it to give different results if I run it on a different day, so I seed it with a combination of the date and a unique row ID:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND(CAST(GETDATE) AS INTEGER) + RowID) &lt; 0.10 </code></pre> <p>I still don't get any results! When I show the random numbers returned by RAND, I discover that they're all within a narrow range. It appears that getting a random number from RAND requires you to use a random seed. If I had a random seed in the first place, I wouldn't need a random number!</p> <p>I've seen the previous discussions related to this problem: </p> <p><a href="https://stackoverflow.com/questions/52964/sql-server-random-sort">SQL Server Random Sort</a><br> <a href="https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql">How to request a random row in SQL?</a></p> <p>They don't help me. TABLESAMPLE works at the page level, which is great for a big table but not for a small one, and it looks like it applies prior to the WHERE clause. TOP with NEWID doesn't work because I don't know ahead of time how many rows I want.</p> <p>Anybody have a solution, or at least a hint?</p> <p><strong>Edit:</strong> Thanks to AlexCuse for a <a href="https://stackoverflow.com/questions/163604/what-am-i-doing-wrong-when-using-rand-in-ms-sql-server-2005#163843">solution</a> which works for my particular case. Now to the larger question, how to make RAND behave?</p>
[ { "answer_id": 163615, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND 0*rowid+RAND() < 0.10\n RAND()" }, { "answer_id": 163843, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 4, "selected": true, "text": "select top 10 percent * from MyTable order by NEWID()\n CREATE VIEW RandView AS \n\nSELECT RAND() AS Val\n\nGO\n\nCREATE FUNCTION RandomFloat()\nRETURNS FLOAT\nAS\nBEGIN\n\nRETURN (SELECT Val FROM RandView)\n\nEND\n select blah, dbo.RandomFloat() from table" }, { "answer_id": 164195, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 1, "selected": false, "text": "select * from SomeTable\nwhere rand(0*SomeTableID + cast(cast(newid() as binary(4)) as int)) <= 0.10\n" }, { "answer_id": 4806011, "author": "Jonas Stensved", "author_id": 348841, "author_profile": "https://Stackoverflow.com/users/348841", "pm_score": 0, "selected": false, "text": "SELECT TOP 10 PERCENT * FROM schema.MyTable ORDER BY NEWID()\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5987/" ]
163,610
<p>I run a browser based game at www.darknovagames.com. Recently, I've been working on reformatting the site with CSS, trying to get all of its pages to verify according to the HTML standard.</p> <p>I've been toying with this idea of having the navigation menu on the left AJAX the pages in (rather than taking the user to a separate page each time, requiring a reload of the title and nav bar, which almost never change) and I know that if I do so, I will probably break the Forward/Back buttons in the browser. My question I guess is, should I go ahead and AJAX the site, thus requiring the user to use the sites navigation to play the game, or should I leave the site as it currently stands, and use standard hyperlinks and things for navigation?</p> <p>The reason I ask I guess is that I built a forums system into the site, and a lot of times I would want to link say to a particular topic within the forums.</p> <p>I'm also open to suggestions. Is there a standard (preferably without traditional frames) way to make only the body area of the site reload, while still changing the URL so that users can bookmark and forward/back, etc? That could potentially solve my problem as well. I'm just asking for the best solution here, not an answer to a specific question. ^_^</p> <p>Thanks</p>
[ { "answer_id": 10234045, "author": "Nikita Koksharov", "author_id": 764206, "author_profile": "https://Stackoverflow.com/users/764206", "pm_score": 2, "selected": false, "text": "Path.map(\"#/page\").to(function(){\n alert('page!');\n});\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
163,628
<p>When placing email addresses on a webpage do you place them as text like this:</p> <pre><code>joe.somebody@company.com </code></pre> <p>or use a clever trick to try and fool the email address harvester bots? For example:</p> <p><strong>HTML Escape Characters:</strong></p> <pre><code>&amp;#106;&amp;#111;&amp;#101;&amp;#46;&amp;#115;&amp;#111;&amp;#109;&amp;#101;&amp;#98;&amp;#111;&amp;#100;&amp;#121;&amp;#64;&amp;#99;&amp;#111;&amp;#109;&amp;#112;&amp;#97;&amp;#110;&amp;#121;&amp;#46;&amp;#99;&amp;#111;&amp;#109; </code></pre> <p><strong>Javascript Decrypter:</strong></p> <pre><code>function XOR_Crypt(EmailAddress) { Result = new String(); for (var i = 0; i &lt; EmailAddress.length; i++) { Result += String.fromCharCode(EmailAddress.charCodeAt(i) ^ 128); } document.write(Result); } XOR_Crypt("êïå®óïíåâïäùÀãïíðáîù®ãïí"); </code></pre> <p><strong>Human Decode:</strong></p> <pre><code>joe.somebodyNOSPAM@company.com joe.somebody AT company.com </code></pre> <p>What do you use or do you even bother?</p>
[ { "answer_id": 163784, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "<a href=\"#\" class=\"--mailto--john--domain--com-- other classes goes here\" />\n // match all a-elements with \"--mailto--\" somehere in the class property\n$(\"a[class*='--mailto--']\").each(function ()\n{\n /*\n for each of those elements use a regular expression to pull\n out the data you need to construct a valid e-mail adress\n */\n var validEmailAdress = this.className.match();\n\n $(this).click(function ()\n {\n window.location = validEmailAdress;\n });\n});\n" }, { "answer_id": 163840, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "Dim rxEmailLink As New Regex(\"<a\\b[^>]*mailto:\\b[^>]*>(.*?)</a>\")\nDim m As Match = rxEmailLink.Match(Html)\nWhile m.Success\n Dim strEntireLinkOrig As String = m.Value\n Dim strEntireLink As String = strEntireLinkOrig\n strEntireLink = strEntireLink.Replace(\"'\", \"\"\"\") ' replace any single quotes with double quotes to make sure the javascript is well formed\n Dim rxLink As New Regex(\"(<a\\b[^>]*mailto:)([\\w.\\-_^@]*@[\\w.\\-_^@]*)(\\b[^>]*?)>(.*?)</a>\")\n Dim rxLinkMatch As Match = rxLink.Match(strEntireLink)\n Dim strReplace As String = String.Format(\"<script language=\"\"JavaScript\"\">document.write('{0}{1}{2}>{3}</a>');</script>\", _\n RandomlyChopStringJS(rxLinkMatch.Groups(1).ToString), _\n ConvertToAsciiHex(rxLinkMatch.Groups(2).ToString), _\n rxLinkMatch.Groups(3), _\n ConvertToHtmlEntites(rxLinkMatch.Groups(4).ToString))\n Result = Result.Replace(strEntireLinkOrig, strReplace)\n m = m.NextMatch()\nEnd While\n Public Function RandomlyChopStringJS(ByVal s As String) As String\n Dim intChop As Integer = Int(6 * Rnd()) + 1\n Dim intCount As Integer = 0\n RandomlyChopStringJS = \"\"\n If Not s Is Nothing AndAlso Len(s) > 0 Then\n For Each c As Char In s.ToCharArray()\n If intCount = intChop Then\n RandomlyChopStringJS &= \"'+'\"\n intChop = Int(6 * Rnd()) + 1\n intCount = 0\n End If\n RandomlyChopStringJS &= c\n intCount += 1\n Next\n End If\n End Function\n <script language=\"JavaScript\">document.write('<a '+'clas'+'s='+'\"Mail'+'Link'+'\" hr'+'ef'+'=\"ma'+'ilto:%69%6E%66%6F%40%62%69%63%75%73%61%2E%6F%72%67\">&#105;&#110;&#102;&#111;&#64;&#98;&#105;&#99;&#117;&#115;&#97;&#46;&#111;&#114;&#103;</a>');</script>\n" }, { "answer_id": 296970, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<a href=\"mailto:userhatestogetspam@example.com\" \n onclick=\"this.href=this.href.replace(/hatestogetspam/,'')\">\n" }, { "answer_id": 483224, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 2, "selected": false, "text": "[at] @ // PHP example\n// encodes every character using URL encoding (%hh)\nfunction foo($str) {\n $retVal = '';\n $length = strlen($str);\n for ($i=0; $i<$length; $i++) $retVal.=sprintf('%%%X', ord($str[$i]));\n return $retVal;\n}\n// encodes every character into HTML character references (&#xhh;)\nfunction bar($str) {\n $retVal = '';\n $length = strlen($str);\n for ($i=0; $i<$length; $i++) $retVal.=sprintf('&#x%X;', ord($str[$i]));\n return $retVal;\n}\n\n$email = 'user@example.com';\necho '<a href=\"'.bar('mailto:?to=' . foo(','.$email.'')).'\">mail me</a>';\n\n// output\n// <a href=\"&#x6D;&#x61;&#x69;&#x6C;&#x74;&#x6F;&#x3A;&#x3F;&#x74;&#x6F;&#x3D;&#x25;&#x32;&#x43;&#x25;&#x37;&#x35;&#x25;&#x37;&#x33;&#x25;&#x36;&#x35;&#x25;&#x37;&#x32;&#x25;&#x34;&#x30;&#x25;&#x36;&#x35;&#x25;&#x37;&#x38;&#x25;&#x36;&#x31;&#x25;&#x36;&#x44;&#x25;&#x37;&#x30;&#x25;&#x36;&#x43;&#x25;&#x36;&#x35;&#x25;&#x32;&#x45;&#x25;&#x36;&#x33;&#x25;&#x36;&#x46;&#x25;&#x36;&#x44;\">mail me</a>\n" }, { "answer_id": 483225, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 2, "selected": false, "text": "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#109;&#101;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;\">email me</A>\n" }, { "answer_id": 483239, "author": "roundcrisis", "author_id": 162325, "author_profile": "https://Stackoverflow.com/users/162325", "pm_score": 7, "selected": false, "text": "span.reverse {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n <span class=\"reverse\">moc.rehtrebttam@retsambew</span>\n" }, { "answer_id": 483252, "author": "mati", "author_id": 58128, "author_profile": "https://Stackoverflow.com/users/58128", "pm_score": 4, "selected": false, "text": "<img src=\"scriptname.php\">\n <?php\nheader(\"Content-type: image/png\");\n// Your email address which will be shown in the image\n$email = \"you@yourdomain.com\";\n$length = (strlen($email)*8);\n$im = @ImageCreate ($length, 20)\n or die (\"Kann keinen neuen GD-Bild-Stream erzeugen\");\n$background_color = ImageColorAllocate ($im, 255, 255, 255); // White: 255,255,255\n$text_color = ImageColorAllocate ($im, 55, 103, 122);\nimagestring($im, 3,5,2,$email, $text_color);\nimagepng ($im);\n?>\n" }, { "answer_id": 483430, "author": "ofaurax", "author_id": 15209, "author_profile": "https://Stackoverflow.com/users/15209", "pm_score": 3, "selected": false, "text": "onclick=\"this.href='mailto:' + 'admin' + '&#x40;' + 'domain.com'\"\n" }, { "answer_id": 484654, "author": "xaddict", "author_id": 59159, "author_profile": "https://Stackoverflow.com/users/59159", "pm_score": 1, "selected": false, "text": "<button> <input type=\"button\"> <html>\n<body>\n<script type=\"text/javascript\">\n e1=\"@domain\";\n e2=\"me\";\n e3=\".extension\";\nemail_link=\"mailto:\"+e2+e1+e3;\n</script>\n<input type=\"text\" onClick=\"this.onClick=window.open(email_link);\" value=\"Click for mail\"/>\n<input type=\"text\" onClick=\"this.value=email;\" value=\"Click for mail-address\"/>\n<input type=\"button\" onClick=\"this.onClick=window.open(email_link);\" value=\"Click for mail\"/>\n<input type=\"button\" onClick=\"this.value=email;\" value=\"Click for mail-address\"/>\n</body></html>\n" }, { "answer_id": 3395273, "author": "SimonDowdles", "author_id": 302341, "author_profile": "https://Stackoverflow.com/users/302341", "pm_score": 3, "selected": false, "text": "function myobfiscate($emailaddress){\n $email= $emailaddress; \n $length = strlen($email); \n for ($i = 0; $i < $length; $i++){ \n $obfuscatedEmail .= \"&#\" . ord($email[$i]).\";\";\n }\n echo $obfuscatedEmail;\n}\n <a href=\"mailto:<?php echo myobfiscate('someone@somewhere.com'); ?>\"\ntitle=\"Email me!\"><?php echo myobfiscate('someone@somewhere.com');?> </a>\n" }, { "answer_id": 7308749, "author": "Haluk", "author_id": 174559, "author_profile": "https://Stackoverflow.com/users/174559", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n$(document).ready(function() {\n str1=\"mailto:\";\n str2=\"info\";\n str3=\"@test.com\";\n $(\"#email_a\").attr(\"href\", str1+str2+str3);\n\n});\n</script>\n\n<a href=\"#\" id=\"email_a\"><img src=\"sample.png\"/></a>\n" }, { "answer_id": 10300743, "author": "Fuhrmanator", "author_id": 1168342, "author_profile": "https://Stackoverflow.com/users/1168342", "pm_score": 7, "selected": false, "text": "<!--#include file=\"emailObfuscator.include\" --> emailObfuscator.include <!-- // http://lists.evolt.org/archive/Week-of-Mon-20040202/154813.html -->\n<script type=\"text/javascript\">\n function gen_mail_to_link(lhs,rhs,subject) {\n document.write(\"<a href=\\\"mailto\");\n document.write(\":\" + lhs + \"@\");\n document.write(rhs + \"?subject=\" + subject + \"\\\">\" + lhs + \"@\" + rhs + \"<\\/a>\");\n }\n</script>\n <script type=\"text/javascript\"> \n gen_mail_to_link('john.doe','example.com','Feedback about your site...');\n</script>\n<noscript>\n <em>Email address protected by JavaScript. Activate JavaScript to see the email.</em>\n</noscript>\n" }, { "answer_id": 13282029, "author": "Abdalla Mohamed Aly Ibrahim", "author_id": 1641233, "author_profile": "https://Stackoverflow.com/users/1641233", "pm_score": 1, "selected": false, "text": "<p>myname<img src=\"http://www.traidnt.net/vb/images/mail2.gif\" width=\"11\" height=\"9\" alt=\"@\" />domain.com</p>\n" }, { "answer_id": 14097794, "author": "Donny", "author_id": 1939034, "author_profile": "https://Stackoverflow.com/users/1939034", "pm_score": 0, "selected": false, "text": "onclick=\"p1='admin'; p2='domain.com'; this.href='mailto:' + p1 + '& #x40;' + p2\"\n" }, { "answer_id": 14137666, "author": "Johann de Vries", "author_id": 1939080, "author_profile": "https://Stackoverflow.com/users/1939080", "pm_score": 2, "selected": false, "text": "<bdo dir=\"rtl\">moc.elpmaxe@nosrep</bdo>\nResult : person@example.com\n CSS:\n.reverse { unicode-bidi:bidi-override; direction:rtl; }\nHTML:\n<span class=\"reverse\">moc.elpmaxe@nosrep</span>\nResult : person@example.com\n" }, { "answer_id": 16287550, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 1, "selected": false, "text": "joe&#064;mail.com\n joe@mail.com\n" }, { "answer_id": 18419069, "author": "Jani Hyytiäinen", "author_id": 611056, "author_profile": "https://Stackoverflow.com/users/611056", "pm_score": 3, "selected": false, "text": "<div data-bind=\"foreach: contacts\">\n <div class=\"contact\">\n <div>\n <h5 data-bind=\"text: firstName + ' ' + lastName + ' / ' + department\"></h5>\n <ul>\n <li>Phone: <span data-bind=\"text: phone\"></span></li>\n <li><a href=\"#999\" data-bind=\"click:$root.reveal\">E-mail</a> <span data-bind=\"visible: $root.msgMeToThis() != ''\"><input class=\"merged\" data-bind=\"value: mPrefix\" readonly=\"readonly\" /><span data-bind=\"text: '@' + domain\"></span></span></li>\n </ul>\n </div>\n </div>\n</div>\n function ViewModel(){\n var self = this;\n\n self.contacts = ko.observableArray([\n { firstName:'John', mPrefix: 'john.doe', domain: 'domain.com', lastName: 'Doe', department: 'Sales', phone: '+358 12 345 6789' },\n { firstName:'Joe', mPrefix: 'joe.w', domain: 'wonder.com', lastName: 'Wonder', department: 'Time wasting', phone: '+358 98 765 4321' },\n { firstName:'Mike', mPrefix: 'yo', domain: 'rappin.com', lastName: 'Rophone', department: 'Audio', phone: '+358 11 222 3333' }\n ]);\n self.msgMeToThis = ko.observable('');\n self.reveal = function(m, e){\n var name = e.target.attributes.href.value;\n name = name.replace('#', '');\n self.msgMeToThis(name);\n };\n}\nvar viewModel = new ViewModel();\nko.applyBindings(viewModel);\n" }, { "answer_id": 18428998, "author": "Jani Hyytiäinen", "author_id": 611056, "author_profile": "https://Stackoverflow.com/users/611056", "pm_score": 0, "selected": false, "text": "var str = 'john.doe@email.com';\nstr = str.toLowerCase().replace(/[\\.@a-z]/gi, function(match, position, str){\n var num = str.charCodeAt(position);\n return ('&#' + (num + 65248) + ';');\n});\n" }, { "answer_id": 19349775, "author": "webrama.pl", "author_id": 1317014, "author_profile": "https://Stackoverflow.com/users/1317014", "pm_score": 1, "selected": false, "text": " function antiboteEmail($email)\n {\n $html = '';\n\n $email = strrev($email);\n $randId = rand(1, 500);\n\n $html .= '<span id=\"addr-'.$randId.'\" class=\"addr\">[turn javascript on to see the e-mail]</span>';\n $html .= <<<EOD\n <script>\n $(document).ready(function(){\n\n var addr = \"$email\";\n addr = addr.split(\"\").reverse().join(\"\");\n $(\"#addr-$randId\").html(\"<a href=\\\"mailto:\" + addr + \"\\\">\" + addr + \" </a>\");\n });\n </script>\nEOD;\n\n return $html;\n }\n" }, { "answer_id": 22217705, "author": "saun4frsh", "author_id": 2666947, "author_profile": "https://Stackoverflow.com/users/2666947", "pm_score": 1, "selected": false, "text": " <span id=\"email\"> </span> // blank tag\n\n <script>\n var parts = [\"info\", \"XXXXabc\", \"com\", \"&#46;\", \"&#64;\"];\n var email = parts[0] + parts[4] + parts[1] + parts[3] + parts[2];\n document.getElementById(\"email\").innerHTML=email; \n </script>\n info(AT)XXXabc(DOT)com \n" }, { "answer_id": 22217773, "author": "saun4frsh", "author_id": 2666947, "author_profile": "https://Stackoverflow.com/users/2666947", "pm_score": 0, "selected": false, "text": " <span id=\"email\"> </span> // blank tag\n\n <script>\n var parts = [\"info\", \"XXXXabc\", \"com\", \"&#46;\", \"&#64;\"];\n var email = parts[0] + parts[4] + parts[1] + parts[3] + parts[2];\n document.getElementById(\"email\").innerHTML=email; \n </script>\n info(AT)XXXabc(DOT)com \n" }, { "answer_id": 24135598, "author": "Sasse", "author_id": 3725049, "author_profile": "https://Stackoverflow.com/users/3725049", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n $(function () {\n setTimeout(function () {\n var m = ['com', '.', 'domain', '@', 'info', ':', 'mailto'].reverse().join('');\n\n /* Set the contact email url for each \"contact us\" links.*/\n $('.contactUsLink').prop(\"href\", m);\n }, 200);\n });\n</script>\n" }, { "answer_id": 26420534, "author": "Andy Swift", "author_id": 72958, "author_profile": "https://Stackoverflow.com/users/72958", "pm_score": 6, "selected": false, "text": "<a href=\"mailto:coxntact@domainx.com\"\n onmouseover=\"this.href=this.href.replace(/x/g,'');\">link</a>\n" }, { "answer_id": 30476468, "author": "Sergiu", "author_id": 612847, "author_profile": "https://Stackoverflow.com/users/612847", "pm_score": 2, "selected": false, "text": "<a href=\"mailto:me@example.spam\" id=\"lnkMail\">moc.elpmaxe@em</a>\n #lnkMail {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n $('#lnkMail').hover(function(){\n // here you can use whatever replace you want\n var newHref = $(this).attr('href').replace('spam', 'com');\n $(this).attr('href', newHref);\n});\n" }, { "answer_id": 30476576, "author": "Sergiu", "author_id": 612847, "author_profile": "https://Stackoverflow.com/users/612847", "pm_score": 2, "selected": false, "text": "<a href=\"mailto:me@example.spam\" id=\"lnkMail\">moc.elpmaxe@em</a>\n #lnkMail {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n $('#lnkMail').hover(function(){\n // here you can use whatever replace you want\n var newHref = $(this).attr('href').replace('spam', 'com');\n $(this).attr('href', newHref);\n});\n" }, { "answer_id": 34044386, "author": "Mr. B.", "author_id": 1792858, "author_profile": "https://Stackoverflow.com/users/1792858", "pm_score": 1, "selected": false, "text": "data <span class=\"generate-email\" data-part1=\"john\" data-part2=\"gmail\" data-part3=\"com\">placeholder</span>\n $(function() {\n $('.generate-email').each(function() {\n var that = $(this);\n that.html(\n that.data('part1') + '@' + that.data('part2') + '.' + that.data('part3')\n );\n }); \n});\n" }, { "answer_id": 37175227, "author": "Darius", "author_id": 1293700, "author_profile": "https://Stackoverflow.com/users/1293700", "pm_score": 2, "selected": false, "text": "<div id=\"knock_knock\">Activate JavaScript, please.</div>\n <script>\n (function(d,id,lhs,rhs){\n d.getElementById(id).innerHTML = \"<a rel=\\\"nofollow\\\" href=\\\"mailto\"+\":\"+lhs+\"@\"+rhs+\"\\\">\"+\"Mail\"+\"<\\/a>\";\n })(window.document, \"knock_knock\", \"your.name\", \"example.com\");\n</script>\n <div id=\"knock_knock\"><a rel=\"nofollow\" href=\"your.name@example.com\">Mail</a></div>\n <script>(function(d,i,l,r){d.getElementById(i).innerHTML=\"<a rel=\\\"nofollow\\\" href=\\\"mailto\"+\":\"+l+\"@\"+r+\"\\\">\"+\"Mail\"+\"<\\/a>\";})(window.document,\"knock_knock\",\"your.name\",\"example.com\");</script>\n" }, { "answer_id": 41566570, "author": "cyptus", "author_id": 1216595, "author_profile": "https://Stackoverflow.com/users/1216595", "pm_score": 7, "selected": false, "text": ".cryptedmail:after {\n content: attr(data-name) \"@\" attr(data-domain) \".\" attr(data-tld); \n} <a href=\"#\" class=\"cryptedmail\"\n data-name=\"info\"\n data-domain=\"example\"\n data-tld=\"org\"\n onclick=\"window.location.href = 'mailto:' + this.dataset.name + '@' + this.dataset.domain + '.' + this.dataset.tld; return false;\"></a>" }, { "answer_id": 43749902, "author": "Aaron Esau", "author_id": 3678023, "author_profile": "https://Stackoverflow.com/users/3678023", "pm_score": 3, "selected": false, "text": "email:before {\n content: \"admin\";\n}\n\nemail:after {\n content: \"@example.com\";\n}\n <div id=\"email\"></div>\n" }, { "answer_id": 46271172, "author": "Ogun Adebali", "author_id": 5181427, "author_profile": "https://Stackoverflow.com/users/5181427", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"path/to/font-awesome/css/font-awesome.min.css\">\n\n<p>myemail<i class=\"fa fa-at\" aria-hidden=\"true\"></i>mydomain.com</p>\n" }, { "answer_id": 47967275, "author": "Project Mayhem", "author_id": 1262673, "author_profile": "https://Stackoverflow.com/users/1262673", "pm_score": -1, "selected": false, "text": "<link rel=\"stylesheet\" href=\"path/to/font-awesome/css/font-awesome.min.css\">\n <a href=\"mailto:info@uploadimage.club\"><span class=\"label\">info<i class=\"fa fa-at\"></i>uploadimage.club</span></a>\n" }, { "answer_id": 62969771, "author": "mrts", "author_id": 258772, "author_profile": "https://Stackoverflow.com/users/258772", "pm_score": 2, "selected": false, "text": "div <div id=\"contacts\">Contacts</div>\n\n<script>\n document.querySelector(\"#contacts\").addEventListener(\"mouseover\", (event) => {\n // Base64-encode your email and provide it as argument to atob()\n event.target.textContent = atob('aW5mb0BjbGV2ZXJpbmcuZWU=')\n });\n</script>\n" }, { "answer_id": 63862335, "author": "Emeric", "author_id": 9753985, "author_profile": "https://Stackoverflow.com/users/9753985", "pm_score": 2, "selected": false, "text": "isTrusted getEmail() {\n if (event.isTrusted) {\n /* The event is trusted */\n return 'your-email@domain.com';\n } else {\n /* The event is not trusted */\n return 'chuck@norris.com';\n }\n}\n" }, { "answer_id": 68775296, "author": "ztom", "author_id": 10944219, "author_profile": "https://Stackoverflow.com/users/10944219", "pm_score": 0, "selected": false, "text": "// search for [data-b64mail] attributes\ndocument.querySelectorAll('[data-b64mail]').forEach(el => {\n\n // set \"show\" link\n el.innerHTML = '<span style=\"text-decoration:underline;cursor:pointer\">show</span>';\n \n // set click event to all elements\n el.addEventListener('click', function (e) {\n let cT = e.currentTarget;\n\n // show address\n cT.innerHTML = atob(cT.getAttribute('data-b64mail'));\n \n // set mailto on a tags\n if (cT.tagName === 'A')\n cT.setAttribute('href', 'mailto:' + atob(cT.getAttribute('data-b64mail')));\n\n });\n\n});\n\n// get base64 encoded string\nconsole.log(btoa('mail@example.org')); <p>E-mail (span): <span data-b64mail=\"bWFpbEBleGFtcGxlLm9yZw==\"></span></p>\n\n<p>E-mail (link): <a href=\"#\" data-b64mail=\"bWFpbEBleGFtcGxlLm9yZw==\"></a></p>" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
163,646
<p>I guess I need to know what I need in the classpath (what jar) in order to execute WebSphere 6.1 ant tasks. If someone can provide an example that would be perfect.</p>
[ { "answer_id": 416798, "author": "Dinesh Manne", "author_id": 50853, "author_profile": "https://Stackoverflow.com/users/50853", "pm_score": 2, "selected": false, "text": "wsanttasks.jar /opt/IBM/WebSphere/AppServer/lib/wsanttasks.jar ws_ant ws_ant ws_ant" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15053/" ]
163,678
<p>I want to be able to specify the file name stem for the log file in a Specman test. I need to hard-code the main *.elog filename so that I don't get variance between tests and confuse the post-processing scripts. Is there a constraint or command line I can pass into Specman?</p>
[ { "answer_id": 897319, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "extend sys\n{\n run() is also {\n specman(\"set log specman.elog\");\n };\n};\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20712/" ]
163,707
<p>Whoops, I need some info from a file I deleted, a while ago. In CVS I would just go to the ATTIC to find it, how do I find a file in SVN without having to go back to a revision where it existed (especially annoying since I have no idea really when I deleted -- one week ago, two weeks ago...)</p>
[ { "answer_id": 163737, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": ",v" }, { "answer_id": 163756, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "svn log --verbose\n svn copy --revision <last_revision_with_deleted_file>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
163,732
<p>What would you recommend for class that needs to keep a list of unique integers?</p> <p>I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().</p> <p>Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".</p>
[ { "answer_id": 163738, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 6, "selected": true, "text": "HashSet<T> HashSet<T> HashSet<T> HashSet<T> Dictionary<TKey, TValue> Hashtable HashSet<T> Dictionary<TKey, TValue> HashSet<T>" }, { "answer_id": 163787, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 2, "selected": false, "text": "public class Set<T> {\n private class Unit { ... no behavior }\n private Dictionary<T, Unit> d;\n\n....\n}\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16008/" ]
163,747
<p>I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to <code>jni.h</code>. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and <code>g++</code> is available.</p> <p>Alternatively, is there a way to get <code>javah</code> (or a supporting tool) to give me this path directly?</p>
[ { "answer_id": 164030, "author": "Braden", "author_id": 18144, "author_profile": "https://Stackoverflow.com/users/18144", "pm_score": 4, "selected": true, "text": "AC_CHECK_HEADER CPPFLAGS libjvm dlopen JAVA_HOME JAVA_HOME AC_CHECK_HEADER([jni.h], [have_jni=yes])\nAC_ARG_VAR([JAVA_HOME], [Java Runtime Environment (JRE) location])\nAC_ARG_ENABLE([java-feature],\n [AC_HELP_STRING([--disable-java-feature],\n [disable Java feature])])\ncase $target_cpu in\n x86_64) JVM_ARCH=amd64 ;;\n i?86) JVM_ARCH=i386 ;;\n *) JVM_ARCH=$target_cpu ;;\nesac\nAC_SUBST([JVM_ARCH])\nAS_IF([test X$enable_java_feature != Xno],\n[AS_IF([test X$have_jni != Xyes],\n [AC_MSG_FAILURE([The Java Native Interface is required for Java feature.])])\nAS_IF([test -z \"$JAVA_HOME\"],\n[AC_MSG_WARN([JAVA_HOME has not been set. JAVA_HOME must be set at run time to locate libjvm.])],\n[save_LDFLAGS=$LDFLAGS\nLDFLAGS=\"-L$JAVA_HOME/lib/$JVM_ARCH/client -L$JAVA_HOME/lib/$JVM_ARCH/server $LDFLAGS\"\nAC_CHECK_LIB([jvm], [JNI_CreateJavaVM], [LIBS=$LIBS],\n [AC_MSG_WARN([no libjvm found at JAVA_HOME])])\nLDFLAGS=$save_LDFLAGS\n])])\n" }, { "answer_id": 65376766, "author": "Quincey Koziol", "author_id": 2602941, "author_profile": "https://Stackoverflow.com/users/2602941", "pm_score": 0, "selected": false, "text": "--- a/m4/ax_jni_include_dir.m4\n+++ b/m4/ax_jni_include_dir.m4\n@@ -73,13 +73,19 @@ fi\n \n case \"$host_os\" in\n darwin*) # Apple Java headers are inside the Xcode bundle.\n- macos_version=$(sw_vers -productVersion | sed -n -e 's/^@<:@0-9@:>@\n*.\\(@<:@0-9@:>@*\\).@<:@0-9@:>@*/\\1/p')\n- if @<:@ \"$macos_version\" -gt \"7\" @:>@; then\n- _JTOPDIR=\"$(xcrun --show-sdk-path)/System/Library/Frameworks/JavaVM.framework\"\n- _JINC=\"$_JTOPDIR/Headers\"\n+ major_macos_version=$(sw_vers -productVersion | sed -n -e 's/^\\(@<:@0-9@:>@*\\).@<:@0-9@:>@*.@<:@0-9@:>@*/\\1/p')\n+ if @<:@ \"$major_macos_version\" -gt \"10\" @:>@; then\n+ _JTOPDIR=\"$(/usr/libexec/java_home)\"\n+ _JINC=\"$_JTOPDIR/include\"\n else\n- _JTOPDIR=\"/System/Library/Frameworks/JavaVM.framework\"\n- _JINC=\"$_JTOPDIR/Headers\"\n+ macos_version=$(sw_vers -productVersion | sed -n -e 's/^@<:@0-9@:>@*.\\(@<:@0-9@:>@*\\).@<:@0-9@:>@*/\\1/p')\n+ if @<:@ \"$macos_version\" -gt \"7\" @:>@; then\n+ _JTOPDIR=\"$(xcrun --show-sdk-path)/System/Library/Frameworks/JavaVM.framework\"\n+ _JINC=\"$_JTOPDIR/Headers\"\n+ else\n+ _JTOPDIR=\"/System/Library/Frameworks/JavaVM.framework\"\n+ _JINC=\"$_JTOPDIR/Headers\"\n+ fi\n fi\n ;;\n *) _JINC=\"$_JTOPDIR/include\";;\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
163,748
<p>I have a web project, a C# library project, and a web setup project in Visual Studio 2005. The web project needs the C# library needs to be registered in the GAC. This is simple, just add the GAC folder to the setup project and drop the primary output of the C# library in there. The C# library also needs to be registered for COM interop. I click select the primary output in the GAC folder and change the Register property to vsdrpCOM. I build the setup project and run it but the DLL never gets registered for COM.</p> <p>This is not really a surprise to me. I have always had to add an installer class which had a custom action which used RegistrationServices.RegisterAssembly to properly register my DLLs for COM. So I apply this workaround which I have accepted for years to my situation. Now I find that custom actions assigned to primary output in the GAC folder of a setup project prevent the setup project from even building.</p> <p>I have always felt like I was hacking thigs to get .NET and COM to play nice with setup and deployment projects. What is the proper way to solve my problem?</p>
[ { "answer_id": 164707, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 2, "selected": false, "text": "REM Unregister anything currently in component services\n\nRemoveCom+.vbs\n\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\regsvcs /u \"C:\\source\\bin\\FooCode.dll\"\n\nREM Remove from GAC\n\n\"C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin\\gacutil\" /uf FooCode\n\nREM Register in component services\n\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\regsvcs \"C:\\source\\bin\\FooCode.dll\"\n\nREM Add to GAC\n\n\"C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin\\gacutil\" /if \"C:\\source\\bin\\FooCode.dll\"\n set cat = CreateObject (\"COMAdmin.COMAdminCatalog\")\nSet apps = cat.GetCollection(\"Applications\")\n\nbFound = false\napps.Populate\n\nlNumApps = apps.Count\n\n' Enumerate through applications looking for AppName.\nDim app\nFor I = lNumApps - 1 to 0 step -1\n Set app = apps.Item(I)\n If app.Name = \"FooCode\" Then\n cat.ShutdownApplication (\"FooCode\")\n apps.Remove(I)\n apps.SaveChanges\n End If\nNext\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
163,757
<p>I am using boost::signal in a native C++ class, and I now I am writing a .NET wrapper in C++/CLI, so that I can expose the native C++ callbacks as .NET events. When I try to use boost::bind to take the address of a member function of my managed class, I get compiler error 3374, saying I cannot take the address of a member function unless I am creating a delegate instance. Does anyone know how to bind a member function of a managed class using boost::bind?</p> <p>For clarification, the following sample code causes Compiler Error 3374:</p> <pre><code>#include &lt;boost/bind.hpp&gt; public ref class Managed { public: Managed() { boost::bind(&amp;Managed::OnSomeEvent, this); } void OnSomeEvent(void) { } }; </code></pre>
[ { "answer_id": 165362, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 2, "selected": false, "text": "#include <msclr/marshal.h>\n\n#include <boost/bind.hpp>\n#include <boost/signal.hpp>\n#include <iostream>\n\n#using <mscorlib.dll>\n\nusing namespace System;\nusing namespace msclr::interop;\n\ntypedef boost::signal<void (void)> ChangedSignal;\ntypedef boost::signal<void (void)>::slot_function_type ChangedSignalCB;\ntypedef boost::signals::connection Callback;\n\n\nclass Native\n{\npublic:\n\n void ChangeIt() \n {\n changed();\n }\n\n Callback RegisterCallback(ChangedSignalCB Subscriber)\n {\n return changed.connect(Subscriber);\n }\n\n void UnregisterCallback(Callback CB)\n {\n changed.disconnect(CB);\n }\n\nprivate:\n ChangedSignal changed;\n};\n\n\n\ndelegate void ChangeHandler(void);\n\n\npublic ref class Managed\n{\npublic:\n Managed(Native* Nat);\n ~Managed();\n void OnSomeEvent(void);\n\n event ChangeHandler^ OnChange;\n\nprivate:\n Native* native;\n Callback* callback;\n};\n\n\nvoid SomeEventProxy(gcroot<Managed^> This)\n{\n This->OnSomeEvent();\n}\n\n\nManaged::Managed(Native* Nat)\n : native(Nat)\n{\n native = Nat;\n callback = new Callback;\n *callback = native->RegisterCallback(boost::bind( SomeEventProxy, gcroot<Managed^>(this) ) );\n}\n\nManaged::~Managed()\n{\n native->UnregisterCallback(*callback);\n delete callback;\n}\n\nvoid Managed::OnSomeEvent(void)\n{\n OnChange();\n}\n\n\nvoid OnChanged(void)\n{\n Console::WriteLine(\"Got it!\");\n}\n\nint main(array<System::String ^> ^args)\n{\n Native* native = new Native;\n Managed^ managed = gcnew Managed(native);\n\n managed->OnChange += gcnew ChangeHandler(OnChanged);\n\n native->ChangeIt();\n\n delete native;\n return 0;\n}\n" }, { "answer_id": 703105, "author": "yagni", "author_id": 80525, "author_profile": "https://Stackoverflow.com/users/80525", "pm_score": 4, "selected": true, "text": "public delegate void ChangeHandler(void);\ntypedef void (__stdcall *ChangeCallback)(void);\n\npublic ref class Managed\n{\npublic:\n Managed(Native* Nat);\n ~Managed();\n\n event ChangeHandler^ OnChange;\n\nprivate:\n void OnSomeEvent(void);\n Native* native;\n Callback* callback;\n GCHandle gch;\n};\n\nManaged::Managed(Native* Nat)\n : native(Nat)\n{\n callback = new Callback;\n\n ChangeHandler^ handler = gcnew ChangeHandler( this, &Managed::OnSomeEvent );\n gch = GCHandle::Alloc( handler );\n System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler );\n ChangeCallback cbFunc = static_cast<ChangeCallback>( ip.ToPointer() );\n\n *callback = native->RegisterCallback(boost::bind<void>( cbFunc ) );\n}\n\nManaged::~Managed()\n{\n native->UnregisterCallback(*callback);\n delete callback;\n if ( gch.IsAllocated )\n {\n gch.Free();\n }\n}\n\nvoid Managed::OnSomeEvent(void)\n{\n OnChange();\n}\n bind<R>()" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]