qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
303,371 | <p>I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state.</p>
<p>Platform: linux</p>
<p>What do you guys use to generate NOT parse xml?</p>
<p>So far I'm going down Foredecker's route of just generating it myself -- it's not a large document but I really shouldn't be having this much trouble finding a decent library to generate it correctly.</p>
<p>As for boost, the things that I would like to be able to do is set the node names, set attributes in my nodes, and get rid of all the extra crap that comes with it as I don't really care about having to put my document back into that class.</p>
| [
{
"answer_id": 303724,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 6,
"selected": false,
"text": "Document doc;\nNode* root(doc.InsertEndChild(Element(\"RootNode\")));\nElement measurements(\"measurements\");\nElement tbr(\"TotalBytesReceived\", 12);\nmeasurements.InsertEndChild(tbr);\nroot->InsertEndChild(measurements);\n <RootNode>\n <measurements>\n <TotalBytesReceived>12</TotalBytesReceived>\n </measurements>\n</RootNode>\n"
},
{
"answer_id": 11058580,
"author": "Daniel Wolf",
"author_id": 52041,
"author_profile": "https://Stackoverflow.com/users/52041",
"pm_score": 3,
"selected": false,
"text": "#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n\nusing boost::property_tree::ptree;\nusing boost::property_tree::write_xml;\nusing boost::property_tree::xml_writer_settings;\n\nint wmain(int argc, wchar_t* argv[]) {\n char* titles[] = {\"And Then There Were None\", \"Android Games\", \"The Lord of the Rings\"};\n\n ptree tree;\n tree.add(\"library.<xmlattr>.version\", \"1.0\");\n for (int i = 0; i < 3; i++) {\n ptree& book = tree.add(\"library.books.book\", \"\");\n book.add(\"title\", titles[i]);\n book.add(\"<xmlattr>.id\", i);\n book.add(\"pageCount\", (i+1) * 234);\n }\n\n // Note that starting with Boost 1.56, the template argument must be std::string\n // instead of char\n write_xml(\"C:\\\\Users\\\\Daniel\\\\Desktop\\\\test.xml\", tree,\n std::locale(),\n xml_writer_settings<char>(' ', 4));\n\n return 0;\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<library version=\"1.0\">\n <books>\n <book id=\"0\">\n <title>And Then There Were None</title>\n <pageCount>234</pageCount>\n </book>\n <book id=\"1\">\n <title>Android Games</title>\n <pageCount>468</pageCount>\n </book>\n <book id=\"2\">\n <title>The Lord of the Rings</title>\n <pageCount>702</pageCount>\n </book>\n </books>\n</library>\n ptree.hpp"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39110/"
] |
303,397 | <p>I have designed a xml schema to parse an incoming xml document. The receive location gets xml documents from 2 feeds, one of them has misspelled a node in the document, "Roookie" instead of "Rookie", Is there a way to have my existing xsd parse this document?</p>
| [
{
"answer_id": 303438,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n<xsl:output method=\"xml\" indent=\"no\"/>\n\n<xsl:template match=\"Roookie\">\n <Rookie>\n <xsl:apply-templates select=\"@*|node()\" />\n </Rookie>\n</xsl:template>\n\n<xsl:template match=\"@*|node()\" name=\"defaultRule\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n</xsl:stylesheet>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443363/"
] |
303,404 | <p>If I have records:</p>
<pre>
Row Date, LocationID, Account
1 Jan 1, 2008 1 1000
2 Jan 2, 2008 1 1000
3 Jan 3, 2008 2 1001
4 Jan 3, 2008 1 1001
5 Jan 3, 2008 3 1001
6 Jan 4, 2008 3 1002
</pre>
<p>I need to get the row (<code>date</code>, <code>locatinid</code>, <code>account</code>) where the row has the most recent date for each distinct <code>locationid</code>:</p>
<pre>
4 Jan 3, 2008 1 1001
3 Jan 3, 2008 2 1001
6 Jan 4, 2008 3 1002
</pre>
| [
{
"answer_id": 303421,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "select *\nfrom mytable t1\nwhere date = (select max(date) from mytable t2\n where t2.location = t1.location);\n"
},
{
"answer_id": 303461,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 0,
"selected": false,
"text": "select t.* from mytable t,\n(select max(Date) as Date,LocationID from mytable group by LocationID) t1 \nwhere t.Date = t1.Date and t.LocationID = t1.LocationID \norder by t1.LocationID \n"
},
{
"answer_id": 303479,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT t1.*\nFROM mytable t1\n LEFT OUTER JOIN mytable t2\n ON (t1.locationid = t2.locationid \n AND (t1.date < t2.date OR t1.date = t2.date AND t1.row < t2.row))\nWHERE t2.row IS NULL;\n"
},
{
"answer_id": 303509,
"author": "Jim",
"author_id": 681,
"author_profile": "https://Stackoverflow.com/users/681",
"pm_score": 3,
"selected": true,
"text": "SELECT t1.*\nFROM table t1\n JOIN (SELECT MAX(Date), LocationID\n FROM table\n GROUP BY Date, LocationID) t2 on t1.Date = t2.Date and t1.LocationID = t2.LocationID\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
303,405 | <p>I have an API call in my application where I am checking the time taken for a single call. I have put this in a FOR loop and using 10000 calls to get the average times of all calls. Now the issue which came up was that the actual application using the API, is multi-threaded. If I wish to make my application also do the same, how would I go about doing this? </p>
<p>The platform is REL and my aim is to send multiple calls in the same time with either the same parameters or different parameters. Can this be implemented in C++ and if so, what library functions to use and can an example be provided for the same? </p>
| [
{
"answer_id": 10769819,
"author": "betabandido",
"author_id": 1135819,
"author_profile": "https://Stackoverflow.com/users/1135819",
"pm_score": 0,
"selected": false,
"text": "std::thread"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
303,417 | <p>I found that SQL stored procedures are very interesting and useful. I have written stored procedures but i want to write well crafted, good performance tuned and concise SPs for any sort of requirement and also would love to learn about any tricks or good practices for stored procedures. How do i move from the beginner to the advanced stage in writing stored procedures?</p>
<p><em>Update: Found from comments that my question should be more specific.
Everyone has some tricks upon their sleeves and I was expecting such tricks and practices for SPs which they use in their code which differentiates them from others and more importantly spruce up the productivity in writing and working with stored procedures.</em></p>
| [
{
"answer_id": 303462,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 4,
"selected": false,
"text": "/*\n Usage:\n EXEC usp_ThisProc @Param1 = 1, @Param2 = 2\n*/\n"
},
{
"answer_id": 303819,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 6,
"selected": false,
"text": "EXEC @err = AnyStoredProc @value\nSET @save_error = @@error\n-- NULLIF says that if @err is 0, this is the same as null\n-- COALESCE returns the first non-null value in its arguments\nSELECT @err = COALESCE( NULLIF(@err, 0), @save_error )\nIF @err <> 0 BEGIN \n -- Because stored proc may have started a tran it didn't commit\n ROLLBACK TRANSACTION \n RETURN @err \nEND\n INSERT, DELETE, UPDATE\nSELECT INTO\nInvocation of stored procedures\ninvocation of dynamic SQL\nCOMMIT TRANSACTION\nDECLARE and OPEN CURSOR\nFETCH from cursor\nWRITETEXT and UPDATETEXT\n"
},
{
"answer_id": 1530465,
"author": "Simon Hughes",
"author_id": 5884,
"author_profile": "https://Stackoverflow.com/users/5884",
"pm_score": 4,
"selected": false,
"text": "SET NOCOUNT ON\nBEGIN TRAN\n INSERT...\n UPDATE...\nCOMMIT\n SET NOCOUNT ON\nBEGIN TRAN\n INSERT...\n IF @ErrorVar <> 0\n BEGIN\n RAISERROR(N'Message', 16, 1)\n GOTO QuitWithRollback\n END\n\n UPDATE...\n IF @ErrorVar <> 0\n BEGIN\n RAISERROR(N'Message', 16, 1)\n GOTO QuitWithRollback\n END\n\n EXECUTE @ReturnCode = some_proc @some_param = 123\n IF (@@ERROR <> 0 OR @ReturnCode <> 0)\n GOTO QuitWithRollback \nCOMMIT\nGOTO EndSave \nQuitWithRollback:\n IF (@@TRANCOUNT > 0)\n ROLLBACK TRANSACTION \nEndSave:\n SET NOCOUNT ON\nSET XACT_ABORT ON\nBEGIN TRY\n BEGIN TRAN\n INSERT...\n UPDATE...\n COMMIT\nEND TRY\nBEGIN CATCH\n IF (XACT_STATE()) <> 0\n ROLLBACK\nEND CATCH\n SET NOCOUNT ON\nSET XACT_ABORT ON\nBEGIN TRAN\n INSERT...\n UPDATE...\nCOMMIT\n"
},
{
"answer_id": 11746721,
"author": "nk2",
"author_id": 1110935,
"author_profile": "https://Stackoverflow.com/users/1110935",
"pm_score": 1,
"selected": false,
"text": " BEGIN TRY\n one_or_more_sql_statements\n END TRY\n BEGIN CATCH\n one_or_more_sql_statements\n END CATCH\n ERROR_NUMBER()\n ERROR_MESSAGE()\n ERROR_SEVERITY()\n ERROR_STATE()\n ERROR_LINE()\n ERROR_PROCEDURE()\n"
},
{
"answer_id": 56273625,
"author": "darlove",
"author_id": 4392206,
"author_profile": "https://Stackoverflow.com/users/4392206",
"pm_score": 0,
"selected": false,
"text": "\nBEGIN TRAN;\n\n SELECT @@TRANCOUNT AS after_1_begin;\n\nBEGIN TRAN;\n\n SELECT @@TRANCOUNT AS after_2_begin;\n\nCOMMIT TRAN;\n\n SELECT @@TRANCOUNT AS after_1_commit;\n\nBEGIN TRANSACTION;\n\n SELECT @@TRANCOUNT AS after_3_begin;\n\nROLLBACK TRAN;\n\n SELECT @@TRANCOUNT AS after_rollback;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113/"
] |
303,440 | <p>I'm working on a idea where my a:link have one state (blue, no underline etc) with a a:hover being white. I want my <strong>visited links to have the same state</strong> as <code>a:link</code> and <code>a:hover</code>. Is this possible? supported in most common browsers?</p>
| [
{
"answer_id": 303447,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 1,
"selected": false,
"text": "a\n{\n color:#6c7492;\n font-weight:bold;\n text-decoration:none;\n}\na:hover\n{\n border-bottom:1px solid #6c7492;\n}\n"
},
{
"answer_id": 303449,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "a:visited, a:hover {\n ...\n}\n"
},
{
"answer_id": 303464,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 4,
"selected": false,
"text": "a, a:link, a:hover, a:visited, a:active {text-decoration: none; color: blue;}\n a:hover a:hover {color: white !important;}\n"
},
{
"answer_id": 303466,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 4,
"selected": false,
"text": "a:link { }\na:visited { }\na:hover { }\na:active { }\n a:visited:hover { }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
303,460 | <p>Greetings!</p>
<p>I'm creating a User Control that will display data in a GridView control. We are using n-tier architecture and the data in question is retrieved from our database and returned to us as a ReadOnlyCollection. OurNewObject is a class containing several properties and an empty constructor that takes no parameters - it's in the following namespace: Acme.ObjectModel.</p>
<p>In the user control, I have the following:</p>
<pre><code><asp:GridView ID="ourGrid" runat="server" DataSourceID="ourDataSource">
<columns>
<asp:BoundField DataField="Name" HeaderText="Full Name" />
<asp:BoundField DataField="Gender" HeaderText="Gender" />
<asp:BoundField DataField="BirthYear" HeaderText="Year of Birth" />
<asp:BoundField DataField="JoinDate" HeaderText="Date Joined" />
</columns>
</asp:GridView>
<asp:ObjectDataSource ID="ourDataSource" runat="server" SelectMethod="GetTopUsers" TypeName="Acme.Model.OurNewObject">
</asp:ObjectDataSource>
</code></pre>
<p>In the User Control's code behind, I have the following public method:</p>
<pre><code>public ReadOnlyCollection<OurNewObject> GetTopUsers()
{
return (OurDataProxy.GetJustTheTopUsers());
}
</code></pre>
<p>When I place the User Control on a Web form and run it, I get the following message:</p>
<p><strong>ObjectDataSource 'ourDataSource' could not find a non-generic method 'GetTopUsers' that has no parameters.</strong></p>
<p>So my questions are:</p>
<ol>
<li>Am I using the ObjectDataSource
incorrectly?</li>
<li>Is there a more proper way to use the ObjectDataSource in this situation?</li>
</ol>
<p>Thanks.</p>
| [
{
"answer_id": 303506,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": true,
"text": "[System.ComponentModel.DataObjectMethodAttribute\n (System.ComponentModel.DataObjectMethodType.Select, true)]\n [System.ComponentModel.DataObject]\n"
},
{
"answer_id": 330134,
"author": "IrishChieftain",
"author_id": 31444,
"author_profile": "https://Stackoverflow.com/users/31444",
"pm_score": 0,
"selected": false,
"text": "DataKeyNames GridView"
},
{
"answer_id": 336062,
"author": "Jeff Woodman",
"author_id": 42689,
"author_profile": "https://Stackoverflow.com/users/42689",
"pm_score": 2,
"selected": false,
"text": "public class SampleDataObject\n{\n public ICollection<OurNewObject> GetTopUsers()\n {\n //[...]\n }\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
303,488 | <p>In through <code>php_info()</code> where the WSDL cache is held (<code>/tmp</code>), but I don't necessarily know if it is safe to delete all files starting with WSDL. </p>
<p>Yes, I <em>should</em> be able to just delete everything from <code>/tmp</code>, but I don't know what else this could effect if I delete any all WSDL files.</p>
| [
{
"answer_id": 303514,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": true,
"text": "ini_set(\"soap.wsdl_cache_enabled\", 0);\n $client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );\n"
},
{
"answer_id": 17991617,
"author": "staabm",
"author_id": 1597388,
"author_profile": "https://Stackoverflow.com/users/1597388",
"pm_score": 4,
"selected": false,
"text": "$client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');\n"
},
{
"answer_id": 21493222,
"author": "user3259435",
"author_id": 3259435,
"author_profile": "https://Stackoverflow.com/users/3259435",
"pm_score": 5,
"selected": false,
"text": "wsdl* /tmp"
},
{
"answer_id": 23120515,
"author": "Markomafs",
"author_id": 1750091,
"author_profile": "https://Stackoverflow.com/users/1750091",
"pm_score": 4,
"selected": false,
"text": "rm /tmp/wsdl-*\n"
},
{
"answer_id": 24972408,
"author": "peter_the_oak",
"author_id": 818827,
"author_profile": "https://Stackoverflow.com/users/818827",
"pm_score": 2,
"selected": false,
"text": "WSDL_CACHE_NONE soap.wsdl_cache_enabled"
},
{
"answer_id": 56070691,
"author": "Kiran Reddy",
"author_id": 4984906,
"author_profile": "https://Stackoverflow.com/users/4984906",
"pm_score": 0,
"selected": false,
"text": "php.ini soap.wsdl_cache_enabled 0 [soap]\n; Enables or disables WSDL caching feature.\n; http://php.net/soap.wsdl-cache-enabled\nsoap.wsdl_cache_enabled=0\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] |
303,502 | <p>I ran across this and was wondering if someone could explain why this works in VB.NET when I would expect it should fail, just like it does in C#</p>
<pre><code>//The C# Version
struct Person {
public string name;
}
...
Person someone = null; //Nope! Can't do that!!
Person? someoneElse = null; //No problem, just like expected
</code></pre>
<p>But then in VB.NET...</p>
<pre><code>Structure Person
Public name As String
End Structure
...
Dim someone As Person = Nothing 'Wha? this is okay?
</code></pre>
<p>Is Nothing not the same as null (<em>Nothing != null - LOL?)</em>, or is this just different ways of handling the same situation between the two languages?</p>
<p>Why or what is handled differently between the two that makes this okay in one, but not the other?</p>
<p><strong>[Update]</strong></p>
<p>Given some of the comments, I messed with this a bit more... it seems as if you actually have to use Nullable if you want to allow something to be null in VB.NET... so for example...</p>
<pre><code>'This is false - It is still a person'
Dim someone As Person = Nothing
Dim isSomeoneNull As Boolean = someone.Equals(Nothing) 'false'
'This is true - the result is actually nullable now'
Dim someoneElse As Nullable(Of Person) = Nothing
Dim isSomeoneElseNull As Boolean = someoneElse.Equals(Nothing) 'true'
</code></pre>
<p>Too weird...</p>
| [
{
"answer_id": 303525,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "Nothing default(T) Nothing"
},
{
"answer_id": 17376576,
"author": "piBoss",
"author_id": 826297,
"author_profile": "https://Stackoverflow.com/users/826297",
"pm_score": -1,
"selected": false,
"text": "Public Class Employees\n Public Structure EmployeeInfoType\n Dim Name As String ' String\n Dim Age as Integer ' Integer\n Dim Salary as Single ' Single\n End Structure\n\n Private MyEmp as New EmployeeInfoType\n\n Public Function IsEmployeeNothing(Employee As EmployeeInfoType) As Boolean\n If **IsNothing**(Employee) Then\n Return True\n Else\n Return False\n End If\n End Function\nEnd Class\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091/"
] |
303,510 | <p>My XML (<strong>a.xhtml</strong>) starts like this</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...
</code></pre>
<p>My code starts like this</p>
<pre><code>use XML::XPath;
use XML::XPath::XMLParser;
my $xp = XML::XPath->new(filename => "a.xhtml");
my $nodeset = $xp->find('/html/body//table');
</code></pre>
<p>It's very slow, and it turns out that it spends a lot of time getting the DTD (<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="nofollow noreferrer">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>).</p>
<p>Is there a way to explicitly declare an HTTP proxy server in the Perl XML:: family? I hate to modify the original <strong>a.xhtml</strong> document like having a local copy of the DTD.</p>
| [
{
"answer_id": 304842,
"author": "mirod",
"author_id": 11095,
"author_profile": "https://Stackoverflow.com/users/11095",
"pm_score": 5,
"selected": true,
"text": "my $p = XML::Parser->new( NoLWP => 1);\nmy $xp= XML::XPath->new( parser => $p, filename => \"a.xhtml\");\n"
},
{
"answer_id": 5227637,
"author": "Anonymous Coward",
"author_id": 649137,
"author_profile": "https://Stackoverflow.com/users/649137",
"pm_score": 2,
"selected": false,
"text": "use XML::XPath;\nuse XML::Catalog;\n\nmy $parser = new XML::Parser;\nmy $catalog_handler = new XML::Catalog(\"xhtml1-20020801/DTD/xhtml.soc\")->get_handler($parser);\n$parser->setHandlers(\"ExternEnt\" => $catalog_handler);\nmy $xp = new XML::XPath(xml => $xml, parser => $parser);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24349/"
] |
303,511 | <p>I'm setting up CruiseControl.NET and during the build I want to modify my version.txt file and have it checked in. When I do this, CruiseControl.NET doesn't know this checkin was done by the build and so the next time it checks sources, it sees there were modifications and rebuilds again (I have IfModificationExists set in the project build). How do I tell CruiseControl.NET to check this file in or let it know that this one is OK so it doesn't keep re-triggering builds?</p>
| [
{
"answer_id": 303665,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 4,
"selected": true,
"text": "<sourcecontrol type=\"filtered\">\n <sourceControlProvider type=\"svn\">\n ... \n </sourceControlProvider>\n <exclusionFilters>\n <pathFilter>\n <pattern>**/Version.txt</pattern>\n </pathFilter>\n </exclusionFilters>\n</sourcecontrol>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
303,512 | <p>It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.</p>
<ul>
<li>Try to limit answers to Groovy core</li>
<li>One feature per answer</li>
<li>Give an example and short description of the feature, not just a link to documentation</li>
<li>Label the feature using bold title as the first line</li>
</ul>
<p>See also:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li>
<li><a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby">Hidden features of Ruby</a></li>
<li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl">Hidden features of Perl</a></li>
<li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li>
</ol>
| [
{
"answer_id": 303561,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 5,
"selected": false,
"text": "def x = [foo:1, bar:{-> println \"Hello, world!\"}]\nx.foo\nx.bar()\n"
},
{
"answer_id": 303641,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "def animals = ['ant', 'buffalo', 'canary', 'dog']\nassert animals.size() == 4\nassert animals*.size() == [3, 7, 6, 3]\n animals.collect { it.size() }"
},
{
"answer_id": 303704,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 3,
"selected": false,
"text": "def foo(Map m=[:], String msg, int val, Closure c={}) {\n [...]\n}\n foo(\"msg\", 2, x:1, y:2)\nfoo(x:1, y:2, \"blah\", 2)\nfoo(\"blah\", x:1, 2, y:2) { [...] }\nfoo(\"blah\", 2) { [...] }\n"
},
{
"answer_id": 304286,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 5,
"selected": false,
"text": "def d = \"hello\";\ndef obj = null;\n\ndef obj2 = obj ?: d; // sets obj2 to default\nobj = \"world\"\n\ndef obj3 = obj ?: d; // sets obj3 to obj (since it's non-null)\n"
},
{
"answer_id": 304534,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 4,
"selected": false,
"text": "def company = builder.company( name: 'ACME' ) {\n address( id: 'a1', line1: '123 Groovy Rd', zip: 12345, state: 'JV' )\n employee( name: 'Duke', employeeId: 1 ){\n address( refId: 'a1' )\n }\n}\n List null"
},
{
"answer_id": 305040,
"author": "Rui Vieira",
"author_id": 143732,
"author_profile": "https://Stackoverflow.com/users/143732",
"pm_score": 4,
"selected": false,
"text": "switch(event.source) {\n case object1:\n // do something\n break\n case object2:\n // do something\n break\n}\n"
},
{
"answer_id": 305058,
"author": "Rui Vieira",
"author_id": 143732,
"author_profile": "https://Stackoverflow.com/users/143732",
"pm_score": 5,
"selected": false,
"text": " myObj1.setValue(10)\n otherObj.setTitle(myObj1.getName())\n myObj1.setMode(Obj1.MODE_NORMAL)\n myObj1.with {\n value = 10\n otherObj.title = name\n mode = MODE_NORMAL\n }\n"
},
{
"answer_id": 306404,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 4,
"selected": false,
"text": "println \n\"\"\"\nGroovy has \"multi-line\" strings.\nHooray!\n\"\"\"\n"
},
{
"answer_id": 306441,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 4,
"selected": false,
"text": "new File(\"/etc/profile\").withReader { r ->\n System.out << r\n}\n"
},
{
"answer_id": 307985,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 4,
"selected": false,
"text": "def filePaths = \"\"\"\n/tmp/file.txt\n/usr/bin/dummy.txt\n\"\"\"\n\nassert (filePaths =~ /(.*)\\/(.*)/).collect { full, path, file -> \n \"$file -> $path\"\n } == [\"file.txt -> /tmp\", \"dummy.txt -> /usr/bin\"]\n"
},
{
"answer_id": 307997,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 5,
"selected": false,
"text": "\"foo\".metaClass.methods.name.sort().unique()\n [\"charAt\", \"codePointAt\", \"codePointBefore\", \"codePointCount\", \"compareTo\",\n \"compareToIgnoreCase\", \"concat\", \"contains\", \"contentEquals\", \"copyValueOf\", \n \"endsWith\", \"equals\", \"equalsIgnoreCase\", \"format\", \"getBytes\", \"getChars\", \n \"getClass\", \"hashCode\", \"indexOf\", \"intern\", \"lastIndexOf\", \"length\", \"matches\", \n \"notify\", \"notifyAll\", \"offsetByCodePoints\", \"regionMatches\", \"replace\", \n \"replaceAll\", \"replaceFirst\", \"split\", \"startsWith\", \"subSequence\", \"substring\", \n \"toCharArray\", \"toLowerCase\", \"toString\", \"toUpperCase\", \"trim\", \"valueOf\", \"wait\"]\n"
},
{
"answer_id": 996278,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "MyInterface foo\n foo = {Object[] args -> println \"This closure will be called by ALL methods\"} as MyInterface\n foo = [bar: {-> println \"bar invoked\"}, \n baz: {param1 -> println \"baz invoked with param $param1\"}] as MyInterface\n"
},
{
"answer_id": 3605452,
"author": "ken",
"author_id": 128586,
"author_profile": "https://Stackoverflow.com/users/128586",
"pm_score": 5,
"selected": false,
"text": " Foo {\n static A() { println \"I'm A\"}\n\n static $static_methodMissing(String name, args) {\n println \"Missing static $name\"\n }\n }\n\nFoo.A() //prints \"I'm A\"\nFoo.B() //prints \"Missing static B\"\n"
},
{
"answer_id": 3739198,
"author": "ken",
"author_id": 128586,
"author_profile": "https://Stackoverflow.com/users/128586",
"pm_score": 4,
"selected": false,
"text": "def list = ['key', 'value', 'foo', 'bar'] as Object[]\ndef map = list.toSpreadMap()\n\nassert 2 == map.size()\nassert 'value' == map.key\nassert 'bar' == map['foo']\n"
},
{
"answer_id": 7000158,
"author": "mmigdol",
"author_id": 448741,
"author_profile": "https://Stackoverflow.com/users/448741",
"pm_score": 4,
"selected": false,
"text": "def list = [\n [ id:0, first: 'Michael', last: 'Smith', age: 23 ],\n [ id:1, first: 'John', last: 'Smith', age: 30 ],\n [ id:2, first: 'Michael', last: 'Smith', age: 15 ], \n [ id:3, first: 'Michael', last: 'Jones', age: 15 ], \n]\n\n// sort list by last name, then first name, then by descending age\nassert (list.sort { a,b -> a.last <=> b.last ?: a.first <=> b.first ?: b.age <=> a.age })*.id == [ 3,1,0,2 ]\n"
},
{
"answer_id": 7892366,
"author": "Grim",
"author_id": 843943,
"author_profile": "https://Stackoverflow.com/users/843943",
"pm_score": 2,
"selected": false,
"text": "public void buyItems(Collection list, Closure except={it > 0}){\n list.findAll(){except(it)}.each(){print it}\n}\nbuyItems([1,2,3]){it > 2}\nbuyItems([0,1,2])\n"
},
{
"answer_id": 12729171,
"author": "Bojan Dolinar",
"author_id": 1720320,
"author_profile": "https://Stackoverflow.com/users/1720320",
"pm_score": 5,
"selected": false,
"text": "def list = [1, 'bla', false]\ndef (num, str, bool) = list\nassert num == 1\nassert str == 'bla'\nassert !bool\n"
},
{
"answer_id": 13470216,
"author": "Jason",
"author_id": 599058,
"author_profile": "https://Stackoverflow.com/users/599058",
"pm_score": 2,
"selected": false,
"text": "class FunctionTests {\n\ndef privateAccessWithClosure = {\n\n def privVar = 'foo'\n\n def privateFunc = { x -> println \"${privVar} ${x}\"}\n\n return {x -> privateFunc(x) } \n}\n\n\ndef addTogether = { x, y ->\n return x + y\n}\n\ndef curryAdd = { x ->\n return { y-> addTogether(x,y)}\n}\n\npublic static void main(String[] args) {\n def test = new FunctionTests()\n\n test.privateAccessWithClosure()('bar')\n\n def curried = test.curryAdd(5)\n\n println curried(5)\n}\n}\n"
},
{
"answer_id": 15295604,
"author": "Luis Muñiz",
"author_id": 1326627,
"author_profile": "https://Stackoverflow.com/users/1326627",
"pm_score": 2,
"selected": false,
"text": "def exec(operand1,operand2,Closure op) {\n op.call(operand1,operand2)\n}\n\ndef addition = {a,b->a+b}\ndef multiplication = {a,b->a*b}\n\ndef instructions = [\n [1,2,addition],\n [2,2,multiplication]\n]\n\ninstructions.each{instr->\n println exec(*instr)\n}\n String locale=\"en_GB\"\n\n//this invokes new Locale('en','GB')\ndef enGB=new Locale(*locale.split('_'))\n"
},
{
"answer_id": 17370576,
"author": "Hans Westerbeek",
"author_id": 273826,
"author_profile": "https://Stackoverflow.com/users/273826",
"pm_score": 4,
"selected": false,
"text": "groovy.transform @Immutable @CompileStatic @Canonical @Slf4j"
},
{
"answer_id": 20021341,
"author": "Omnipresent",
"author_id": 44286,
"author_profile": "https://Stackoverflow.com/users/44286",
"pm_score": 3,
"selected": false,
"text": "class Foo {\n def footest() { return \"footest\"} \n}\n\nclass Bar {\n @Delegate Foo foo = new Foo() \n}\n\ndef bar = new Bar()\n\nassert \"footest\" == bar.footest()\n"
},
{
"answer_id": 21147085,
"author": "micha",
"author_id": 1115554,
"author_profile": "https://Stackoverflow.com/users/1115554",
"pm_score": 3,
"selected": false,
"text": "def l = [1, 2, 3] + [4, 5, 6] - [2, 5] - 3 + (7..9)\nassert l == [1, 4, 6, 7, 8, 9]\n\ndef m = [a: 1, b: 2] + [c: 3] - [a: 1]\nassert m == [b: 2, c: 3]\n switch (42) {\n case 0: .. break\n case 1..9: .. break\n case Float: .. break\n case { it % 4 == 0 }: .. break\n case ~/\\d+/: .. break\n}\n assert (1..10).step(2) == [1, 3, 5, 7, 9]\nassert (1..10)[1, 4..8] == [2, 5, 6, 7, 8, 9]\nassert ('a'..'g')[-4..-2] == ['d', 'e', 'f']\n def α = 123\ndef β = 456\ndef Ω = α * β\nassert Ω == 56088\n"
},
{
"answer_id": 21161321,
"author": "BIdesi",
"author_id": 921399,
"author_profile": "https://Stackoverflow.com/users/921399",
"pm_score": 3,
"selected": false,
"text": "null def list = [obj1, obj2, null, obj4, null, obj6]\nlist -= null\nassert list == [obj1, obj2, obj4, obj6]\n"
},
{
"answer_id": 22589268,
"author": "lifeisfoo",
"author_id": 3340702,
"author_profile": "https://Stackoverflow.com/users/3340702",
"pm_score": 2,
"selected": false,
"text": "class Dynamic {\n def one() { println \"method one()\" }\n def two() { println \"method two()\" }\n}\n\ndef callMethod( obj, methodName ) {\n obj.\"$methodName\"()\n}\n\ndef dyn = new Dynamic()\n\ncallMethod( dyn, \"one\" ) //prints 'method one()'\ncallMethod( dyn, \"two\" ) //prints 'method two()'\ndyn.\"one\"() //prints 'method one()'\n"
},
{
"answer_id": 22595687,
"author": "ludo_rj",
"author_id": 2115767,
"author_profile": "https://Stackoverflow.com/users/2115767",
"pm_score": 2,
"selected": false,
"text": "withDefault def tree // declare first before using a self reference\ntree = { -> [:].withDefault{ tree() } }\n frameworks = tree()\nframeworks.grails.language.name = 'groovy'\nframeworks.node.language.name = 'js'\n\ndef result = new groovy.json.JsonBuilder(frameworks)\n {\"grails\":{\"language\":{\"name\":\"groovy\"}},\"node\":{\"language\":{\"name\":\"js\"}}}"
},
{
"answer_id": 29605238,
"author": "Pankaj Shinde",
"author_id": 1134084,
"author_profile": "https://Stackoverflow.com/users/1134084",
"pm_score": 3,
"selected": false,
"text": "long creditCardNumber = 1234_5678_9012_3456L\nlong socialSecurityNumbers = 999_99_9999L\ndouble monetaryAmount = 12_345_132.12\nlong hexBytes = 0xFF_EC_DE_5E\nlong hexWords = 0xFFEC_DE5E\nlong maxLong = 0x7fff_ffff_ffff_ffffL\nlong alsoMaxLong = 9_223_372_036_854_775_807L\nlong bytes = 0b11010010_01101001_10010100_10010010\n"
},
{
"answer_id": 29605341,
"author": "Pankaj Shinde",
"author_id": 1134084,
"author_profile": "https://Stackoverflow.com/users/1134084",
"pm_score": 2,
"selected": false,
"text": "def person = Person.find { it.id == 123 } // find will return a null instance \ndef name = person?.name // use of the null-safe operator prevents from a NullPointerException, result is null\n"
},
{
"answer_id": 30074202,
"author": "Tobia",
"author_id": 517371,
"author_profile": "https://Stackoverflow.com/users/517371",
"pm_score": 2,
"selected": false,
"text": "import groovy.transform.Memoized\n\n@Memoized\nNumber factorial(Number n) {\n n == 0 ? 1 : factorial(n - 1)\n}\n\n@Memoized(maxCacheSize=1000)\nMap fooDetails(Foo foo) {\n // call expensive service here\n}\n def factorial = {Number n ->\n n == 0 ? 1 : factorial(n - 1)\n}.memoize()\n\nfooDetails = {Foo foo ->\n // call expensive service here\n}.memoizeAtMost(1000)\n @Memoized import groovy.transform.Memoized\n\n@Memoized\ndef getMY_CONSTANT() {\n // compute the constant value using any external services needed\n}\n"
},
{
"answer_id": 34292560,
"author": "Ishwor",
"author_id": 2118080,
"author_profile": "https://Stackoverflow.com/users/2118080",
"pm_score": 0,
"selected": false,
"text": "displayCity = user.city ? user.city: 'UnKnown City'\n displayCity = user.city ?: 'UnKnown City'\n"
},
{
"answer_id": 35333290,
"author": "Zulqarnain Satti",
"author_id": 2829080,
"author_profile": "https://Stackoverflow.com/users/2829080",
"pm_score": 1,
"selected": false,
"text": "def (a,b,c) = [1,2,3]\n def (String a, int b) = ['Groovy', 1]\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
303,519 | <p>someone has an idea how can I do that ?</p>
<p>thanks</p>
| [
{
"answer_id": 303551,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "n n"
},
{
"answer_id": 303610,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 2,
"selected": false,
"text": "int foo[1000] = {0};\n"
},
{
"answer_id": 303666,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "n O(n) O(n) O(n) O(1)"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
303,548 | <p>I have the following xml that's sent to me from a web service. I'm using .NET to deserialize it, but I'm getting an exception saying that its formatted wrong. <code>There is an error in XML document (2, 2)</code> Now, if I understand that correctly, it's not liking that it's finding the first <code><error></code> node.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<messages xmlns="http://www.w3.org/1999/xml">
<error>error text</error>
<message>message text</message>
</messages>
</code></pre>
<p>my code looks like this, data being the <code>String</code> version of the XML above:</p>
<pre><code>Dim resp As cResponseMessage
Dim sr As New StringReader(data)
Dim xs As New XmlReaderSettings()
Dim xd As New XmlSerializer(GetType(cResponseMessage))
resp = xd.Deserialize(XmlTextReader.Create(sr, xs))
</code></pre>
<p>and <code>cResponseMessage</code> is simply a class with an <code>XMLRoot</code> attribute and 2 properties with <code>XMLElement</code> attributes. Nothing fancy here, but it doesn't want to work.</p>
<p>Any help would be great.</p>
| [
{
"answer_id": 303633,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": true,
"text": "<XmlRoot(Namespace:=\"http://www.w3.org/1999/xml\", ElementName:=\"messages\")> _\nPublic Class cResponseMessage\n\n <XmlElement> _\n Public Property [error] As String\n Get\n Set(ByVal value As String)\n End Property\n\n <XmlElement> _\n Public Property message As String\n Get\n Set(ByVal value As String)\n End Property\nEnd Class\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
303,554 | <p>I have a hidden field that i want to bind to either a function on the page's code behind. I don't quite recall the exact syntax and i can't find the answer via Google. Is the code below correct? Thank.</p>
<pre><code>print("<asp:HiddenField ID="dummy" Value='<%#Getdummy() %>' runat="server" />");
</code></pre>
| [
{
"answer_id": 303663,
"author": "WestDiscGolf",
"author_id": 33116,
"author_profile": "https://Stackoverflow.com/users/33116",
"pm_score": 2,
"selected": false,
"text": "<asp:HiddenField ID=\"hdnId\" runat=\"server\" Value='<%# GetValue() %>'/>\n protected string GetValue()\n{\n return \"something\";\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
303,555 | <p>Suppose I have two classes with the same interface:</p>
<pre><code>interface ISomeInterface
{
int foo{get; set;}
int bar{get; set;}
}
class SomeClass : ISomeInterface {}
class SomeOtherClass : ISomeInterface {}
</code></pre>
<p>Suppose I have an instance of ISomeInterface that represents a SomeClass. Is there an easy way to copy that into a new instance of SomeOtherClass without copying each member by hand?</p>
<p><strong>UPDATE:</strong> For the record, I'm <em>not</em> trying to cast the instance of SomeClass into the instance of SomeOtherClass. What I'd like to do is something like this:</p>
<pre><code>ISomeInterface sc = new SomeClass() as ISomeInterface;
SomeOtherClass soc = new SomeOtherClass();
soc.foo = sc.foo;
soc.bar = soc.bar;
</code></pre>
<p>I just don't want to have to do that for each by hand as these objects have lots of properties.</p>
| [
{
"answer_id": 303570,
"author": "mendicant",
"author_id": 1800,
"author_profile": "https://Stackoverflow.com/users/1800",
"pm_score": 3,
"selected": false,
"text": " public ISomeInterface CopyValues(ISomeInterface fromSomeClass, ISomeInterface toSomeOtherClass)\n {\n //copy properties here\n return toSomeOtherClass;\n }\n"
},
{
"answer_id": 303571,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 2,
"selected": false,
"text": "class MyClass : ICloneable\n{\npublic MyClass()\n{\n\n}\npublic object Clone() // ICloneable implementation\n{\nMyClass mc = this.MemberwiseClone() as MyClass;\n\nreturn mc;\n}\n"
},
{
"answer_id": 303627,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 3,
"selected": false,
"text": "public class SomeClass\n{\n public static implicit operator SomeOtherClass(SomeClass sc)\n {\n //replace with whatever conversion logic is necessary\n return new SomeOtherClass()\n {\n foo = sc.foo,\n bar = sc.bar\n }\n }\n\n public static implicit operator SomeClass(SomeOtherClass soc)\n {\n return new SomeClass()\n {\n foo = soc.foo,\n bar = soc.bar\n }\n }\n //rest of class here\n}\n SomeOtherClass soc = sc;"
},
{
"answer_id": 303752,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 3,
"selected": true,
"text": "var props = typeof(Foo)\n .GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\nforeach (PropertyInfo p in props)\n{\n // p.Name gives name of property\n}\n"
},
{
"answer_id": 303860,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": " ISomeInterface sc = new SomeClass() as ISomeInterface;\n SomeOtherClass soc = new SomeOtherClass();\n foreach (PropertyInfo info in typeof(ISomeInterface)\n .GetProperties(BindingFlags.Instance\n |BindingFlags.Public))\n {\n info.SetValue(soc,info.GetValue(sc,null),null);\n }\n"
},
{
"answer_id": 73515885,
"author": "Rafi Henig",
"author_id": 9369606,
"author_profile": "https://Stackoverflow.com/users/9369606",
"pm_score": 0,
"selected": false,
"text": "public interface IPerson\n{\n string Name { get; set; }\n\n static void CopyProperties<A, B>(A source, B dest) where A : IPerson where B : IPerson\n {\n foreach (var property in typeof(IPerson).GetProperties())\n {\n property.SetValue(dest, property.GetValue(source));\n }\n }\n}\n IPerson public class Worker : IPerson\n{\n public string Name { get; set; }\n}\n\npublic class Manager : IPerson\n{\n public string Name { get; set; }\n}\n var worker = new Worker { Name = \"John\" };\nvar manager = new Manager();\n\nIPerson.CopyProperties(worker, manager);\n new public interface IPerson\n {\n string Name { get; set; }\n \n static TDest ChangeType<TDest, TSource>(TSource source) where TSource : IPerson where TDest : IPerson, new()\n { \n var instance = new TDest();\n foreach (var property in typeof(IPerson).GetProperties())\n {\n property.SetValue(instance, property.GetValue(source));\n }\n return instance;\n }\n }\n \n var worker = new Worker { Name = \"John\" };\nvar manager = IPerson.ChangeType<Manager, Worker>(worker);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
303,562 | <p>I'm trying to write a macro that would allow me to do something like: <code>FORMAT(a << "b" << c << d)</code>, and the result would be a string -- the same as creating an ostringstream, inserting <code>a...d</code>, and returning <code>.str()</code>. Something like:</p>
<pre><code>string f(){
ostringstream o;
o << a << "b" << c << d;
return o.str()
}
</code></pre>
<p>Essentially, <code>FORMAT(a << "b" << c << d) == f()</code>.</p>
<p>First, I tried:</p>
<pre><code>1: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << items)).str()
</code></pre>
<p>If the very first item is a C string (<code>const char *</code>), it will print the address of the string in hex, and the next items will print fine. If the very first item is an <code>std::string</code>, it will fail to compile (no matching operator <code><<</code>).</p>
<p>This:</p>
<pre><code>2: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << 0 << '\b' << items)).str()
</code></pre>
<p>gives what seems like the right output, but the <code>0</code> and <code>\b</code> are present in the string of course.</p>
<p>The following seems to work, but compiles with warnings (taking address of temporary):</p>
<pre><code>3: #define FORMAT(items) \
((std::ostringstream&)(*((std::ostream*)(&std::ostringstream())) << items)).str()
</code></pre>
<p>Does anyone know why 1 prints the address of the c-string and fails to compile with the <code>std::string</code>? Aren't 1 and 3 essentially the same?</p>
<p>I suspect that C++0x variadic templates will make <code>format(a, "b", c, d)</code> possible. But is there a way to solve this now?</p>
| [
{
"answer_id": 303620,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "operator << (ostream&, char*) const void* using namespace std; #define MAKE_OUTPUT(z, n, data) \\\n BOOST_PP_TUPLE_ELEM(2, 0, data) << BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, data), n);\n\n#define MAKE_FORMAT(z, n, data) \\\n template <BOOST_PP_ENUM_PARAMS_Z(z, BOOST_PP_INC(n), typename T)> \\\n inline string format(BOOST_PP_ENUM_BINARY_PARAMS_Z(z, BOOST_PP_INC(n), T, p)) \\\n { \\\n ostringstream s; \\\n BOOST_PP_REPEAT_##z(z, n, MAKE_OUTPUT, (s, p)); \\\n return s.str(); \\\n }\n BOOST_PP_REPEAT(N, MAKE_FORMAT, ()) #undef BOOST_PP_REPEAT"
},
{
"answer_id": 303637,
"author": "cadabra",
"author_id": 39132,
"author_profile": "https://Stackoverflow.com/users/39132",
"pm_score": 1,
"selected": false,
"text": "#define FORMAT(items) \\\n ((std::ostringstream&)(std::ostringstream() << std::dec << items)).str()\n"
},
{
"answer_id": 303675,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": false,
"text": "#define FORMAT(items) static_cast<std::ostringstream &>((std::ostringstream() << std::string() << items)).str()\n"
},
{
"answer_id": 303716,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": false,
"text": "// makestring.h:\n\nclass MakeString\n{\n public:\n std::stringstream stream;\n operator std::string() const { return stream.str(); }\n\n template<class T>\n MakeString& operator<<(T const& VAR) { stream << VAR; return *this; }\n}; string myString = MakeString() << a << \"b\" << c << d;"
},
{
"answer_id": 306053,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 5,
"selected": true,
"text": "ostringstream ostream str() ostringstream .str() ostringstream ios::operator void*() operator<<(...) ostream ostream& ostringstream()<<\"foo\" ostream::operator<<(void* ) operator<<(ostream&,const char* ) ostream::operator<<(void* ) ostream ostringstream ostream ostringstream str() ostringstream() ostringstream() << std::string() // Kudos to *David Norman* ostringstream() << std::dec // Kudos to *cadabra* ostringstream() . seekp( 0, ios_base::cur ) ostringstream() . write( \"\", 0 ) ostringstream() . flush() ostringstream() << flush ostringstream() << nounitbuf ostringstream() << unitbuf ostringstream() << noshowpos #include <iomanip> operator<<( ostringstream(), \"\" ) (ostream &) ostringstream() (ostringstream&) dynamic_cast dynamic_cast NULL .str() str() #define FORMAT(ITEMS) \\\n ( ( dynamic_cast<ostringstream &> ( \\\n ostringstream() . seekp( 0, ios_base::cur ) << ITEMS ) \\\n ) . str() )\n ostringstream ostream::operator<<()"
},
{
"answer_id": 495080,
"author": "DevSolar",
"author_id": 60281,
"author_profile": "https://Stackoverflow.com/users/60281",
"pm_score": 1,
"selected": false,
"text": "ostringstream().seekp( 0, ios_base::cur )\n ostringstream() << std::dec\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39132/"
] |
303,591 | <p>Range intersection is a simple, but non-trivial problem.</p>
<p>Its has been answered twice already:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/224878/find-number-range-intersection">Find number range intersection</a></li>
<li><a href="https://stackoverflow.com/questions/143552/comparing-date-ranges">Comparing date ranges</a></li>
</ul>
<p>The first solutions is O(n) and the second solution is for a database (which is less than O(n) of course).</p>
<p>I have the same problem, but for a large n and I am not within a database.</p>
<p>This problem seems to be very similar to <a href="https://stackoverflow.com/questions/303243/store-2d-points-for-quick-retrieval-of-those-inside-a-rectangle">Store 2D points for quick retrieval of those inside a rectangle</a> but I don't see how it maps.</p>
<p>So what data structure would you store the set of ranges in, such that a search on a range costs less than O(n)? (Extra credit for using libraries available for Java)</p>
<p><b>EDIT:</b></p>
<p>I want to get a subset of all intersecting ranges, meaning the search range could intersect multiple ranges. </p>
<p>The method that needs to be less than O(n) in Java is:</p>
<pre><code>public class RangeSet {
....
public Set<Range> intersects(Range range);
....
}
</code></pre>
<p>Where Range is just a class containing a pair of int start and end.</p>
<p>This is not an impossible question, I already have the solution, I just wanted to see if there was a more standard/simpler way of doing it</p>
| [
{
"answer_id": 303644,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": " - if the node range intersects the input range:\n - if it's a leaf node, then add the range to your result list\n - if it's not a leaf node, then traverse down to the child nodes and repeat this process.\n"
},
{
"answer_id": 303736,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 0,
"selected": false,
"text": "final int lower; // lower end of range\nfinal int upper; // upper end of range\n\npublic int compareTo(Object obj) {\n if(obj==null) { return -1; }\n\n Range oth=(Range)obj;\n\n if(lower<oth.lower) { return -1; }\n if(lower>oth.lower) { return 1; }\n if(upper<oth.upper) { return -1; }\n if(upper>oth.upper) { return 1; }\n return 0;\n }\n public Builder addRange(int fir, int las) {\n if(fir!=-1) { fir&=0x001FFFFF; }\n if(las!=-1) { las&=0x001FFFFF; }\n\n if(codepoints==null || codepoints.length==0) {\n codepoints=new Range[]{new Range(fir,las)};\n }\n else {\n int idx=Range.findChar(codepoints,fir);\n int ins=(idx<0 ? -(idx+1) : idx);\n\n if(idx<0) {\n if (ins>0 && fir==(codepoints[ins-1].upper+1)) { idx=(ins-1); } // new range adjoins the following range (can't overlap or idx would be >=0)\n else if(ins<codepoints.length && las>=(codepoints[ins ].lower-1)) { idx=ins; } // new range overlaps or adjoins the following range\n }\n\n if(idx<0) {\n codepoints=(Range[])Util.arrayInsert(codepoints,ins,new Range(fir,las));\n }\n else {\n boolean rmv=false;\n\n for(int xa=(idx+1); xa<codepoints.length && codepoints[xa].lower<=las; xa++) {\n if(las<codepoints[xa].upper) { las=codepoints[xa].upper; }\n codepoints[xa]=null;\n rmv=true;\n }\n if(codepoints[idx].lower>fir || codepoints[idx].upper<las) {\n codepoints[idx]=new Range((codepoints[idx].lower < fir ? codepoints[idx].lower : fir),(codepoints[idx].upper>las ? codepoints[idx].upper : las));\n }\n if(rmv) { codepoints=Range.removeNulls(codepoints); }\n }\n }\n return this;\n }\n static int findChar(Range[] arr, int val) {\n if(arr.length==1) {\n if (val< arr[0].lower) { return -1; } // value too low\n else if(val<=arr[0].upper) { return 0; } // value found\n else { return -2; } // value too high\n }\n else {\n int lowidx=0; // low index\n int hghidx=(arr.length-1); // high index\n int mididx; // middle index\n Range midval; // middle value\n\n while(lowidx<=hghidx) {\n mididx=((lowidx+hghidx)>>>1);\n midval=arr[mididx];\n if (val< midval.lower) { hghidx=(mididx-1); } // value too low\n else if(val<=midval.upper) { return mididx; } // value found\n else { lowidx=(mididx+1); } // value too high\n }\n return -(lowidx+1); // value not found.\n }\n }\n"
},
{
"answer_id": 303881,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 5,
"selected": false,
"text": "class TreeNode\n{\npublic:\n long pivot;\n List<Range> leaves; //Any ranges that intersect the pivot\n TreeNode left; //Tree nodes that fall to the left of the pivot\n TreeNode right; //Tree nodes that fall to the right of the pivot\n};\n 4\n --------------+------------------\n 3 | 7\n | 1-4 |\n | 2-4 |\n | 0-5 |\n | 4-5 |\n ---------+------ --------+--------\n 2 | null 6 | null\n -----+---- 2-3 ----+---- 3-7\nnull | null null | null \n 0-2 2-6\n 1-2\n"
},
{
"answer_id": 303922,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 2,
"selected": false,
"text": "int stop[size];\nstop[size-1] = Ranges[size - 1].start;\nfor (int i = size - 2; i >= 0; i--)\n{\n stop[i] = min(Ranges[i].start, stop[i+1]);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
303,608 | <p>I noticed that doxygen uses the graphviz library for creating diagrams. Have you ever used graphviz for generating documentation? Is it worth learning the graphviz for documentation purposes outside the scope of doxygen? Or am I better off to sticking with a standard data modeling package like Visio?</p>
<p>I understand the merits of it as a graphing library, but for trying to represent more complex UML (or similar) is it still worth looking into?</p>
| [
{
"answer_id": 976801,
"author": "Quinn Taylor",
"author_id": 120292,
"author_profile": "https://Stackoverflow.com/users/120292",
"pm_score": 4,
"selected": false,
"text": "-(NSString*)dotGraphString -(NSString*)dotGraphStringForNode: CHAbstractBinarySearchTree.m dotGraphString"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
303,611 | <p>I originally used WebRequest and WebResponse to sent Http Post Messages. Always I got a response of "OK". The message I post is an XML signed with a certificate in the xml.</p>
<p>The composition is this:
C# service that is sending to a https website.
HTTPS Website on another place that I cant say.
HTTPS Local Website locally that is just receiving the messages I post locally and writing the results to a file. Just to simulate what the other website is getting.</p>
<p>Local Website is signed with a self signed certificate to expire in 2048. </p>
<p>This code was working fine until this week. I always posted and got an OK. In both websites. But this week the test and the real project implementation both go Kaput. On Both Websites.
<br/> On the local website it was saying unable to connect to SSL.
This problem is caused by the self signed certificate that for some reason beyond my understanding its giving hell. Thanks to the questions here I just validated the certificate to always be true and now it is not bugging anymore.</p>
<p>To fix this just write this: </p>
<pre><code>ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
</code></pre>
<p>In the start of your application. So that it only runs once.</p>
<p>The remaining problem is the "The remote server returned an error: (503) Server Unavailable.". I enter the URL in my browser and it works fine for me. In the code this website is not receiving anything and when it goes to the web response it gives me the above error</p>
<p>I did a test application that only sends "Testing 1 2 3" but I keep getting the error. I also sent it to a harvard https website and there was no errors.</p>
<pre><code>private void btnSend_Click(object sender, EventArgs e)
{
try
{
WebRequest req = WebRequest.Create(cboUrl.Text);
req.PreAuthenticate = true;
req.UseDefaultCredentials = true;
req.Method = "POST";
req.ContentType = "text/xml";
String msg = txtMsg.Text;
using (Stream s = req.GetRequestStream())
{
try
{
s.Write(
System.Text.ASCIIEncoding.ASCII.GetBytes(msg), 0, msg.Length);
}
finally
{
s.Close();
}
}
WebResponse resp = req.GetResponse();
StreamReader str = new StreamReader(resp.GetResponseStream());
txtRes.Text = str.ReadToEnd();
}
catch (WebException ex)
{
txtRes.Text = ex.Message;
}
catch (Exception ex)
{
txtRes.Text = ex.Message;
}
}
</code></pre>
<p>This is another example I built from what I found in the internet:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(cboUrl.Text);
myReq.Headers.Clear();
myReq.Method = "POST";
myReq.KeepAlive = false;
myReq.ProtocolVersion = HttpVersion.Version11;
myReq.ContentType = "text/xml";
myReq.Proxy = null;
myReq.Credentials = null;
myReq.ContentLength = txtMsg.Text.Length;
using (StreamWriter sendingData = new StreamWriter(myReq.GetRequestStream()))
{
sendingData.Write(txtMsg.Text);
sendingData.Flush();
sendingData.Close();
}
HttpWebResponse myResponse = (HttpWebResponse) myReq.GetResponse();
StreamReader responseStream = new StreamReader(myResponse.GetResponseStream());
txtRes.Text = responseStream.ReadToEnd();
responseStream.Close();
myResponse.Close();
}
catch(WebException ex )
{
txtRes.Text = ex.Message;
}
catch (Exception ex)
{
txtRes.Text = ex.Message;
}
}
</code></pre>
<p><strong>Update</strong></p>
<p>Error was that the one I was calling with httpwebrequest, needed some httpheaders that I was not providing. Before the only thing that happened was that I got an "OK" response. They fixed their code and I fixed mine and now its working. </p>
<p>If it happens to someone else check like the one below said the proxy settings and also check if the other side is giving an exception or returning nothing at all.</p>
| [
{
"answer_id": 15832221,
"author": "gradosevic",
"author_id": 915320,
"author_profile": "https://Stackoverflow.com/users/915320",
"pm_score": 1,
"selected": false,
"text": "request.Proxy = null; request.Credentials = System.Net.CredentialCache.DefaultCredentials;"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12924/"
] |
303,613 | <p>Here are the specs that I'm trying to implement in a nutshell:</p>
<p>1) Some Alerts have to be sent on certain events in the application.</p>
<p>2) These Alerts have Users subscribe to them.</p>
<p>3) And the Users have set their own Notification preferences (e.g. Email and/or SMS).</p>
<p>I have not been able to find an open source solution in Java so far.</p>
<p>Is JMX Notifications an option? The more I read about JMX, the more I feel that it is trying to achieve something different that my problem.</p>
<p>Any help would be useful.</p>
| [
{
"answer_id": 3682691,
"author": "simbo1905",
"author_id": 329496,
"author_profile": "https://Stackoverflow.com/users/329496",
"pm_score": 1,
"selected": false,
"text": "-Dcom.sun.management.jmxremote.port=9999 \n-Dcom.sun.management.jmxremote.authenticate=false \n-Dcom.sun.management.jmxremote.ssl=false\n jconsole"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325613/"
] |
303,625 | <p>I've followed the ADAM Step by Step Guide from Microsoft and setup an ADAM instance on my local machine. I'm attempting to authenticate using the "Mary Baker" account, but every time I get a COM exception on the <code>if (entry.Guid != null)</code> line below. The exception states that there's an unknown user name or bad password.</p>
<p>However, I can use the ldp utility to connect to ADAM and successfully perform a simple bind - so I know that the user name both exists, and I have the correct password.</p>
<p>Additionally, I have set the msDS-UserAccountDisabled property on the user to false, and added the user to both the Administrators and Readers roles. </p>
<p>Any thoughts?</p>
<pre><code> path = "LDAP://localhost:50000/O=Microsoft,c=US";
userId = "CN=Mary Baker,OU=ADAM users,";
password = "Mary@101";
DirectoryEntry entry = new DirectoryEntry(path, userId, password, AuthenticationTypes.None);
if (entry.Guid != null)
LoadWelcomeScreen();
</code></pre>
<p>Thanks.</p>
| [
{
"answer_id": 6287693,
"author": "Ryan Sweet",
"author_id": 79736,
"author_profile": "https://Stackoverflow.com/users/79736",
"pm_score": 2,
"selected": false,
"text": "displayName user displayName displayName"
},
{
"answer_id": 16465582,
"author": "Kwex",
"author_id": 705902,
"author_profile": "https://Stackoverflow.com/users/705902",
"pm_score": 1,
"selected": false,
"text": " [TestMethod]\n public void CreateUserAccount()\n {\n var username = \"amurray\";\n var password = \"ADAMComplexPassword1234\";\n var firstname = \"Andy\";\n var lastname = \"Murray\";\n\n const AuthenticationTypes authTypes = AuthenticationTypes.Signing |\n AuthenticationTypes.Sealing |\n AuthenticationTypes.Secure;\n\n var ldapPath = \"LDAP://localhost:389/OU=MyProject,OU=Applications,DC=Company,DC=ADAM\";\n using (var dirEntry = new DirectoryEntry(ldapPath, \"MyPC\\\\adamuser\", \"Password1!\", authTypes))\n {\n DirectoryEntry user = null;\n const int ADS_PORT = 389;\n const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;\n const long ADS_OPTION_PASSWORD_METHOD = 7;\n const int ADS_PASSWORD_ENCODE_CLEAR = 1;\n\n try\n {\n user = dirEntry.Children.Add(string.Format(\"CN={0} {1}\", firstname, lastname), \"user\");\n user.Properties[\"displayName\"].Value = username;\n user.Properties[\"userPrincipalName\"].Value = username;\n user.Properties[\"msDS-UserAccountDisabled\"].Value = false;\n user.Properties[\"msDS-UserDontExpirePassword\"].Value = true;\n user.CommitChanges();\n var userid = user.Guid.ToString();\n\n // Set port number, method, and password.\n user.Invoke(\"SetOption\", new object[]{ADS_OPTION_PASSWORD_PORTNUMBER,ADS_PORT});\n user.Invoke(\"SetOption\", new object[]{ADS_OPTION_PASSWORD_METHOD,ADS_PASSWORD_ENCODE_CLEAR});\n\n user.Invoke(\"SetPassword\", new object[] {password});\n user.CommitChanges();\n user.Close();\n }\n catch (Exception e)\n {\n var msg = e.GetBaseException().Message;\n Console.WriteLine(e);\n System.Diagnostics.Debug.Print(msg);\n } \n }\n }\n\n\n [TestMethod]\n public void TestUserAuthentication()\n {\n try\n {\n var ldsContext = new PrincipalContext(ContextType.ApplicationDirectory, \"localhost:389\",\n \"OU=MyProject,OU=Applications,DC=Company,DC=ADAM\",\n ContextOptions.SimpleBind);\n\n // Returns true if login details are valid\n var isValid = ldsContext.ValidateCredentials(\"amurray\", \"ADAMComplexPassword1234\", ContextOptions.SimpleBind);\n }\n catch (Exception e)\n {\n var msg = e.GetBaseException().Message;\n Console.WriteLine(e);\n System.Diagnostics.Debug.Print(msg);\n }\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26218/"
] |
303,639 | <p>I'm terrible with regex, but I've had a try and a Google (and even looked in reddit's source) and I'm still stuck so here goes:</p>
<p>My aim is to match the following 'codes' and replace them with the HTML tags. It's just the regex I'm stuck with.</p>
<pre><code>**bold text**
_italic text_
~hyperlink~
</code></pre>
<p>Here's my attempts at the bold one:</p>
<pre><code>^\*\*([.^\*]+)\*\*$
</code></pre>
<p>Why this isn't working? I'm using the preg syntax.</p>
| [
{
"answer_id": 303647,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "\\*\\*(.[^*]*)\\*\\*\n \\*\\* // match two *'s\n(. // match any character\n[^*] // that is not a *\n*) // continuation of any character\n\\*\\* // match two *'s\n (.*) (.[^*]*) **bold *text** \\*\\*(.*?)\\*\\*\n"
},
{
"answer_id": 303657,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "\\*\\*(.+?)\\*\\*\n"
},
{
"answer_id": 303669,
"author": "Adam",
"author_id": 13320,
"author_profile": "https://Stackoverflow.com/users/13320",
"pm_score": 1,
"selected": false,
"text": "\\*\\*(.*?)\\*\\*\n"
},
{
"answer_id": 304065,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "\\*\\*((?:[^*]|\\*(?!\\*))*)\\*\\* my %tag2re = (b => <<'RE_BOLD', i => '_([^_]*)_');\n \\*\\*( # begin bold\n (?:[^*] # non-star\n | # or\n \\*(?!\\*) # single star\n )* # zero or more times\n )\\*\\* # end bold\nRE_BOLD\n\nmy $text = <<BBCODE;\nbefore **bold and _italic_ *text\n2nd line** after _just\n italic_ \n****\n**tag _soup** as a result_\nBBCODE\n\nwhile (my ($tag, $re) = each %tag2re) {\n $text =~ s~$re~<$tag>$1</$tag>~gsx;\n}\nprint $text;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
303,642 | <p>I have written a new custom component derived from TLabel. The component adds some custom drawing to component, but nothing else. When component is painted, everything works fine. But when the redraw is needed (like dragging another window over the component), "label part" works fine but my custom drawing is not properly updated. I'm basically drawing directly to the canvas in an overridden Paint method, and when the redraw is required the parts of canvas where my code has drawn something is painted black. It seems like that the paint method is not called. What I should do to get proper redraw?</p>
<p>The component is basically:</p>
<pre><code>TMyComponent = class(TCustomLabel, IMyInterface)
..
protected
procedure Paint; override;
..
procedure TMyComponent.Paint;
begin
inherited;
MyCustomPaint;
end;
</code></pre>
<p>Update, the paint routine:</p>
<pre><code>Position := Point(0,0);
Radius := 15;
FillColor := clBlue;
BorderColor := clBlack;
Canvas.Pen.Color := BorderColor;
Canvas.Pen.Width := 1;
Canvas.Brush.Color := BorderColor;
Canvas.Ellipse(Position.X, Position.Y, Position.X + Radius, Position.Y + Radius);
Canvas.Brush.Color := FillColor;
Canvas.FloodFill(Position.X + Radius div 2,
Position.Y + Radius div 2, BorderColor, fsSurface);
</code></pre>
<p>SOLVED:</p>
<p>The problem is (redundant) use of FloodFill. If the Canvas is not fully visible floodfill causes artifacts. I removed the floodfill and now it works as needed.</p>
| [
{
"answer_id": 303899,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 1,
"selected": false,
"text": "procedure TMyComponent.MyCustomPaint;\nvar\n rect: TRect;\nbegin\n rect := self.BoundsRect;\n rect.TopLeft := ParentToClient(rect.TopLeft);\n rect.BottomRight := ParentToClient(Rect.BottomRight);\n Canvas.Pen.Color := clRed;\n Canvas.Rectangle(Rect);\nend;\n"
},
{
"answer_id": 304219,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "TXPManifest"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7735/"
] |
303,656 | <p>Our application is an Xbap running in full trust. I have a function similar to this:</p>
<pre><code>private void ShowPage(Page page)
{
NavigationWindow mainWindow = Application.Current.MainWindow as NavigationWindow;
mainWindow.Navigate(page);
}
</code></pre>
<p>This works great for browsing inside an existing window. I would like to open this new page in a separate window. Is there anyway to do this?</p>
<p>There is an overload that takes 'extraData' but I haven't been able to determine what to pass to navigate to a new window.</p>
| [
{
"answer_id": 310022,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 3,
"selected": true,
"text": "private void ShowPage(Page page)\n{\n NavigationWindow popup = new NavigationWindow(); \n popup.Height = 400;\n popup.Width = 600;\n popup.Show();\n popup.Navigate(page);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514/"
] |
303,664 | <p>I am new to Python, and I'm working on writing some database code using the <code>cx_Oracle</code> module. In the <a href="http://cx-oracle.sourceforge.net/html/module.html" rel="nofollow noreferrer">cx_Oracle documentation</a> they have a code example like this:</p>
<pre><code>import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc.args
print >> sys.stderr, "Oracle-Error-Code:", error.code
print >> sys.stderr, "Oracle-Error-Message:", error.message
</code></pre>
<p>My question has to do with where the "error" object is created. What does the "<code>, =</code>" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)</p>
<p>I know that the exc.args is a singleton tuple, but I just don't understand the "<code>, =</code>" syntax. If I remove the comma, I get the error message, "<code>AttributeError: 'tuple' object has no attribute 'code'</code>". </p>
<p>Can someone point me to where this is documented? Thanks!</p>
<p><strong>EDIT:</strong></p>
<p>This works without having to unpack the tuple:</p>
<pre><code>import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code
print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message
</code></pre>
| [
{
"answer_id": 303693,
"author": "Andrew Beyer",
"author_id": 38691,
"author_profile": "https://Stackoverflow.com/users/38691",
"pm_score": 2,
"selected": false,
"text": "error"
},
{
"answer_id": 303697,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 4,
"selected": true,
"text": "error, = exc.args\n [error] = exc.args\n (foo,)"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31319/"
] |
303,668 | <p>Hey I usually run into a situation where I will create a class that should only be instantiated by one or a few classes. In this case I would make its constructor private and make it a friend class to the objects that should be able to instantiate it. For example (in C++):</p>
<pre><code>class CFoo
{
friend class CFoo;
// private ctor because only a select few classes should instantiate
private:
CFoo()
{
... Do stuff
}
}
class CBar
{
// CBar is one of the few classes that only need to use CFoo
CFoo *m_pFoo;
CBar()
{
m_pFoo = new CFoo;
}
}
</code></pre>
<p>So my question is: Is this stupid? Or is there a better way to achieve this? I'm especially interested in a way where it would work with C# considering the language lacks the friend keyword completely. Thanks.</p>
| [
{
"answer_id": 303680,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 1,
"selected": false,
"text": "public class CBar\n{\n CBar()\n {\n m_pFoo = new CFoo();\n }\n\n CFoo m_pFoo;\n\n private class CFoo\n {\n CFoo()\n {\n // Do stuff\n }\n }\n}\n"
},
{
"answer_id": 303692,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "internal class CFoo\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115/"
] |
303,679 | <p>I would like to search my table having a column of first names and a column of last names. I currently accept a search term from a field and compare it against both columns, one at a time with </p>
<pre><code> select * from table where first_name like '%$search_term%' or
last_name like '%$search_term%';
</code></pre>
<p>This works fine with single word search terms but the result set includes everyone with the name "Larry". But if someone enters a first name then a space, then a last name, I want a narrower search result. I've tried the following without success. </p>
<pre><code> select * from table where first_name like '%$search_term%' or last_name
like '%$search_term%' or concat_ws(' ',first_name,last_name)
like '%$search_term%';
</code></pre>
<p>Any advice?</p>
<p><strong>EDIT:</strong> The name I'm testing with is "Larry Smith". The db stores "Larry" in the "first_name" column, and "Smith" in the "last_name" column. The data is clean, no extra spaces and the search term is trimmed left and right.</p>
<p><strong>EDIT 2:</strong> I tried Robert Gamble's answer out this morning. His is very similar to what I was running last night. I can't explain it, but this morning it works. The only difference I can think of is that last night I ran the concat function as the third "or" segment of my search query (after looking through first_name and last_name). This morning I ran it as the last segment after looking through the above as well as addresses and business names. </p>
<p>Does running a mysql function at the end of a query work better than in the middle?</p>
| [
{
"answer_id": 303730,
"author": "Jack",
"author_id": 24998,
"author_profile": "https://Stackoverflow.com/users/24998",
"pm_score": 3,
"selected": false,
"text": "SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'\n"
},
{
"answer_id": 303770,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 8,
"selected": true,
"text": "select * from table where concat_ws(' ',first_name,last_name) \nlike '%$search_term%';\n"
},
{
"answer_id": 303950,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 1,
"selected": false,
"text": "$whereclauses=array();\n$terms = explode(' ', $search_term);\nforeach ($terms as $term) {\n $term = mysql_real_escape_string($term);\n $whereclauses[] = \"CONCAT(first_name, ' ', last_name) LIKE '%$term%'\";\n}\n$sql = \"select * from table where\";\n$sql .= implode(' and ', $whereclauses);\n"
},
{
"answer_id": 9226729,
"author": "Luc",
"author_id": 1201863,
"author_profile": "https://Stackoverflow.com/users/1201863",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'\n SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%')\n"
},
{
"answer_id": 9421910,
"author": "zelyan",
"author_id": 1229452,
"author_profile": "https://Stackoverflow.com/users/1229452",
"pm_score": 2,
"selected": false,
"text": "select * from table where concat(' ',first_name,last_name) \n like '%$search_term%';\n"
},
{
"answer_id": 13184217,
"author": "mynameispaulie",
"author_id": 1329264,
"author_profile": "https://Stackoverflow.com/users/1329264",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', first_name, last_name, CAST(age AS CHAR)) LIKE UPPER('%$search_term%');\n"
},
{
"answer_id": 27108534,
"author": "juanchobar",
"author_id": 4288168,
"author_profile": "https://Stackoverflow.com/users/4288168",
"pm_score": -1,
"selected": false,
"text": "select * FROM table where (concat(first_name, ' ', last_name)) = $search_term;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
303,699 | <p>I have a text area and a function to do syntax highlighting on it. Right now it reads the entire RichTextBox. How would I get a string variable containing the current line? Below is the code i currently have.</p>
<pre><code>Private Sub HighLight()
Dim rm As System.Text.RegularExpressions.MatchCollection
Dim m As System.Text.RegularExpressions.Match
Dim x As Integer ''lets remember where the text courser was before we mess with it
For Each pass In FrmColors.lb1.Items
x = rtbMain.SelectionStart
rm = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
For Each m In rm
rtbMain.Select(m.Index, m.Length)
rtbMain.SelectionColor = Color.Blue
Next
rtbMain.Select(x, 0)
rtbMain.SelectionColor = Color.Black
Next
End Sub
</code></pre>
| [
{
"answer_id": 303729,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": true,
"text": "rtbMain.Lines(lineNumber)\n"
},
{
"answer_id": 303733,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 1,
"selected": false,
"text": "rtbMain.Lines(rtbMain.GetLineFromCharIndex(rtbMain.SelectionStart))\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39143/"
] |
303,712 | <p>In a Java application (JRE 1.5.0_12) on Windows XP, I call a native method:</p>
<pre><code>public native int attachImage( ... );
</code></pre>
<p>... which lives in a Visual C++ 6.0 .dll. It displays an application-modal window. Problem is, the application's tray icon doesn't respond to mouseclicks while this window has focus. This is an issue because when this window is displayed, users often switch to another application to select the image to attach, then want to restore this application.</p>
| [
{
"answer_id": 303753,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 2,
"selected": true,
"text": "Shell shell = new Shell(display,SWT.APPLICATION_MODAL);\n dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35142/"
] |
303,718 | <p>My Firefox 3.0.4 does not display non-existing images at all, or it displays the image alt as plain text (if available).<br/>
This way I would have no idea that there is supposed to be an image there.</p>
<p>Does anyone know if there is a way to make it work like IE/Opera? (ie. display a box even if the image file doesn't exists) - plugin or anything?</p>
<p>Test image: <img src="https://example.com/notavalidlink" alt="[broken image test]"></p>
| [
{
"answer_id": 303772,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": -1,
"selected": false,
"text": "<img src='...' width='100' height='100' alt='...'></img>\nor\n<img src='...' alt='...' style='width:100px; height:100px;'></img>\n"
},
{
"answer_id": 303973,
"author": "Grayside",
"author_id": 38408,
"author_profile": "https://Stackoverflow.com/users/38408",
"pm_score": 1,
"selected": false,
"text": "<img>"
},
{
"answer_id": 6744791,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 2,
"selected": false,
"text": "browser.display.show_image_placeholders userContent.css /*\n * Show image placeholders\n */\n@-moz-document url-prefix(http), url-prefix(https), url-prefix(file) {\n img:-moz-broken {\n -moz-force-broken-image-icon: 1;\n width: 24px;\n height: 24px;\n }\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36036/"
] |
303,720 | <p>I'm looking for something like <code>alert()</code>, but that doesn't "pause" the script.</p>
<p>I want to display an alert and allow the next command, a form <code>submit()</code>, to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK.</p>
<p>Is there something like this or is it just one of those impossible things?</p>
| [
{
"answer_id": 303735,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 7,
"selected": true,
"text": "setTimeout(\"alert('hello world');\", 1);\n setTimeout(function() { alert('hello world'); }, 1);\n eval"
},
{
"answer_id": 31519945,
"author": "JasonK",
"author_id": 5135621,
"author_profile": "https://Stackoverflow.com/users/5135621",
"pm_score": 2,
"selected": false,
"text": "/*HTML*/\n<div class=\"floatingDiv\" id=\"msgBox\" style=\"visibility:hidden\"></div>\n\n/*javaScript*/\nfunction openWindow(id){\n\"use strict\";\ndocument.getElementById(id).style.visibility = 'visible'; \n}\nfunction closeWindow(id){\n\"use strict\";\ndocument.getElementById(id).style.visibility = 'hidden'; \n}\nfunction myMsgBox(TITLE,MESSAGE) {\n\"use strict\"; \ndocument.getElementById(\"msgBox\").innerHTML = \"<a href=\\\"javascript:closeWindow('msgBox')\\\" style=\\\"float:right\\\"><img src=\\\"imgs/close.png\\\" onmouseover=\\\"src='imgs/closeOver.png'\\\" onmouseout=\\\"src='imgs/close.png'\\\"/ alt=\\\"[close]\\\"></a><h2 style=\\\"text-align:center; margin-top:0px;\\\">\" + TITLE + \"</h2><hr><p align=\\\"left\\\">\" + MESSAGE + \"</p>\";\nopenWindow(\"msgBox\");\n}\n\n/*CSS*/\n.floatingDiv {\nposition:absolute; \nz-index:10000;\nleft:33%;\ntop:250px;\nwidth:33%;\nbackground-color:#FFF;\nmin-width:217px;\ntext-align: left;\nborder-radius: 10px 10px;\nborder:solid;\nborder-width:1px;\nborder-color:#000;\nvertical-align:top;\npadding:10px;\n\nbackground-image: -ms-linear-gradient(top, #CCCCCC 0%, #FFFFFF 25px, #FFFFFF 100%);\nbackground-image: -moz-linear-gradient(top, #CCCCCC 0%, #FFFFFF 25px, #FFFFFF 100%);\nbackground-image: -o-linear-gradient(top, #CCCCCC 0%, #FFFFFF 25px, #FFFFFF 100%);\nbackground-image: -webkit-linear-gradient(top, #CCCCCC 0%, #FFFFFF 25px, #FFFFFF 100%);\nbackground-image: linear-gradient(to bottom, #CCCCCC 0%, #FFFFFF 25px, #FFFFFF 100%);\n\nbox-shadow:3px 3px 5px #003; \nfilter: progid:DXImageTransform.Microsoft.Shadow(color='#000033', Direction=145, Strength=3);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
303,726 | <p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p>
<pre><code>import sys
import socket
import re
from urlparse import urlsplit
url = urlsplit(sys.argv[1])
sock = socket.socket()
sock.connect((url[0] + '://' + url[1],80))
path = url[2]
if not path:
path = '/'
print path
sock.send('GET ' + path + ' HTTP/1.1\r\n'
+ 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n'
+ 'Accept: */*\r\n'
+ 'Accept-Language: en-US,en\r\n'
+ 'Accept-Charset: ISO-8859-1,*,utf-8\r\n'
+ 'Host: 68.33.143.182\r\n'
+ 'Connection: Keep-alive\r\n'
+ '\r\n')
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File
"D:\Development\Python\PyCrawler\PyCrawler.py",
line 10, in
sock.connect((url[0] + '://' + url[1],80)) File "", line 1,
in connect socket.gaierror: (11001,
'getaddrinfo failed')</p>
</blockquote>
<p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow noreferrer">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
| [
{
"answer_id": 303747,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 1,
"selected": false,
"text": "addr = socket.gethostbyname(url[1])\n...\nsock.connect((addr,80))\n"
},
{
"answer_id": 303749,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "sock.connect((url[0] + '://' + url[1],80))\n sock.connect((url[1], 80))\n connect"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
303,745 | <p>This is probably a beginner question, but how do you set a recordset to a string variable? </p>
<p>Here is my code: </p>
<pre><code>Function getOffice (strname, uname)
strEmail = uname
WScript.Echo "email: " & strEmail
Dim objRoot : Set objRoot = GetObject("LDAP://RootDSE")
Dim objDomain : Set objDomain = GetObject("LDAP://" & objRoot.Get("defaultNamingContext"))
Dim cn : Set cn = CreateObject("ADODB.Connection")
Dim cmd : Set cmd = CreateObject("ADODB.Command")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Set cmd.ActiveConnection = cn
cmd.CommandText = "SELECT physicalDeliveryOfficeName FROM '" & objDomain.ADsPath & "' WHERE mail='" & strEmail & "'"
cmd.Properties("Page Size") = 1
cmd.Properties("Timeout") = 300
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Dim objRS : Set objRS = cmd.Execute
WScript.Echo objRS.Fields(0)
Set cmd = Nothing
Set cn = Nothing
Set objDomain = Nothing
Set objRoot = Nothing
Dim arStore
Set getOffice = objRS.Fields(0)
Set objRS = Nothing
End function
</code></pre>
<p>When I try to run the function, it throws an error "vbscript runtime error: Type mismatch"
I presume this means it can't set the string variable with a recordset value. </p>
<p>How do I fix this problem?</p>
<hr>
<p>I just tried </p>
<p>if IsNull(objRS.Fields(0).Value) = TRUE then
getOFfice = "noAD"
else
getOFfice = objRS.Fields(0).VAlue
end if </p>
<p>And that throws a different error ADODB.Field: Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.</p>
| [
{
"answer_id": 303754,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 0,
"selected": false,
"text": "Cstr(objRS.Fields(0))\n"
},
{
"answer_id": 312645,
"author": "AnonJr",
"author_id": 25163,
"author_profile": "https://Stackoverflow.com/users/25163",
"pm_score": 0,
"selected": false,
"text": "Function getOffice (strname, uname) \n\nstrEmail = uname\nWScript.Echo \"email: \" & strEmail \nDim objRoot : Set objRoot = GetObject(\"LDAP://RootDSE\")\nDim objDomain : Set objDomain = GetObject(\"LDAP://\" & objRoot.Get(\"defaultNamingContext\"))\nDim cn : Set cn = CreateObject(\"ADODB.Connection\")\nDim cmd : Set cmd = CreateObject(\"ADODB.Command\")\ncn.Provider = \"ADsDSOObject\"\ncn.Open \"Active Directory Provider\"\nSet cmd.ActiveConnection = cn\n\ncmd.CommandText = \"SELECT physicalDeliveryOfficeName FROM '\" & objDomain.ADsPath & \"' WHERE mail='\" & strEmail & \"'\"\ncmd.Properties(\"Page Size\") = 1\ncmd.Properties(\"Timeout\") = 300\ncmd.Properties(\"Searchscope\") = ADS_SCOPE_SUBTREE\n\nDim objRS : Set objRS = cmd.Execute\n\nIf Not objRS.BOF Then objRS.Move First\nIf Not objRS.EOF Then \n If Not IsNull(objRS.Fields(0)) and objRS.Fields(0) <> \"\" Then WScript.Echo cStr(objRS.Fields(0))\nEnd If\n\nSet cmd = Nothing\nSet cn = Nothing\nSet objDomain = Nothing\nSet objRoot = Nothing\n\nDim arStore \n\nSet getOffice = objRS.Fields(0)\n\nSet objRS = Nothing\n\nEnd function\n"
},
{
"answer_id": 315173,
"author": "Tester101",
"author_id": 38695,
"author_profile": "https://Stackoverflow.com/users/38695",
"pm_score": 2,
"selected": false,
"text": "\nIf objRS.RecordCount <> 0 Then\n getOffice = CStr(objRS.Fields(0))\nElse\n getOffice = \"\"\nEnd If\n"
},
{
"answer_id": 322261,
"author": "Tester101",
"author_id": 38695,
"author_profile": "https://Stackoverflow.com/users/38695",
"pm_score": 2,
"selected": false,
"text": "\ngetOffice = objRS.getString\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
303,759 | <p>I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char* to a long long type. Is there an easy way to do it?</p>
<p>Thanks in advance :)</p>
| [
{
"answer_id": 303796,
"author": "altruic",
"author_id": 38620,
"author_profile": "https://Stackoverflow.com/users/38620",
"pm_score": 4,
"selected": true,
"text": "_atoi64. char* __int64"
},
{
"answer_id": 303800,
"author": "Alan",
"author_id": 37843,
"author_profile": "https://Stackoverflow.com/users/37843",
"pm_score": 4,
"selected": false,
"text": "std::stringstream sstr(mystr);\n__int64 val;\nsstr >> val;\n"
},
{
"answer_id": 303836,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 3,
"selected": false,
"text": "long long ll = boost::lexical_cast<long long>(mystr)\n"
},
{
"answer_id": 33681846,
"author": "Keith Thomas",
"author_id": 1289504,
"author_profile": "https://Stackoverflow.com/users/1289504",
"pm_score": 2,
"selected": false,
"text": "long long ll = std::stoll(mystr);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24927/"
] |
303,760 | <p>The concept of a <a href="http://en.wikipedia.org/wiki/Coroutine" rel="noreferrer">coroutine</a> sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use cases for coroutines, where the coroutine implementation is more elegant, simpler or more efficient than other methods?</p>
| [
{
"answer_id": 303789,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 5,
"selected": true,
"text": "yield return yield return"
},
{
"answer_id": 304234,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 5,
"selected": false,
"text": "grep TODO *.c | wc -l\n grep wc grep wc"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
303,761 | <p>The Drupal API has <a href="http://api.drupal.org/api/function/drupal_get_path/6" rel="noreferrer"><code>drupal_get_path($type, $name)</code></a> which will give the path of any particular theme or module. What if I want the path of the current theme?</p>
| [
{
"answer_id": 303792,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": false,
"text": "global $theme;\n$path = drupal_get_path('theme', $theme);\n\n// there's also a $theme_path global\n\nglobal $theme_path;\n"
},
{
"answer_id": 306380,
"author": "FGM",
"author_id": 33991,
"author_profile": "https://Stackoverflow.com/users/33991",
"pm_score": 6,
"selected": true,
"text": "path_to_theme"
},
{
"answer_id": 47910811,
"author": "s6712",
"author_id": 906526,
"author_profile": "https://Stackoverflow.com/users/906526",
"pm_score": 0,
"selected": false,
"text": "function hook_preprocess_page(&$variables) {\n $variables['some_logo_file'] = \"/{$variables['theme']['path']}/images/logo.png\";\n}\n <img src=\"{{ logo_src }}\">\n"
},
{
"answer_id": 48498060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "global $base_url;\n$theme = \\Drupal::theme()->getActiveTheme();\n$image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';\n"
},
{
"answer_id": 58801183,
"author": "Arie",
"author_id": 4871012,
"author_profile": "https://Stackoverflow.com/users/4871012",
"pm_score": 3,
"selected": false,
"text": "$themeHandler = \\Drupal::service('theme_handler');\n$themePath = $themeHandler->getTheme($themeHandler->getDefault())->getPath();\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393/"
] |
303,763 | <p>I was wondering if anyone knew of a macro or keyboard shortcut or anything really that would automate Attaching to a Process within visual studio?</p>
| [
{
"answer_id": 303765,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 4,
"selected": true,
"text": "System.Diagnostics.Debugger.Break()"
},
{
"answer_id": 303774,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 3,
"selected": false,
"text": "CTRL + ALT + P W"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
303,767 | <p>I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.</p>
<p>I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.</p>
| [
{
"answer_id": 303778,
"author": "Joey V.",
"author_id": 34462,
"author_profile": "https://Stackoverflow.com/users/34462",
"pm_score": 3,
"selected": false,
"text": "$(window).height()\n\n$(window).width()\n"
},
{
"answer_id": 303791,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 9,
"selected": true,
"text": "const height = $(window).height();\nconst scrollTop = $(window).scrollTop();\n"
},
{
"answer_id": 3676975,
"author": "Aidamina",
"author_id": 227955,
"author_profile": "https://Stackoverflow.com/users/227955",
"pm_score": 5,
"selected": false,
"text": "$(window).height(); // returns height of browser viewport\n$(document).height(); // returns height of HTML document\n $(window).scrollTop() // return the number of pixels scrolled vertically\n"
},
{
"answer_id": 51133452,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "window.innerHeight\nwindow.scrollY\n"
},
{
"answer_id": 61815582,
"author": "dush88c",
"author_id": 5097602,
"author_profile": "https://Stackoverflow.com/users/5097602",
"pm_score": 1,
"selected": false,
"text": "$('html, body').animate({\n scrollTop: $(\"#div1\").offset().top\n }, 'slow');\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38666/"
] |
303,783 | <p>I'm building a fairly simple PHP script that will need to send some emails with attachments. I've found these 2 libraries to do this. </p>
<p>Does either one have significant advantages over the other? Or should I just pick one at random and be done with it?</p>
| [
{
"answer_id": 15074414,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 3,
"selected": false,
"text": "SMTPDebug = 2"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
303,809 | <p>I'm working on a simple application to start learning my way around WPF. I created a vector graphic in Microsoft Expression Design at 400px by 400px, mainly because I thought it would be easier to create it on a bigger canvas.</p>
<p>I've exported the image to a XAML file as a series of objects within a 400px square canvas. All of the child objects are positioned based on that 400px canvas.</p>
<p>I would like to place the image in my application window, but scaled down to maybe 100px by 100px, but I don't know how to do this. As a vector image, the concept of easy scaling seems simple, but I'm missing something. Click-n-drag resizes the canvas, but not the elements inside. Internet searches have been less than useful thus far.</p>
<p>I just want to place the image in my window... not in a button or anything special, and have easy control over its size. Do I need to copy all the XAML into my window's XAML? Can I reference the XAML file somehow instead? How can I make the elements of the image scale with the overall image? Any help would be appreciated.</p>
| [
{
"answer_id": 310491,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 0,
"selected": false,
"text": " dot = new Image();\n BitmapImage dotSource = new BitmapImage();\n dotSource.BeginInit();\n string dotImageFile = String.Format(\"path/to/my/{0}.png\", \"image\");\n dotSource.UriSource = new Uri(@dotImageFile, UriKind.Relative);\n dotSource.EndInit();\n dot.Stretch = Stretch.None;\n dot.Source = dotSource;\n dot.RenderTransformOrigin = new Point(0.5, 0.5);\n dotTransformGroup = new TransformGroup();\n dotScaleTransform = new ScaleTransform(scaleX, scaleX);\n dotSkewTransform = new SkewTransform();\n dotRotateTransform = new RotateTransform();\n dotTranslateTransform = new TranslateTransform();\n dotTransformGroup.Children.Add(dotScaleTransform);\n dotTransformGroup.Children.Add(dotSkewTransform);\n dotTransformGroup.Children.Add(dotRotateTransform);\n dotTransformGroup.Children.Add(dotTranslateTransform);\n dot.RenderTransform = dotTransformGroup;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641985/"
] |
303,827 | <p>How do you access a MySQL relation using RoR?</p>
| [
{
"answer_id": 304730,
"author": "allesklar",
"author_id": 19893,
"author_profile": "https://Stackoverflow.com/users/19893",
"pm_score": 3,
"selected": true,
"text": "has_many :addresses\n belongs_to :user\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39155/"
] |
303,829 | <p>In Ruby we have the 'bang' method <code>capitalize!</code> which has the strange behavior of returning a <code>nil</code> if no changes to the string were made.</p>
<p>That means I can't chain this commands with other since it effectively destroys the chain if it returns <code>nil</code>.</p>
<p>What im trying to do is something like this:</p>
<pre><code>fname = fullname[0...fullname.index(' ')].capitalize!
</code></pre>
<p>which extracts the first name from a string and should capitalize it as well. But if it is already capitalized the string stored in <code>fname</code> is <code>nil</code>.</p>
<p>Of courses I can add another statement but was wondering if there is a way to do this "without breaking the chain".</p>
| [
{
"answer_id": 303861,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "fname = fullname[0...fullname.index(' ')].capitalize\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587/"
] |
303,830 | <p>I have a body of text that I have to scan and each line contains at least 2 and sometimes four parts of information. The problem is that each line can be 1 out of 15-20 different actions.</p>
<p>in ruby the current code looks somewhat like this:</p>
<pre>
text.split("\n").each do |line| #around 20 times..
..............
expressions['actions'].each do |pat, reg| #around 20 times
.................
</pre>
<p>This is obviously 'THE PROBLEM'.
I did manage to make it faster (in C++ by a 50% margin) by combining all the regexen into one but that is still not the speed I require -- I need to parse thousands of these files FAST!</p>
<p>Right now I match them with regexes -- however this is intolerably slow. I started with ruby and hopped over to C++ in hopes that I'd get a speed boost and it just isn't happening.</p>
<p>I've casually read on PEGs and grammar based parsing but it looks somewhat difficult to implement. Is this the direction I should head or are there different routes?</p>
<p>basically I'm parsing poker hand histories and each line of the hand history usually contains 2-3 bits of information that I need to collect:
who the player was, how much money or what cards the action entailed.. etc..</p>
<p>Sample text that needs to be parsed:</p>
<pre>
buriedtens posts $5
The button is in seat #4
*** HOLE CARDS ***
Dealt to Mayhem 31337 [8s Ad]
Sherwin7 folds
OneMiKeee folds
syhg99 calls $5
buriedtens raises to $10
</pre>
<p>After I collect this information each action is turned into an xml node.</p>
<p>Right now my ruby implementation of this is much faster than my C++ one but that's prob. Just cause I have not written in c code for well over 4-5 years</p>
<p><strong>UPDATE:</strong>
I don't want to post all the code here but so far my hands/second look like the following:</p>
<pre>
588 hands/second -- boost::spirit in c++
60 hands/second -- 1 very long and complicated regex in c++ (all the regexen put together)
33 hands/second -- normal regex style in ruby
</pre>
<p>I'm currently testing antlr to see if we can go any further but as of right now I'm very very happy with spirit's results.</p>
<p>Related question: <a href="https://stackoverflow.com/questions/192957/efficiently-querying-one-string-against-multiple-regexes">Efficiently querying one string against multiple regexes.</a></p>
| [
{
"answer_id": 304532,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 0,
"selected": false,
"text": "regex1|regex2|regex3|...|regex15\n"
},
{
"answer_id": 306688,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "perldoc perlfaq6 while (<>) {\n chomp;\n PARSER: {\n m/ \\G( \\d+\\b )/gcx && do { print \"number: $1\\n\"; redo; };\n m/ \\G( \\w+ )/gcx && do { print \"word: $1\\n\"; redo; };\n m/ \\G( \\s+ )/gcx && do { print \"space: $1\\n\"; redo; };\n m/ \\G( [^\\w\\d]+ )/gcx && do { print \"other: $1\\n\"; redo; };\n }\n}\n PARSER m/ \\G( \\d+\\b )/gcx c pos()"
},
{
"answer_id": 310633,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 0,
"selected": false,
"text": "HAND_LINE: for ($Line)\n { /^\\*\\*\\* ([A-Z ]+)/ and do \n { # parse the string that is captured in $1\n last HAND_LINE; };\n /^Dealt to (.+) \\[(.. ..)\\]$/ and do\n { # $1 contains the name, $2 contains the cards as string\n last HAND_LINE; };\n /(.+) folds$/ and do\n { # you get the drift\n last HAND_LINE; }; };\n \"*** NEXT PHASE ***\" Tie::File"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39110/"
] |
303,838 | <p>I am in the process of setting up CruiseControl.NET. The problem I am having is that I am running CC as a console application and when my build completes successfully and executes (using exec) it launches it within the CruiseControl DOS prompt. I am just using simple batch files to launch my app but having it run within the same prompt as CC is causing CC to think the build continues as long as my app runs.</p>
<p>Are there command line parameters to <code>cmd.exe</code> that will spawn another separate prompt window?</p>
| [
{
"answer_id": 303844,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 9,
"selected": true,
"text": "start cmd.exe\n"
},
{
"answer_id": 303869,
"author": "BlackMael",
"author_id": 19377,
"author_profile": "https://Stackoverflow.com/users/19377",
"pm_score": 5,
"selected": false,
"text": "start cmd.exe \n start file.cmd \n"
},
{
"answer_id": 4177011,
"author": "bajie",
"author_id": 459555,
"author_profile": "https://Stackoverflow.com/users/459555",
"pm_score": 2,
"selected": false,
"text": "@cmd\n @cmd /k \"command1&command2\"\n"
},
{
"answer_id": 14679992,
"author": "kite",
"author_id": 423356,
"author_profile": "https://Stackoverflow.com/users/423356",
"pm_score": 0,
"selected": false,
"text": "schtasks.exe /create /F /SC once /ST 08:50 /TN TaskName /TR \"c:/path/to/batchFileName.bat\"\n"
},
{
"answer_id": 15888719,
"author": "Michael",
"author_id": 2259271,
"author_profile": "https://Stackoverflow.com/users/2259271",
"pm_score": 2,
"selected": false,
"text": "START \"notepad.exe\"\necho Will launch the notepad.exe application\nPAUSE\n @echo\nTITLE example.bat\nPAUSE\ntaskkill/IM cmd.exe\n"
},
{
"answer_id": 19773173,
"author": "xsukax",
"author_id": 2953437,
"author_profile": "https://Stackoverflow.com/users/2953437",
"pm_score": 6,
"selected": false,
"text": "start cmd.exe @cmd /k \"Command\"\n"
},
{
"answer_id": 31241638,
"author": "Esterlinkof",
"author_id": 2056746,
"author_profile": "https://Stackoverflow.com/users/2056746",
"pm_score": 6,
"selected": false,
"text": "start start\n cmd"
},
{
"answer_id": 52983682,
"author": "Jagadeesh HN",
"author_id": 10543876,
"author_profile": "https://Stackoverflow.com/users/10543876",
"pm_score": 3,
"selected": false,
"text": "start start cmd start cmd.exe"
},
{
"answer_id": 67597894,
"author": "Irfan wani",
"author_id": 13789135,
"author_profile": "https://Stackoverflow.com/users/13789135",
"pm_score": 1,
"selected": false,
"text": "start start cmd.exe start \"Command Prompt\"\n"
},
{
"answer_id": 71305297,
"author": "Hà Mã Tím",
"author_id": 5591888,
"author_profile": "https://Stackoverflow.com/users/5591888",
"pm_score": 2,
"selected": false,
"text": "start alices.bat\nstart bobs.bat\n"
},
{
"answer_id": 72697359,
"author": "Eng_Farghly",
"author_id": 5661396,
"author_profile": "https://Stackoverflow.com/users/5661396",
"pm_score": 0,
"selected": false,
"text": "cmd with new session start"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25946/"
] |
303,841 | <p>I am getting this warning:</p>
<pre><code>Use of uninitialized value in eval \"string\" at myscript.pl line 57.
</code></pre>
<p>When I run this code:</p>
<pre><code>eval;
{
`$client -f $confFile -i $inputFile -o $outputFile`;
};
if( $@ )
{
# error handling here ...
}
</code></pre>
<p>What is causing the error?</p>
<p>How can I fix the underlying cause? (Or otherwise suppress the warning?)</p>
| [
{
"answer_id": 303855,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 4,
"selected": true,
"text": "eval"
},
{
"answer_id": 303990,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "$@ $? system($client, '-f', $confFile, '-i', $inputFile, '-o', $outputFile) and do {\n #error handling here...\n};\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39153/"
] |
303,842 | <p>I'm wondering if there is any way to create a User Account on a Windows XP machine that can be done through scripting from an ActiveX control on a webpage. Specifically, I'd like to know if there's any way to deploy an ActiveX control with computers (that I preconfigure and ship) that will allow use of my webpage from that computer to detect that the ActiveX control is present, and allow for automated creation of local (Windows XP) user accounts on the computer. Essentially, consider this to be a question of preinstalling an ActiveX control (if necessary) and providing a link on the desktop; the user receives the machine and logs on (with admin rights) and goes to a web site, where my server determine what the appropriate user accounts are, sends them back as HTML, and the ActiveX control creates the user accounts I specify.</p>
<p>This sort of thing seems like it should be possible, but at the same time, there are obvious security flaws that are potentially involved. Access to these machines will be very limited, so the security issues are less of a concern.</p>
<p>Does anyone know if this is possible? Do any of the built in WMI components do anything like this? Is this even allowed by the security model of XP? Or is this just opening up a huge security hole that should be avoided entirely?</p>
| [
{
"answer_id": 303855,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 4,
"selected": true,
"text": "eval"
},
{
"answer_id": 303990,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "$@ $? system($client, '-f', $confFile, '-i', $inputFile, '-o', $outputFile) and do {\n #error handling here...\n};\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28053/"
] |
303,853 | <p>I am considering using Maven for a Java open source project I manage.</p>
<p>In the past, however, Maven has not always had the best reputation. What are your impressions of Maven, at this time? </p>
| [
{
"answer_id": 3361860,
"author": "Jan",
"author_id": 357556,
"author_profile": "https://Stackoverflow.com/users/357556",
"pm_score": 2,
"selected": false,
"text": "pom.xml"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32174/"
] |
303,877 | <p>TeX/LaTeX is great, I use it in many ways. Some of its advantages are:</p>
<ul>
<li>it uses text files, this way the input-files can be diffed and many tools exist to work with text</li>
<li>it is very flexible</li>
<li>it has a stable layout: if I change something at the start of the document, it doesn't affect other things at the end of the document</li>
<li>it has many extensions to reach different goals (a successor would start without extensions, but would have a good extension-system)</li>
<li>you can use standard build control tools to support complicated documents (thanks dmckee)</li>
<li>you can encapsulate solutions and copy&paste them to new documents or send them to others to learn from (thanks dmckee)</li>
</ul>
<p>But on the other hand some little things are not so good:</p>
<ul>
<li>it is hard to learn at the beginning</li>
<li>it is complicated to control position of images</li>
<li>a few things are a little counter-intuitive</li>
<li>sometimes you have to type too much (begin{itemize} ... \end{itemize})</li>
</ul>
<p>So, does there exist a successor/alternative to LaTeX or at least is some hot candidate for an alternative in development. A real successor/good alternative would keep the advantages and fix the disadvantages, or at least some of them.</p>
| [
{
"answer_id": 304039,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 2,
"selected": false,
"text": " .pl 10.0i\n .po 0\n .ll 7.2i\n .lt 7.2i\n .nr LL 7.2i\n .nr LT 7.2i\n .ds RF FORMFEED[Page %]\n .ds LH Internet Draft\n .\\\" --> Header/footers: Set short title, author(s), and dates:\n .ds CH 2-nroff.template \\\" <Short title>\n .ds LF Postel, Braden \\\" <Authors>\n .ds RH October 25, 2006 \\\" <Submission date>\n .ds CF Expires April 2007 \\\" <Expiration date>\n .hy 0\n .ad l\n .nf\n .\\\" 5678901234567 check 72 column width 12345678901234567890123456789012\n Internet Draft J. Postel\n <draft-rfc-editor-nroff-template-00.txt> RFC Editor\n Category: Informational USC ISI\n Expires April 2007 October 25, 2006\n\n .ce\n Nroff Template for Internet Drafts and RFCs\n .ce\n <draft-rfc-editor-nroff.template-00.txt>\n\n .in 3 \\\" Basic indent for text is 3 spaces\n .ti 0 \\\" \"Temporary indent\" for next line: 0 spaces\n Status of this Memo\n\n Distribution of this memo is unlimited.\n\n By submitting this Internet-Draft, each author represents that any\n applicable patent or other IPR claims of which he or she is aware\n have been or will be disclosed, and any of which he or she becomes\n aware will be disclosed, in accordance with Section 6 of BCP 79.\n\n Internet-Drafts are working documents of the Internet Engineering Task\n Force (IETF), its areas, and its working groups. Note that other groups\n may also distribute working documents as Internet-Drafts.\n\n Internet-Drafts are draft documents valid for a maximum of six months\n and may be updated, replaced, or obsoleted by other documents at any\n"
},
{
"answer_id": 304326,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 2,
"selected": false,
"text": "\\begin{whatever}...\\end{whatever}\n"
},
{
"answer_id": 11706706,
"author": "elias",
"author_id": 1560498,
"author_profile": "https://Stackoverflow.com/users/1560498",
"pm_score": 3,
"selected": false,
"text": "\\includegraphics"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/303877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
303,911 | <p>There is a similar question <a href="https://stackoverflow.com/questions/203495/testing-rest-webservices">here</a> but it only covers some of the issues below.</p>
<p>We have a client who requires web services using REST.</p>
<p>We have tons of experience using SOAP and over time have gathered together a really good set of tools for SOAP development and testing e.g.</p>
<ul>
<li>soapUI </li>
<li>Eclipse plugins</li>
<li>wsdl2java</li>
<li>WSStudio</li>
</ul>
<p>By "tools" I mean a product "out of the box" that we can start using. I'm not talking about cutting code to "roll our own" using Ajax or whatever.</p>
<p>The tool set for REST doesn't seem to be nearly as mature?</p>
<ul>
<li><p>What tools are out there (we use C# and Java mainly) ?</p></li>
<li><p>Do the tools handle GET, POST, PUT, and DELETE?</p></li>
<li><p>Is there a decent Eclipse plugin?</p></li>
<li><p>Is there a decent client testing application like WSStudio where you point the tool to the WSDL and it generates a proxy on the fly with the appropriate methods and inputs and you simple type the data in?</p></li>
<li><p>Are there any good package monitoring tools that allow you to look at the data? (I'm not thinking about sniffers like Wireshark here but rather things like soapUI that allow you to see the request / response) ?</p></li>
</ul>
| [
{
"answer_id": 21280384,
"author": "Johan",
"author_id": 398441,
"author_profile": "https://Stackoverflow.com/users/398441",
"pm_score": 0,
"selected": false,
"text": "{ \"greeting\" : { \"firstName\" : <first_name>, \"lastName\" : <last_name> } }\n given().\n param(\"first_name\", \"John\").\n param(\"last_name\", \"Doe\").\nwhen().\n get(\"/greeting\").\nthen().\n statusCode(200).\n body(\"greeting.firstName\", equalTo(\"John\").\n body(\"greeting.lastName\", equalTo(\"Doe\");\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
] |
303,913 | <pre><code>File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
int [] tall = new int [100];
String s =in.readLine();
while(s!=null)
{
int i = 0;
tall[i] = Integer.parseInt(s); //this is line 19
System.out.println(tall[i]);
s = in.readLine();
}
in.close();
</code></pre>
<p>I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:</p>
<pre><code>Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinarySok.main(BinarySok.java:19)
</code></pre>
<p>Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.</p>
| [
{
"answer_id": 303921,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "try {\n tall[i++] = Integer.parseInt(s);\n}\ncatch (NumberFormatException ex) {\n continue;\n}\n if (s.length() == 0) \n continue;\n i while for"
},
{
"answer_id": 303932,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "String s = in.readLine();\nint i = 0;\n\nwhile (s != null) {\n // Skip empty lines.\n s = s.trim();\n if (s.length() == 0) {\n continue;\n }\n\n tall[i] = Integer.parseInt(s); // This is line 19.\n System.out.println(tall[i]);\n s = in.readLine();\n i++;\n}\n\nin.close();\n"
},
{
"answer_id": 304061,
"author": "Julien Grenier",
"author_id": 23051,
"author_profile": "https://Stackoverflow.com/users/23051",
"pm_score": 5,
"selected": false,
"text": "Scanner scanner = new Scanner(new File(\"tall.txt\"));\nint [] tall = new int [100];\nint i = 0;\nwhile(scanner.hasNextInt()){\n tall[i++] = scanner.nextInt();\n}\n"
},
{
"answer_id": 795139,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 2,
"selected": false,
"text": "File file = new File(\"Tall.txt\");\nbyte[] bytes = new byte[(int) file.length()];\nFileInputStream fis = new FileInputStream(file);\nfis.read(bytes);\nfis.close();\nString[] valueStr = new String(bytes).trim().split(\"\\\\s+\");\nint[] tall = new int[valueStr.length];\nfor (int i = 0; i < valueStr.length; i++) \n tall[i] = Integer.parseInt(valueStr[i]);\nSystem.out.println(Arrays.asList(tall));\n"
},
{
"answer_id": 46538521,
"author": "Ban",
"author_id": 3929003,
"author_profile": "https://Stackoverflow.com/users/3929003",
"pm_score": 0,
"selected": false,
"text": "File file = new File(\"E:/Responsibility.txt\"); \n Scanner scanner = new Scanner(file);\n List<Integer> integers = new ArrayList<>();\n while (scanner.hasNext()) {\n if (scanner.hasNextInt()) {\n integers.add(scanner.nextInt());\n } else {\n scanner.next();\n }\n }\n System.out.println(integers);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37161/"
] |
303,916 | <p>I'm trying to wrap my head around the best way to use IoC within my application for dependency injection, however I have a little issue.</p>
<p>I am using a loose implementation of the MVP pattern with a WPF app. Essentially, a presenter class is instantiated, and a view and task (e.g. IEmployeeView and IEmployeeTask for EmployeePresenter) are injected into the presenter.</p>
<p>I would like to use an IoC container (I'm trying out Unity, though I guess this would also happen with others such as ninject or Structure Map) instead of manually injecting these instances, however if the presenter is created (or resolved from an IoC container) on an async delegate call, or an event thread (e.g. not STA threaded) then creating a new instance of a WPF window throws the following exception:</p>
<blockquote>
<p>The current build operation (build key
Build Key[<em>namespace</em>.Window1, null])
failed: The calling thread must be
STA, because many UI components
require this.</p>
</blockquote>
<p>Now, I know that new window instances etc need to be STA, however is it possible to use an IoC Container to do the dependency injection even when the UI must be created on an STA thread?</p>
<p>From looking at this problem it would seem that the class/type being resolved is instantiated at the resolve time, not when its registered...</p>
| [
{
"answer_id": 303921,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "try {\n tall[i++] = Integer.parseInt(s);\n}\ncatch (NumberFormatException ex) {\n continue;\n}\n if (s.length() == 0) \n continue;\n i while for"
},
{
"answer_id": 303932,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "String s = in.readLine();\nint i = 0;\n\nwhile (s != null) {\n // Skip empty lines.\n s = s.trim();\n if (s.length() == 0) {\n continue;\n }\n\n tall[i] = Integer.parseInt(s); // This is line 19.\n System.out.println(tall[i]);\n s = in.readLine();\n i++;\n}\n\nin.close();\n"
},
{
"answer_id": 304061,
"author": "Julien Grenier",
"author_id": 23051,
"author_profile": "https://Stackoverflow.com/users/23051",
"pm_score": 5,
"selected": false,
"text": "Scanner scanner = new Scanner(new File(\"tall.txt\"));\nint [] tall = new int [100];\nint i = 0;\nwhile(scanner.hasNextInt()){\n tall[i++] = scanner.nextInt();\n}\n"
},
{
"answer_id": 795139,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 2,
"selected": false,
"text": "File file = new File(\"Tall.txt\");\nbyte[] bytes = new byte[(int) file.length()];\nFileInputStream fis = new FileInputStream(file);\nfis.read(bytes);\nfis.close();\nString[] valueStr = new String(bytes).trim().split(\"\\\\s+\");\nint[] tall = new int[valueStr.length];\nfor (int i = 0; i < valueStr.length; i++) \n tall[i] = Integer.parseInt(valueStr[i]);\nSystem.out.println(Arrays.asList(tall));\n"
},
{
"answer_id": 46538521,
"author": "Ban",
"author_id": 3929003,
"author_profile": "https://Stackoverflow.com/users/3929003",
"pm_score": 0,
"selected": false,
"text": "File file = new File(\"E:/Responsibility.txt\"); \n Scanner scanner = new Scanner(file);\n List<Integer> integers = new ArrayList<>();\n while (scanner.hasNext()) {\n if (scanner.hasNextInt()) {\n integers.add(scanner.nextInt());\n } else {\n scanner.next();\n }\n }\n System.out.println(integers);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18434/"
] |
303,939 | <p>I'm wondering why styling an element within a specific class, like this:</p>
<pre><code>.reddish H1 { color: red }
</code></pre>
<p>is shown as an example of correct syntax in the CSS1 specification under Contextual selectors:</p>
<p><a href="http://www.w3.org/TR/2008/REC-CSS1-20080411/#class-as-selector" rel="nofollow noreferrer">Cascading Style Sheets, level 1</a></p>
<p>but it's not shown as an example in the CSS2 spec:</p>
<p><a href="http://www.w3.org/TR/2008/REC-CSS2-20080411/selector.html" rel="nofollow noreferrer">Cascading Style Sheets, Level 2</a></p>
<p>At least I can't find an example of it. Has the syntax rules for this changed in CSS2, or is it simply inferred as correct syntax?</p>
| [
{
"answer_id": 304122,
"author": "philnash",
"author_id": 28376,
"author_profile": "https://Stackoverflow.com/users/28376",
"pm_score": 3,
"selected": true,
"text": ".reddish h1 h1 .reddish h1 { color: blue; }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
303,955 | <p>I have a generic function which gets a interface as a type, now in one condition I have to create a new class depending on the interface. I have been thinking about it and a way to solve it would be to use an IoC but I was hoping there would be an other way because an IoC seems a bit like an overkill. </p>
<p>below is an attempt using the visitor pattern:</p>
<pre><code>public class RepositoryManager<T> : IRepositoryManager<T> where T : class, new()
{
public T GetOrCreate(string id)
{
T item = (T)CreateNew(new T(), id);
return item;
}
}
</code></pre>
<p>If instead of an interface I was getting an object then I could use the visitor pattern to figure out what class to instantiate but I can't seem to figure this out depending on the interface provided.</p>
<p>An other idea I had was if I can make the where declaration like an or?</p>
<pre><code>public class RepositoryManager<T> : IRepositoryManager<T> where T : class, Iabc or Ixyz, new()
</code></pre>
<p>I hope the question is clear :)</p>
<p>-Mark</p>
<hr>
<p>Thanks for the reply's.</p>
<p>The problem is that the method can have many different interfaces assigned to it for example:</p>
<p>RepositoryManager class:</p>
<pre><code>private static IMedicament CreateNew(IMedicament emptyType, string id)
{
return new Medicament { Id = id };
}
private static IRefund CreateNew(IRefund emptyType, string id)
{
return new Refund { Id = id };
}
RepositoryManager<Iabc> abcRepository = new RepositoryManager<Iabc>();
RepositoryManager<Ixyz> xyzRepository = new RepositoryManager<Ixyz>();
Iabc abc = abcRepository.GetOrCreate("12345");
Ixyz xyz = xyzRepository.GetOrCreate("12345");
</code></pre>
<p>so using <code>T item = (T)CreateNew(new T(), id);</code> won't work because I have to tell it that T can either be of type Iabc or Ixyz but when I do that I get the following error:</p>
<p>The call is ambiguous between the following methods or properties: <code>RepositoryManager<T>.CreateNew(IMedicament, string)</code> and <code>RepositoryManager<T>.CreateNew(IRefund, string)</code></p>
<p>It would be nice if I get this working besides just copying the code several times.</p>
| [
{
"answer_id": 304155,
"author": "Odd",
"author_id": 11908,
"author_profile": "https://Stackoverflow.com/users/11908",
"pm_score": 0,
"selected": false,
"text": "public void Method<T>()\n{\n Type type = typeof(T);\n\n T newObject = (T)type.GetConstructor(new System.Type[] { }).Invoke(new object[] { });\n}\n"
},
{
"answer_id": 304165,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "public class RepositoryManager<T> : IRepositoryManager<T> where T : Ixyz, new()\n{\n public T GetOrCreate(string id)\n {\n T item = (T)CreateNew(new T(), id);\n return item;\n }\n}\n public class RepositoryManager<T> : IRepositoryManager<T> where T : Ixyz\n{\n private Func<T> _tConstructor;\n\n public RepositoryManager(Func<T> tConstructor)\n {\n this._tConstructor = tConstructor;\n }\n\n public T GetOrCreate(string id, )\n {\n T item = (T)CreateNew(this._tConstructor(), id);\n return item;\n }\n}\n"
},
{
"answer_id": 304215,
"author": "Rohan West",
"author_id": 38686,
"author_profile": "https://Stackoverflow.com/users/38686",
"pm_score": 2,
"selected": false,
"text": "public class Repository\n{\n public T Create<T>(string id) where T : class\n {\n return Activator.CreateInstance(typeof(T), new[] { id }) as T;\n }\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305008/"
] |
303,956 | <p>Is it possible using <a href="https://jquery.com/" rel="noreferrer">jQuery</a> to select all <code><a></code> links which href ends with "ABC"?</p>
<p>For example, if I want to find this link <code><a href="http://server/page.aspx?id=ABC"></code></p>
| [
{
"answer_id": 303961,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 12,
"selected": true,
"text": " $('a[href$=\"ABC\"]')...\n = is exactly equal\n!= is not equal\n^= is starts with\n$= is ends with\n*= is contains\n~= is contains word\n|= is starts with prefix (i.e., |= \"prefix\" matches \"prefix-...\")\n"
},
{
"answer_id": 3113845,
"author": "Ash",
"author_id": 375704,
"author_profile": "https://Stackoverflow.com/users/375704",
"pm_score": 5,
"selected": false,
"text": "$('a[href$=\"ABC\"]:first').attr('title');\n"
},
{
"answer_id": 9495740,
"author": "Sumit",
"author_id": 1239745,
"author_profile": "https://Stackoverflow.com/users/1239745",
"pm_score": 4,
"selected": false,
"text": "$(\"a[href*='id=ABC']\").addClass('active_jquery_menu');\n"
},
{
"answer_id": 12515289,
"author": "Ganesh Anugu",
"author_id": 1686355,
"author_profile": "https://Stackoverflow.com/users/1686355",
"pm_score": 3,
"selected": false,
"text": "$(\"a[href*=ABC]\").addClass('selected');\n"
},
{
"answer_id": 56233705,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": false,
"text": "querySelectorAll const anchors = document.querySelectorAll('a[href$=\"ABC\"]');\n const anchor = document.querySelector('a[href$=\"ABC\"]');\n a[href$=ABC]\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36036/"
] |
303,970 | <p>I am having trouble constructing a single XPath statement to return two different sets of attributes. </p>
<p>For example take the following XML document:</p>
<pre><code><root>
<line name="one" alpha="a1" beta="b1"/>
<line name="two" alpha="a2" beta="b2"/>
<line name="three" alpha="a3" beta="b3"/>
</root>
</code></pre>
<p>If I use the following XPath statement:</p>
<pre><code>//@alpha
</code></pre>
<p>It yields the following attribute set:</p>
<pre><code>alpha="a1"
alpha="a2"
alpha="a3"
</code></pre>
<p>What statement do I use to yield the following attribute set:</p>
<pre><code>alpha="a1"
alpha="a2"
alpha="a3"
beta="b1"
beta="b2"
beta="b3"
</code></pre>
| [
{
"answer_id": 303999,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 5,
"selected": true,
"text": "| //@alpha | //@beta\n"
},
{
"answer_id": 304003,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 4,
"selected": false,
"text": "//@*[name()='alpha' or name()='beta']\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3810/"
] |
303,987 | <p>Is there any way in Linq to check to see if a record of a parent exists in its children? </p>
<p>I have a table that has a foreign key relationship with 12 other tables. All I want to do is see if any records in those child tables depend on the parent, so I can delete it without causing errors with FK constraints. </p>
<p>Thanks guys.</p>
<p>I ended up just making an extension class that checked each one... Time consuming but got the job done... I would still like opinions if possible</p>
| [
{
"answer_id": 304074,
"author": "matt_dev",
"author_id": 39086,
"author_profile": "https://Stackoverflow.com/users/39086",
"pm_score": 0,
"selected": false,
"text": " ParentChildrenDataContext context = new ParentChildrenDataContext();\n\n var child1Ids = from c in context.ChildType1s\n select c.ParentId;\n\n var child2Ids = from c in context.ChildType2s\n select c.ParentId;\n\n\n var allChildren = child1Ids.Union(child2Ids);\n\n var myParents = from p in context.Parents\n where allChildren.Contains<int?>(p.ParentId)\n select p;\n\n return myParents.Count();\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4144/"
] |
303,994 | <p>Is it possible for me to turn on audit logging on my mysql database?</p>
<p>I basically want to monitor all queries for an hour, and dump the log to a file.</p>
| [
{
"answer_id": 304008,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 8,
"selected": true,
"text": "mysqld --log=log_file_name\n my.cnf log = log_file_name\n --log-slow-queries --log long_query_time"
},
{
"answer_id": 14403905,
"author": "Alexandre Marcondes",
"author_id": 412426,
"author_profile": "https://Stackoverflow.com/users/412426",
"pm_score": 8,
"selected": false,
"text": "mysql CREATE TABLE `slow_log` (\n `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP \n ON UPDATE CURRENT_TIMESTAMP,\n `user_host` mediumtext NOT NULL,\n `query_time` time NOT NULL,\n `lock_time` time NOT NULL,\n `rows_sent` int(11) NOT NULL,\n `rows_examined` int(11) NOT NULL,\n `db` varchar(512) NOT NULL,\n `last_insert_id` int(11) NOT NULL,\n `insert_id` int(11) NOT NULL,\n `server_id` int(10) unsigned NOT NULL,\n `sql_text` mediumtext NOT NULL,\n `thread_id` bigint(21) unsigned NOT NULL\n ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log'\n CREATE TABLE `general_log` (\n `event_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP\n ON UPDATE CURRENT_TIMESTAMP,\n `user_host` mediumtext NOT NULL,\n `thread_id` bigint(21) unsigned NOT NULL,\n `server_id` int(10) unsigned NOT NULL,\n `command_type` varchar(64) NOT NULL,\n `argument` mediumtext NOT NULL\n ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='General log'\n SET global general_log = 1;\nSET global log_output = 'table';\n select * from mysql.general_log\n SET global general_log = 0;\n"
},
{
"answer_id": 20485975,
"author": "Ram",
"author_id": 2799178,
"author_profile": "https://Stackoverflow.com/users/2799178",
"pm_score": 8,
"selected": false,
"text": "SET global log_output = 'FILE';\nSET global general_log_file='/Applications/MAMP/logs/mysql_general.log';\nSET global general_log = 1;\n SET global general_log = 0;\n"
},
{
"answer_id": 25080306,
"author": "alexeydemin",
"author_id": 831549,
"author_profile": "https://Stackoverflow.com/users/831549",
"pm_score": 7,
"selected": false,
"text": "[mysqld]\ngeneral_log = on\ngeneral_log_file=/usr/log/general.log\n"
},
{
"answer_id": 40661981,
"author": "Nanhe Kumar",
"author_id": 1087040,
"author_profile": "https://Stackoverflow.com/users/1087040",
"pm_score": 4,
"selected": false,
"text": "mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';\nmysql> SET GLOBAL general_log = 'ON';\n"
},
{
"answer_id": 43252707,
"author": "Vipin Yadav",
"author_id": 4759275,
"author_profile": "https://Stackoverflow.com/users/4759275",
"pm_score": 6,
"selected": false,
"text": "mysql> SET GLOBAL general_log = 'ON';\nmysql> SET GLOBAL log_output = 'table';\n SELECT * FROM mysql.general_log\n TRUNCATE table mysql.general_log;\n"
},
{
"answer_id": 53710961,
"author": "Raphvanns",
"author_id": 5009287,
"author_profile": "https://Stackoverflow.com/users/5009287",
"pm_score": 3,
"selected": false,
"text": "$ uname -a\nDarwin Raphaels-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 x86_64\n\n$ mysql --version\n/usr/local/mysql/bin/mysql Ver 14.14 Distrib 5.6.23, for osx10.8 (x86_64) using EditLine wrapper\n /var/log/... sudo vi ./usr/local/mysql-5.6.23-osx10.8-x86_64/my.cnf\n\n[mysqld]\ngeneral_log = on\ngeneral_log_file=/var/log/mysql/mysqld_general.log\n $ sudo tail -f /var/log/mysql/mysqld_general.log\n181210 9:41:04 21 Connect root@localhost on employees\n 21 Query /* mysql-connector-java-5.1.47 ( Revision: fe1903b1ecb4a96a917f7ed3190d80c049b1de29 ) */SELECT @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@collation_server AS collation_server, @@collation_connection AS collation_connection, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS transaction_isolation, @@wait_timeout AS wait_timeout\n 21 Query SET NAMES latin1\n 21 Query SET character_set_results = NULL\n 21 Query SET autocommit=1\n 21 Query SELECT USER()\n 21 Query SELECT USER()\n181210 9:41:10 21 Query show tables\n181210 9:41:25 21 Query select count(*) from current_dept_emp\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/303994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
304,010 | <p>I have a multi-threaded application that is hanging on a call to _dl_sysinfo_int80(). According to gdb, all threads are stuck in this call.</p>
<p>The top of the stack trace looks like:</p>
<pre><code>#0 0x002727a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x004f23de in __lll_mutex_lock_wait () from /lib/tls/libpthread.so.0
#2 0x004ef00b in _L_mutex_lock_35 () from /lib/tls/libpthread.so.0
#3 0x092828ac in construction vtable for std::ostream-in-std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> > ()
</code></pre>
<p>Any idea what could be causing this?</p>
| [
{
"answer_id": 305277,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "_dl_sysinfo_int80 int $0x80 __lll_mutex_lock_wait"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449/"
] |
304,011 | <p>What's the easiest way to truncate a C++ <code>float</code> variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?</p>
| [
{
"answer_id": 304013,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": "char sz[64];\ndouble lf = 0.600000002;\nsprintf(sz, \"%.4lf\\n\", lf); //sz contains 0.6000\n\ndouble lf2 = atof(sz);\n\n//lf == 0.600000002;\n//lf2 == 0.6000\n\nprintf(\"%.4lf\", lf2); //print 0.6000\n double lf = 0.600000002;\nint iSigned = lf > 0? 1: -1;\nunsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate\nlf = (((double)uiTemp)/pow(10,4) * iSigned);\n"
},
{
"answer_id": 312020,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "roundf(myfloat * powf(10, numDigits)) / powf(10, numDigits);\n roundf(0.6000002 * 1000) / 1000\n// And thus:\nroundf(600.0002) / 1000\n600 / 1000\n0.6\n"
},
{
"answer_id": 2215915,
"author": "JBOI",
"author_id": 268009,
"author_profile": "https://Stackoverflow.com/users/268009",
"pm_score": 2,
"selected": false,
"text": "floor(0.6000002*10000)/10000\n"
},
{
"answer_id": 15414998,
"author": "David Doria",
"author_id": 284529,
"author_profile": "https://Stackoverflow.com/users/284529",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <cmath>\n\nstatic void Truncate(double& d, unsigned int numberOfDecimalsToKeep);\n\nint main(int, char*[])\n{\n\n double a = 1.23456789;\n unsigned int numDigits = 3;\n\n std::cout << a << std::endl;\n\n Truncate(a,3);\n\n std::cout << a << std::endl;\n\n return 0;\n}\n\nvoid Truncate(double& d, unsigned int numberOfDecimalsToKeep)\n{\n d = roundf(d * powf(10, numberOfDecimalsToKeep)) / powf(10, numberOfDecimalsToKeep);\n}\n"
},
{
"answer_id": 34908243,
"author": "Rubarb",
"author_id": 2957447,
"author_profile": "https://Stackoverflow.com/users/2957447",
"pm_score": 1,
"selected": false,
"text": "trunc(valueToTrunc*10000)/10000\n value = (double)((int)(valueToTrunc*10000))/(double)10000\n"
},
{
"answer_id": 43687257,
"author": "chema989",
"author_id": 6410484,
"author_profile": "https://Stackoverflow.com/users/6410484",
"pm_score": 1,
"selected": false,
"text": "std::round <cmath> auto trunc_value = std::round(value_to_trunc * 10000) / 10000;\n"
},
{
"answer_id": 65125428,
"author": "parsa poorzahedy",
"author_id": 14715703,
"author_profile": "https://Stackoverflow.com/users/14715703",
"pm_score": 0,
"selected": false,
"text": "int n = 1.12378;\ncout << fixed << setprecision(4) << n;\n 1.1238 1.1237"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
304,041 | <p>I've been working with Vector2's and XNA, and I've come to find that calling the Normalize() member function on a Zero Vector normalizes it to a vector of {NaN, NaN}. This is all well and good, but in my case I'd prefer it instead just leave them as Zero Vectors.</p>
<p>Adding this code to my project enabled a cute extension method:</p>
<pre><code>using ExtensionMethods;
namespace ExtensionMethods
{
public static class MyExtensions
{
public static Vector2 NormalizeOrZero(this Vector2 v2)
{
if (v2 != Vector2.Zero)
v2.Normalize();
return v2;
}
}
}
</code></pre>
<p>Unfortunately, this method <em>returns</em> the normalized vector, rather than simply normalizing the vector which I use to invoke this extension method. I'd like to to instead behave as <em>vector2Instance</em>.Normalize() does.</p>
<p>Aside from making this void, how do I adjust this so that the 'v2' is modified?
(Essentially, I need access to the 'this' object, or I need 'v2' to be passed by reference.)</p>
<p>Edit:</p>
<p>And yes, I have tried this:</p>
<pre><code> public static void NormalizeOrZero(this Vector2 v2)
{
if (v2 != Vector2.Zero)
v2.Normalize();
}
</code></pre>
<p>Doesn't work, v2 is just a variable in the scope of NormalizeOrZero.</p>
| [
{
"answer_id": 304077,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "Vector2 v2 = new Vector2()\nv2 = v2.NormalizeOrZero();\n"
},
{
"answer_id": 304098,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 0,
"selected": false,
"text": "ref this"
},
{
"answer_id": 304105,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 1,
"selected": false,
"text": "public static void NormalizeOrZero(this Vector2 ignore, ref Vector2 v2)\n{\n if (v2 != Vector2.Zero)\n v2.Normalize();\n}\n v2.NormalizeOrZero(ref v2);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388/"
] |
304,043 | <p>I'm trying to generate pairwise combinations of rows on based on their ids. SQLite version is 3.5.9. The table contents are the following:</p>
<pre><code>id|name|val
1|A|20
2|B|21
3|C|22
</code></pre>
<p>with table schema being:</p>
<pre><code>CREATE TABLE mytable (
id INTEGER NOT NULL,
name VARCHAR,
val INTEGER,
PRIMARY KEY (id)
);
</code></pre>
<p>Then there's the self-join on ids:</p>
<pre><code>sqlite> select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id > t1.id;
id|id
2|2
2|3
3|3
</code></pre>
<p>Which is clearly not what I want. Now, changing the order of t2 and t1 produces the correct result:</p>
<pre><code>sqlite> select t1.id, t2.id from mytable as t2, mytable as t1 where t2.id > t1.id;
id|id
1|2
1|3
2|3
</code></pre>
<p>Now, for another experiment, I tried combining on a numeric column other than row id. That, on the other hand, gives correct result in both cases.</p>
<p>I am hoping someone can give an insight into what's going on here. As far as I understand, its either a bug in SQLite or some delicate aspect of SQL I don't know.</p>
<p>Thanks,</p>
| [
{
"answer_id": 305680,
"author": "converter42",
"author_id": 28974,
"author_profile": "https://Stackoverflow.com/users/28974",
"pm_score": 0,
"selected": false,
"text": "SQLite version 3.6.2\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite> create table mytable (\n ...> id integer not null,\n ...> name varchar,\n ...> val integer,\n ...> primary key (id)\n ...> );\nsqlite> insert into mytable values(null,'A',20);\nsqlite> insert into mytable values(null,'B',21);\nsqlite> insert into mytable values(null,'C',22);\nsqlite> select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id > t1.id;\n1|2\n1|3\n2|3\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39167/"
] |
304,049 | <p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
| [
{
"answer_id": 312741,
"author": "RichieHH",
"author_id": 37370,
"author_profile": "https://Stackoverflow.com/users/37370",
"pm_score": 4,
"selected": true,
"text": "(setq load-path\n (append (list nil\n \"~/.emacs.d/python-mode-1.0/\"\n \"~/.emacs.d/pymacs/\"\n \"~/.emacs.d/ropemacs-0.6\"\n )\n load-path))\n(setq py-shell-name \"ipython\")\n\n(defadvice py-execute-buffer (around python-keep-focus activate)\n \"return focus to python code buffer\"\n (save-excursion ad-do-it))\n\n(setenv \"PYMACS_PYTHON\" \"python2.5\") \n(require 'pymacs)\n\n(pymacs-load \"ropemacs\" \"rope-\")\n\n(provide 'python-programming)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37370/"
] |
304,081 | <p>I'm building a winForms app in NET3.5SP1 using VS2008Express. Am trying to deserialize an object using the System.Web.Script.Serialization library.</p>
<p>The error is: Type 'jsonWinForm.Category' is not supported for deserialization of an array.</p>
<p>Cheers!</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
namespace jsonWinForm {
public class Category
{
public int categoryid;
public string name;
public int serverimageid;
public DateTime dateuploaded;
public bool enabled;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
//manipulate request headers (optional)
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
string targetUri = "http://www.davemateer.com/ig/genius/category.php";
//execute request and read response as string to console
using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
{
string s = reader.ReadToEnd();
textBox1.Text = s;
Category cat = new Category();
JavaScriptSerializer serializer = new JavaScriptSerializer();
// this fails with a
//Type 'jsonWinForm.Category' is not supported for deserialization of an array.
serializer.Deserialize<Category>(s);
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 304157,
"author": "Dave Mateer",
"author_id": 26086,
"author_profile": "https://Stackoverflow.com/users/26086",
"pm_score": 4,
"selected": false,
"text": "JavaScriptSerializer serializer = new JavaScriptSerializer();\n\n// create a generic list of categories\nList<Category> listOfCategories = new List<Category>();\n\n// deserialize as a list of Categories, and put into listOfCategories\nlistOfCategories = serializer.Deserialize<List<Category>>(s);\n\n//iterate through list and display in text box\nforeach (Category item in listOfCategories)\n{\n textBox2.Text += item.categoryid.ToString() + \"\\r\\n\";\n textBox2.Text += item.name.ToString() + \"\\r\\n\";\n textBox2.Text += item.serverimageid.ToString() + \"\\r\\n\";\n textBox2.Text += item.dateuploaded.ToString() + \"\\r\\n\";\n textBox2.Text += item.enabled.ToString() + \"\\r\\n\";\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26086/"
] |
304,088 | <p>The comment to <a href="https://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int#200099">this answer</a> got me wondering. I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension. Am I wrong about that? Is it possible to write a valid C program that is not valid C++ code?</p>
<p>EDIT: This is really similar to, but not an exact duplicate of <a href="https://stackoverflow.com/questions/145096/is-c-actually-a-superset-of-c#145098">this question</a>.</p>
| [
{
"answer_id": 304091,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 6,
"selected": true,
"text": "int *new;//<-- new is not a keyword in C\nchar *p = malloc(1024); //void * to char* without cast \n"
},
{
"answer_id": 304096,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 2,
"selected": false,
"text": "typedef struct {\n int a, b, c;\n} st;\n\nst s = {\n .a = 1,\n .b = 2,\n};\n"
},
{
"answer_id": 304177,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "int func();\nfunc(0,0); //Error in C++, but not in C\n int new; //Obviously an error in C++\n"
},
{
"answer_id": 304180,
"author": "cadabra",
"author_id": 39132,
"author_profile": "https://Stackoverflow.com/users/39132",
"pm_score": 3,
"selected": false,
"text": "extern \"C\""
},
{
"answer_id": 304185,
"author": "Roland Rabien",
"author_id": 39138,
"author_profile": "https://Stackoverflow.com/users/39138",
"pm_score": 3,
"selected": false,
"text": "char foo[3] = \"abc\" sizeof('A') == sizeof(int) void * struct struct typedef int main // char int"
},
{
"answer_id": 304214,
"author": "Josh Kelley",
"author_id": 25507,
"author_profile": "https://Stackoverflow.com/users/25507",
"pm_score": 4,
"selected": false,
"text": "_Complex _Imaginary"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
304,093 | <p>I was wondering why <code>shared_ptr</code> doesn't have an implicit constructor. The fact it doesn't is alluded to here: <a href="https://stackoverflow.com/questions/142391/getting-a-boostsharedptr-for-this">Getting a boost::shared_ptr for this</a></p>
<p>(I figured out the reason but thought it would be a fun question to post anyway.)</p>
<pre><code>#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace boost;
using namespace std;
void fun(shared_ptr<int> ptr) {
cout << *ptr << endl;
}
int main() {
int foo = 5;
fun(&foo);
return 0;
}
/* shared_ptr_test.cpp: In function `int main()':
* shared_ptr_test.cpp:13: conversion from `int*' to non-scalar type `
* boost::shared_ptr<int>' requested */
</code></pre>
| [
{
"answer_id": 304183,
"author": "user35978",
"author_id": 35978,
"author_profile": "https://Stackoverflow.com/users/35978",
"pm_score": -1,
"selected": false,
"text": "int main() {\n\n int foo = 5;\n fun(&foo);\n\n cout << foo << endl; // ops!!\n\n return 0;\n}\n"
},
{
"answer_id": 7688790,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": 3,
"selected": false,
"text": "delete shared_ scoped_ delete"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
304,109 | <p>Having the window handle for an open application, I'm able to use the GetWindowText function to retrieve the text from the title bar of the app. I would like to take this a step farther and retrieve the icon associated with the same app. </p>
<p>How might I go about doing this? I looked through what I thought would be the relevant Win32 API sections, but nothing jumped out at me.</p>
<p>Any pointers would be appreciated.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 304120,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": true,
"text": "Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);\n"
},
{
"answer_id": 14053737,
"author": "tklepzig",
"author_id": 1211266,
"author_profile": "https://Stackoverflow.com/users/1211266",
"pm_score": 3,
"selected": false,
"text": "[DllImport(\"user32.dll\")]\nstatic extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\n[DllImport(\"user32.dll\")]\nstatic extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);\n\n[DllImport(\"user32.dll\", EntryPoint = \"GetClassLong\")]\nstatic extern uint GetClassLong32(IntPtr hWnd, int nIndex);\n\n[DllImport(\"user32.dll\", EntryPoint = \"GetClassLongPtr\")]\nstatic extern IntPtr GetClassLong64(IntPtr hWnd, int nIndex);\n\n/// <summary>\n/// 64 bit version maybe loses significant 64-bit specific information\n/// </summary>\nstatic IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex)\n{\n if (IntPtr.Size == 4)\n return new IntPtr((long)GetClassLong32(hWnd, nIndex));\n else\n return GetClassLong64(hWnd, nIndex);\n}\n\n\nuint WM_GETICON = 0x007f;\nIntPtr ICON_SMALL2 = new IntPtr(2);\nIntPtr IDI_APPLICATION = new IntPtr(0x7F00);\nint GCL_HICON = -14;\n\npublic static Image GetSmallWindowIcon(IntPtr hWnd)\n{\n try\n {\n IntPtr hIcon = default(IntPtr);\n\n hIcon = SendMessage(hWnd, WM_GETICON, ICON_SMALL2, IntPtr.Zero);\n\n if (hIcon == IntPtr.Zero)\n hIcon = GetClassLongPtr(hWnd, GCL_HICON);\n\n if (hIcon == IntPtr.Zero)\n hIcon = LoadIcon(IntPtr.Zero, (IntPtr)0x7F00/*IDI_APPLICATION*/);\n\n if (hIcon != IntPtr.Zero)\n return new Bitmap(Icon.FromHandle(hIcon).ToBitmap(), 16, 16);\n else\n return null;\n }\n catch (Exception)\n {\n return null;\n }\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39171/"
] |
304,117 | <p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p>
<p>What I'd like to model is:</p>
<p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p>
<p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p>
<p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p>
<p>Any suggestions on the most efficient way to approach this on GAE?</p>
| [
{
"answer_id": 307312,
"author": "ianb",
"author_id": 20218,
"author_profile": "https://Stackoverflow.com/users/20218",
"pm_score": 1,
"selected": false,
"text": "Expando setattr(entity, 'tag_'+tag_name, True)\n def get_all_with_tag(model_class, tag):\n return model_class.all().filter('tag_%s =' % tag, True)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26241/"
] |
304,129 | <p>How do I return a constant from an sql statement? </p>
<p>For example how would I change the code below so "my message" would return if my (boolean expression) was true</p>
<pre><code>if (my boolean expression)
"my message"
else
select top 1 name from people;
</code></pre>
<p>I am using ms sql 2000</p>
| [
{
"answer_id": 304138,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 6,
"selected": true,
"text": "select 'my message';\n"
},
{
"answer_id": 304149,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 1 CASE WHEN myexpression = 'true' THEN 'my message' ELSE name END\nFROM people;\n CASE WHEN address LIKE '%Michigan%'\n"
},
{
"answer_id": 304186,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 3,
"selected": false,
"text": "select \"my message\" as message\n"
},
{
"answer_id": 304188,
"author": "user35559",
"author_id": 35559,
"author_profile": "https://Stackoverflow.com/users/35559",
"pm_score": 0,
"selected": false,
"text": "Use AdventureWorks\n\nDeclare @myVar int\nSET @myVar = 1\n\nif (@myVar = 2)\n\n select top 2 * from HumanResources.Department\n\nelse\n\n select top 1 * from HumanResources.Department\n"
},
{
"answer_id": 304324,
"author": "Bert",
"author_id": 38065,
"author_profile": "https://Stackoverflow.com/users/38065",
"pm_score": 2,
"selected": false,
"text": "select top 1 name \nfrom people\nwhere @MyParameter = whatever\n\nunion\n\nselect 'my message' as name\nwhere @MyParameter != whatever\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
304,130 | <p>Based on the advice provided at <a href="http://www.tweakguides.com/VA_4.html" rel="nofollow noreferrer">http://www.tweakguides.com/VA_4.html</a> to prevent Windows Vista from "intelligently" rearranging column formats in Windows Explorer, I have written a script to automate the process a little.</p>
<pre><code>Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
'Remove the "filthy" reg keys first.
regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU\"
WScript.Echo "Deleting " & regKey & VbCrLf
WshShell.RegDelete regKey
regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\"
WScript.Echo "Deleting " & regKey & VbCrLf
WshShell.RegDelete regKey
'Then recreate a clean Bags key, with sub-keys and FolderType value.
regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\ Windows\Shell\Bags\AllFolders\Shell\FolderType"
WScript.Echo "Creating " & regKey & " as 'NotSpecified' REG_SZ " & VbCrLf
WshShell.RegWrite regKey, "NotSpecified", "REG_SZ"
WScript.Echo "Now define the columns of your preference in Windows Explorer," & VbCrLf
WScript.Echo "and click the Apply to Folders button in Folder Options." & VbCrLf
</code></pre>
<p>But it is refusing to delete the registry key</p>
<pre><code>E:\archive\settings\Windows Vista Explorer columns.vbs(9, 1) WshShell.RegDelete:
Unable to remove registry key "HKCU\Software\Classes\Local Settings\Software\Mi
crosoft\Windows\Shell\BagMRU\".
</code></pre>
<p>The suggestion is to put trailing "\" to indicate a key, which I did. Any ideas?</p>
| [
{
"answer_id": 9645214,
"author": "aelgoa",
"author_id": 1260792,
"author_profile": "https://Stackoverflow.com/users/1260792",
"pm_score": 1,
"selected": false,
"text": "Const HKCR=&H80000000:Const HKCU=&H80000001:Const HKLM=&H80000002:Const HKU=&H80000003:Const HKCC=&H80000005\n\ndim pc,o,hive,key,name,value,i\npc=\".\"\nSet o=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & pc & \"\\root\\default:StdRegProv\")\n\nhive=HKCU\nkey=\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Wallpapers\\knownfolders\\0\\windows wallpapers\\mergefolders\"\nregrid 5\n\nsub regrid(levels)\ndim a,n,j,base,s\n a=split(key,\"\\\")\n n=ubound(a)\n base=\"\":for i=0 to levels-1:base=base & a(i) & \"\\\":next\n for i=n to levels step -1\n s=\"\":for j=levels to i:s=s & a(j) & \"\\\":next\n o.DeleteKey hive,base & s\n next\nend sub\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663/"
] |
304,139 | <p>So the chain of events is:</p>
<ol>
<li>The user submits a form.</li>
<li>During the processing of the submission, there is a message generated, such as "Your record was saved."</li>
<li>The user is redirected to a new page, say the search results.</li>
<li>The new page needs to display the message.</li>
</ol>
<p>So, the question is how to get the message from step 2 to step 3? This is only one simple example...there are many other much more complicated examples.</p>
<p>I am using PHP.</p>
<p>Needs:</p>
<ul>
<li>supports multiple messages and need to be formatted on the receiving machine as required</li>
<li>messages can be added on the same page (such as within step 4)</li>
<li>messages added from inside any function or object</li>
</ul>
<p>Some options I have come up with:</p>
<ul>
<li>store in a session variable as an array and emptied after each display</li>
<li>pass as a get or query parameter; can get annoying as you are constantly processing this and have to remember to get it; as it can get long, it could easily go over the max length of the query string</li>
<li>store in the database on a per session basis (may not always be for a logged in user); this would require an extra insert on each page where they are added, possibly multiple, and an extra select on every page</li>
</ul>
<p>Currently I have been storing the messages in the session in an array, but I'm wondering if there is a better way. I don't think the other 2 options above are very good.</p>
<p><strong>Edit:</strong> I use 2 functions for the session method: AddStatusMsg() (adds an element to the array) and DisplayStatusMsg() (returns an HTML formatted message and empties the array).</p>
| [
{
"answer_id": 304168,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 0,
"selected": false,
"text": "<?php class session\n public function __construct()\n{\n session_start();\n}\n\npublic function set($name, $value)\n{\n $_SESSION[$name] = $value;\n}\n\npublic function get($name)\n{\n return (isset($_SESSION[$name])) ? $_SESSION[$name] : false ;\n}\n\npublic function delete($name)\n{\n unset($_SESSION[$name]);\n}\n\npublic function destroy()\n{\n $_SESSION = array();\n #session_destory();\n #session_regenerate_id();\n}\n"
},
{
"answer_id": 304178,
"author": "Murat Ayfer",
"author_id": 25910,
"author_profile": "https://Stackoverflow.com/users/25910",
"pm_score": 2,
"selected": false,
"text": "function set_message($message_type, $message)\n{\n $_SESSION['messages'][$message_type][] = $message\n}\n\nfunction get_messages()\n{\n $messages_array = $_SESSION['messages'];\n unset($_SESSION['messages']);\n return $messages_array;\n}\n $message_type"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
304,152 | <p>I am using Python and the <a href="http://twistedmatrix.com/trac/" rel="nofollow noreferrer">Twisted</a> framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.</p>
<p>When connecting and calling the <strong>list</strong> method on an <strong>FTPClient</strong>, the resulting <strong>FTPFileListProtocol</strong>'s <strong>files</strong> collection does not contain any directories or file names that contain a space (' ').</p>
<p>Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its <strong>unknownLine</strong> method, parsing the file/directory names manually?</p>
| [
{
"answer_id": 311236,
"author": "Martin Carpenter",
"author_id": 39443,
"author_profile": "https://Stackoverflow.com/users/39443",
"pm_score": 3,
"selected": true,
"text": "NLST LIST LIST LIST MLST MLSD NLST NLST LIST LIST NLST"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696/"
] |
304,213 | <p>I am using the ASP.NET <strong>Client-Side</strong> ajax control toolkit in my asp.net MVC application. I see that there is a .js file named "AjaxControlToolkit.ModalPopup.ModalPopupBehavior.js" in the AjaxControlToolkit folder. However, I cannot find any examples on how to use it.<br /><br />
[Edit] -
As mentioned, I am using the Client-side, Script-only control toolkit. For those unfamiliar, here is the description from CodePlex:<br/></p>
<blockquote>
<p>AjaxControlToolkit-ScriptFilesOnly.zip
contains script files, CSS style
sheets and pictures used by the
toolkit. Use this download if you
don't want to use embedded resources
and prefer a file-based model.</p>
</blockquote>
<p>I have not been able to find many resources on how to use some of the scripts included with this.
CodePlex link: <a href="http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx" rel="nofollow noreferrer">http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx</a></p>
| [
{
"answer_id": 759377,
"author": "Gramic",
"author_id": 18788,
"author_profile": "https://Stackoverflow.com/users/18788",
"pm_score": 3,
"selected": true,
"text": "<script src=\"javascripts/MicrosoftAjax.js\" type=\"text/javascript\" ></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.Compat.Timer.Timer.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.Common.Common.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.ExtenderBase.BaseScripts.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.Animation.Animations.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.DropShadow.DropShadowBehavior.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js\" type=\"text/javascript\"></script>\n<script src=\"javascripts/AjaxControlToolkit/AjaxControlToolkit.PopupExtender.PopupBehavior.js\" type=\"text/javascript\"></script>\n $create(AjaxControlToolkit.PopupControlBehavior, {\"PopupControlID\":\"div_to_popup\",\"Position\":3}, null, null, $get(\"textbox_input_id\"));\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37786/"
] |
304,216 | <p>Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.</p>
| [
{
"answer_id": 304220,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "etree.findall('.//*')\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2220518/"
] |
304,226 | <p>I have a custom NSTableView subclass which is bound to a data source (an NSArray) which updates asynchronously. When items are added to the array, rows are automatically added to the tableview. Awesome!</p>
<p>My question is this: How can I detect that this magic has happened so that I can perform some other tasks related to the display of my custom tableview? Is there a method that I can override in my subclass which will be called when the tableview is updated?</p>
| [
{
"answer_id": 304304,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 4,
"selected": true,
"text": "enclosingScrollView rowHeight intercellSpacing"
},
{
"answer_id": 991114,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "\n// tv = NSTableView\n// view = NSView\n\nint height = ([tv rowHeight] + [tv intercellSpacing].height) * [itemNodes count];\n\nNSScrollView *sv = [tv enclosingScrollView];\n\nNSRect svFrame = [sv frame];\nsvFrame.size.height = height;\n[sv setFrame:svFrame];\n\nNSRect viewFrame = [view frame];\nviewFrame.size.height = height;\n[view setFrame:viewFrame];\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33686/"
] |
304,233 | <p>I'm trying to use the ASP.NET MVC Ajax.BeginForm helper but don't want to use the existing content insertion options when the call completes. Instead, I want to use a custom JavaScript function as the callback.</p>
<p>This works, but the result I want should be returned as JSON. Unfortunately, the framework just treats the data as a string. Below is the client code. The server code simply returns a JsonResult with one field, UppercaseName.</p>
<pre><code><script type='text/javascript'>
function onTestComplete(content) {
var result = content.get_data();
alert(result.UppercaseName);
}
</script>
<% using (Ajax.BeginForm("JsonTest", new AjaxOptions() {OnComplete = "onTestComplete" })) { %>
<%= Html.TextBox("name") %><br />
<input type="submit" />
<%} %>
</code></pre>
<p>Instead of showing the uppercase result, it is instead showing undefined. content.get_data() seems to hold the JSON, but only in string form. How do I go about converting this to an object?</p>
<p>All of this seems a bit convoluted really. Is there a better way to get at the resulting content using Ajax.BeginForm? If it's this hard, I may skip Ajax.BeginForm entirely and just use the jQuery form library.</p>
| [
{
"answer_id": 304517,
"author": "Kobi",
"author_id": 39215,
"author_profile": "https://Stackoverflow.com/users/39215",
"pm_score": 5,
"selected": true,
"text": "var json_data = content.get_response().get_object();\n json_data[0]"
},
{
"answer_id": 2107434,
"author": "Russel",
"author_id": 255545,
"author_profile": "https://Stackoverflow.com/users/255545",
"pm_score": 0,
"selected": false,
"text": "<script type='text/javascript'>\n function onTestComplete(content) {\n var result = eval( '(' + content.get_data() + ')' );\n alert(result.UppercaseName);\n }\n</script>\n"
},
{
"answer_id": 3567781,
"author": "Michael Callahan",
"author_id": 425416,
"author_profile": "https://Stackoverflow.com/users/425416",
"pm_score": -1,
"selected": false,
"text": "var json = context.get_data();\nvar data = Sys.Serialization.JavaScriptSerializer.deserialize(json);\n"
},
{
"answer_id": 7467032,
"author": "Joel Purra",
"author_id": 907779,
"author_profile": "https://Stackoverflow.com/users/907779",
"pm_score": 5,
"selected": false,
"text": "OnFailure OnSuccess OnComplete OnSuccess ~/Scripts/jquery.unobtrusive-ajax.min.js Ajax.BeginForm new AjaxOptions\n {\n OnFailure = \"onTestFailure\",\n OnSuccess = \"onTestSuccess\"\n }\n <script>\n//<![CDATA[\n\n function onTestFailure(xhr, status, error) {\n\n console.log(\"Ajax form submission\", \"onTestFailure\");\n console.log(\"xhr\", xhr);\n console.log(\"status\", status);\n console.log(\"error\", error);\n\n // TODO: make me pretty\n alert(error);\n }\n\n function onTestSuccess(data, status, xhr) {\n\n console.log(\"Ajax form submission\", \"onTestSuccess\");\n console.log(\"data\", data);\n console.log(\"status\", status);\n console.log(\"xhr\", xhr);\n\n // Here's where you use the JSON object\n //doSomethingUseful(data);\n }\n\n//]]>\n</script>\n success error"
},
{
"answer_id": 21997205,
"author": "Juan Carlos Velez",
"author_id": 391895,
"author_profile": "https://Stackoverflow.com/users/391895",
"pm_score": 0,
"selected": false,
"text": " function onTestComplete(data, status, xhr) {\n var data2 = JSON.parse(data.responseText);\n //data2 is your object\n }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656/"
] |
304,240 | <pre><code><?php
class foo
{
//this class is always etended, and has some other methods that do utility work
//and are never overrided
public function init()
{
//what do to here to call bar->doSomething or baz->doSomething
//depending on what class is actually instantiated?
}
function doSomething()
{
//intentionaly no functionality here
}
}
class bar extends foo
{
function doSomething()
{
echo "bar";
}
}
class baz extends foo
{
function doSomething()
{
echo "baz";
}
}
?>
</code></pre>
| [
{
"answer_id": 304245,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "public function init() {\n $this->doSomething();\n}\n\n$obj = new bar();\n$obj->doSomething(); // prints \"bar\"\n\n$obj2 = new baz();\n$obj->doSomething(); // prints \"baz\"\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39183/"
] |
304,249 | <p>I assume 100 bytes is too small and can slow down larger file transfers with all of the writes, but something like 1MB seems like it may be too much. Does anyone have any suggestions for an optimal chunk of bytes per write for sending data over a network?</p>
<p>To elaborate a bit more, I'm implementing something that sends data over a network connection and show the progress of that data being sent. I've noticed if I send large files at about 100 bytes each write, it is extremely slow but the progress bar works out very nicely. However, if I send at say 1M per write, it is much faster, but the progress bar doesn't work as nicely due to the larger chunks being sent.</p>
| [
{
"answer_id": 304841,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 2,
"selected": false,
"text": "Private PreferredTransferDuration As Integer = 1800 ' milliseconds, the timespan the class will attempt to achieve for each chunk, to give responsive feedback on the progress bar.\nPrivate ChunkSizeSampleInterval As Integer = 15 ' interval to update the chunk size, used in conjunction with AutoSetChunkSize. \nPrivate ChunkSize As Integer = 16 * 1024 ' 16k by default \nPrivate StartTime As DateTime\nPrivate MaxRequestLength As Long = 4096 ' default, this is updated so that the transfer class knows how much the server will accept \n Dim currentIntervalMod As Integer = numIterations Mod Me.ChunkSizeSampleInterval\n If currentIntervalMod = 0 Then\n Me.StartTime = DateTime.Now\n ElseIf currentIntervalMod = 1 Then\n Me.CalcChunkSize()\n End If\n Protected Sub CalcAndSetChunkSize()\n ' chunk size calculation is defined as follows \n ' * in the examples below, the preferred transfer time is 1500ms, taking one sample. \n ' * \n ' * Example 1 Example 2 \n ' * Initial size = 16384 bytes (16k) 16384 \n ' * Transfer time for 1 chunk = 800ms 2000 ms \n ' * Average throughput / ms = 16384b / 800ms = 20.48 b/ms 16384 / 2000 = 8.192 b/ms \n ' * How many bytes in 1500ms? = 20.48 * 1500 = 30720 bytes 8.192 * 1500 = 12228 bytes \n ' * New chunksize = 30720 bytes (speed up) 12228 bytes (slow down from original chunk size) \n ' \n\n Dim transferTime As Double = DateTime.Now.Subtract(Me.StartTime).TotalMilliseconds\n Dim averageBytesPerMilliSec As Double = Me.ChunkSize / transferTime\n Dim preferredChunkSize As Double = averageBytesPerMilliSec * Me.PreferredTransferDuration\n Me.ChunkSize = CInt(Math.Min(Me.MaxRequestLength, Math.Max(4 * 1024, preferredChunkSize)))\n ' set the chunk size so that it takes 1500ms per chunk (estimate), not less than 4Kb and not greater than 4mb // (note 4096Kb sometimes causes problems, probably due to the IIS max request size limit, choosing a slightly smaller max size of 4 million bytes seems to work nicely) \nEnd Sub\n"
},
{
"answer_id": 306218,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "int optimalChunkSize = totalDataSize / progressBar1.Width;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39185/"
] |
304,256 | <p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html" rel="noreferrer"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
| [
{
"answer_id": 304288,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": -1,
"selected": false,
"text": "strptime %W %w def fromisocalendar(y,w,d):\n return datetime.strptime( \"%04dW%02d-%d\"%(y,w-1,d), \"%YW%W-%w\")\n 1 %W 0 1 %w 0 7"
},
{
"answer_id": 1700069,
"author": "Ben James",
"author_id": 189179,
"author_profile": "https://Stackoverflow.com/users/189179",
"pm_score": 7,
"selected": true,
"text": ">>> datetime.fromisocalendar(2011, 22, 1)\ndatetime.datetime(2011, 5, 30, 0, 0)\n %G %V %u >>> datetime.strptime('2011 22 1', '%G %V %u')\ndatetime.datetime(2011, 5, 30, 0, 0)\n import datetime\n\ndef iso_year_start(iso_year):\n \"The gregorian calendar date of the first day of the given ISO year\"\n fourth_jan = datetime.date(iso_year, 1, 4)\n delta = datetime.timedelta(fourth_jan.isoweekday()-1)\n return fourth_jan - delta \n\ndef iso_to_gregorian(iso_year, iso_week, iso_day):\n \"Gregorian calendar date for the given ISO year, week and day\"\n year_start = iso_year_start(iso_year)\n return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)\n >>> iso = datetime.date(2005, 1, 1).isocalendar()\n>>> iso\n(2004, 53, 6)\n>>> iso_to_gregorian(*iso)\ndatetime.date(2005, 1, 1)\n\n>>> iso = datetime.date(2010, 1, 4).isocalendar() \n>>> iso\n(2010, 1, 1)\n>>> iso_to_gregorian(*iso)\ndatetime.date(2010, 1, 4)\n\n>>> iso = datetime.date(2010, 1, 3).isocalendar()\n>>> iso\n(2009, 53, 7)\n>>> iso_to_gregorian(*iso)\ndatetime.date(2010, 1, 3)\n"
},
{
"answer_id": 33101215,
"author": "jwg",
"author_id": 1737957,
"author_profile": "https://Stackoverflow.com/users/1737957",
"pm_score": 3,
"selected": false,
"text": "import datetime\n\ndef iso_to_gregorian(iso_year, iso_week, iso_day):\n \"Gregorian calendar date for the given ISO year, week and day\"\n fourth_jan = datetime.date(iso_year, 1, 4)\n _, fourth_jan_week, fourth_jan_day = fourth_jan.isocalendar()\n return fourth_jan + datetime.timedelta(days=iso_day-fourth_jan_day, weeks=iso_week-fourth_jan_week)\n"
},
{
"answer_id": 35167439,
"author": "Erik Cederstrand",
"author_id": 219640,
"author_profile": "https://Stackoverflow.com/users/219640",
"pm_score": 2,
"selected": false,
"text": "datetime.strptime() %G %V %u datetime.strptime('2015 1 2', '%G %V %u').date()"
},
{
"answer_id": 35891060,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 4,
"selected": false,
"text": "%G %u %V %G %V %u %V from datetime import datetime\n\ndatetime.strptime('2002 01 1', '%G %V %u').date()\n from datetime import datetime\n\ndef date_from_isoweek(iso_year, iso_weeknumber, iso_weekday):\n return datetime.strptime(\n '{:04d} {:02d} {:d}'.format(iso_year, iso_weeknumber, iso_weekday),\n '%G %V %u').date()\n"
},
{
"answer_id": 38283685,
"author": "Jo So",
"author_id": 1073695,
"author_profile": "https://Stackoverflow.com/users/1073695",
"pm_score": 2,
"selected": false,
"text": "def iso_to_gregorian(iso_year, iso_week, iso_day):\n jan4 = datetime.date(iso_year, 1, 4)\n start = jan4 - datetime.timedelta(days=jan4.isoweekday()-1)\n return start + datetime.timedelta(weeks=iso_week-1, days=iso_day-1)\n"
},
{
"answer_id": 55957668,
"author": "oviedodaniel",
"author_id": 2144900,
"author_profile": "https://Stackoverflow.com/users/2144900",
"pm_score": 0,
"selected": false,
"text": "import datetime\ndef getDateFromWeek(year,week,day):\n \"\"\"Method to retrieve the date from the specified week, year and weekday\"\"\"\n\n year_start = datetime.date(year,1,1)\n ys_weekday = year_start.weekday()\n delta = (week*7)+(day-ys_weekday)\n if ys_weekday<4:\n delta -= 7\n\n return year_start + datetime.timedelta(days=delta)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
304,268 | <p>I am looking to use Java to get the MD5 checksum of a file. I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file.</p>
<p>How is it done?</p>
| [
{
"answer_id": 304275,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 7,
"selected": false,
"text": "import java.io.*;\nimport java.security.MessageDigest;\n\npublic class MD5Checksum {\n\n public static byte[] createChecksum(String filename) throws Exception {\n InputStream fis = new FileInputStream(filename);\n\n byte[] buffer = new byte[1024];\n MessageDigest complete = MessageDigest.getInstance(\"MD5\");\n int numRead;\n\n do {\n numRead = fis.read(buffer);\n if (numRead > 0) {\n complete.update(buffer, 0, numRead);\n }\n } while (numRead != -1);\n\n fis.close();\n return complete.digest();\n }\n\n // see this How-to for a faster way to convert\n // a byte array to a HEX string\n public static String getMD5Checksum(String filename) throws Exception {\n byte[] b = createChecksum(filename);\n String result = \"\";\n\n for (int i=0; i < b.length; i++) {\n result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );\n }\n return result;\n }\n\n public static void main(String args[]) {\n try {\n System.out.println(getMD5Checksum(\"apache-tomcat-5.5.17.exe\"));\n // output :\n // 0bb2827c5eacf570b6064e24e0e6653b\n // ref :\n // http://www.apache.org/dist/\n // tomcat/tomcat-5/v5.5.17/bin\n // /apache-tomcat-5.5.17.exe.MD5\n // 0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n"
},
{
"answer_id": 304350,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 10,
"selected": true,
"text": "java.security.DigestInputStream MessageDigest md = MessageDigest.getInstance(\"MD5\");\ntry (InputStream is = Files.newInputStream(Paths.get(\"file.txt\"));\n DigestInputStream dis = new DigestInputStream(is, md)) \n{\n /* Read decorated stream (dis) to EOF as normal... */\n}\nbyte[] digest = md.digest();\n"
},
{
"answer_id": 304417,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 4,
"selected": false,
"text": "MessageDigest try {\n String s = \"TEST STRING\";\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(s.getBytes(),0,s.length());\n String signature = new BigInteger(1,md5.digest()).toString(16);\n System.out.println(\"Signature: \"+signature);\n\n} catch (final NoSuchAlgorithmException e) {\n e.printStackTrace();\n}\n"
},
{
"answer_id": 2932513,
"author": "Leif Gruenwoldt",
"author_id": 52176,
"author_profile": "https://Stackoverflow.com/users/52176",
"pm_score": 8,
"selected": false,
"text": "try (InputStream is = Files.newInputStream(Paths.get(\"file.zip\"))) {\n String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);\n}\n"
},
{
"answer_id": 3216165,
"author": "Matt Brock",
"author_id": 313969,
"author_profile": "https://Stackoverflow.com/users/313969",
"pm_score": 2,
"selected": false,
"text": "<checksum file=\"${jarFile}\" todir=\"${toDir}\"/>\n"
},
{
"answer_id": 3229868,
"author": "F.X",
"author_id": 389618,
"author_profile": "https://Stackoverflow.com/users/389618",
"pm_score": 3,
"selected": false,
"text": "public static String MD5Hash(String toHash) throws RuntimeException {\n try{\n return String.format(\"%032x\", // produces lower case 32 char wide hexa left-padded with 0\n new BigInteger(1, // handles large POSITIVE numbers \n MessageDigest.getInstance(\"MD5\").digest(toHash.getBytes())));\n }\n catch (NoSuchAlgorithmException e) {\n // do whatever seems relevant\n }\n}\n"
},
{
"answer_id": 4524930,
"author": "user552999",
"author_id": 552999,
"author_profile": "https://Stackoverflow.com/users/552999",
"pm_score": 3,
"selected": false,
"text": "...\nString signature = new BigInteger(1,md5.digest()).toString(16);\n...\n BigInteger.toString() s = \"27\" \"02e74f10e0327ad868d138f2b4fdd6f0\""
},
{
"answer_id": 4526005,
"author": "oluies",
"author_id": 203968,
"author_profile": "https://Stackoverflow.com/users/203968",
"pm_score": 7,
"selected": false,
"text": "Files.hash() HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());\n\"SHA-1: \" + hc.toString();\n"
},
{
"answer_id": 5325767,
"author": "Lukasz R.",
"author_id": 151813,
"author_profile": "https://Stackoverflow.com/users/151813",
"pm_score": 3,
"selected": false,
"text": "String hash = MD5.asHex(MD5.getHash(new File(filename)));\n"
},
{
"answer_id": 12790157,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 5,
"selected": false,
"text": "HashCode md5 = Files.hash(file, Hashing.md5());\nbyte[] md5Bytes = md5.asBytes();\nString md5Hex = md5.toString();\n\nHashCode crc32 = Files.hash(file, Hashing.crc32());\nint crc32Int = crc32.asInt();\n\n// the Checksum API returns a long, but it's padded with 0s for 32-bit CRC\n// this is the value you would get if using that API directly\nlong checksumResult = crc32.padToLong();\n"
},
{
"answer_id": 14098236,
"author": "Jam",
"author_id": 1939119,
"author_profile": "https://Stackoverflow.com/users/1939119",
"pm_score": 4,
"selected": false,
"text": "public static void main(String[] args) throws Exception {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n FileInputStream fis = new FileInputStream(\"c:\\\\apache\\\\cxf.jar\");\n\n byte[] dataBytes = new byte[1024];\n\n int nread = 0;\n while ((nread = fis.read(dataBytes)) != -1) {\n md.update(dataBytes, 0, nread);\n };\n byte[] mdbytes = md.digest();\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < mdbytes.length; i++) {\n sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));\n }\n System.out.println(\"Digest(in hex format):: \" + sb.toString());\n}\n"
},
{
"answer_id": 15527393,
"author": "MickJ",
"author_id": 2027264,
"author_profile": "https://Stackoverflow.com/users/2027264",
"pm_score": 5,
"selected": false,
"text": "DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))\n DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))\n"
},
{
"answer_id": 19427098,
"author": "gotozero",
"author_id": 2528638,
"author_profile": "https://Stackoverflow.com/users/2528638",
"pm_score": 3,
"selected": false,
"text": "public String checksum(File file) {\n try {\n InputStream fin = new FileInputStream(file);\n java.security.MessageDigest md5er =\n MessageDigest.getInstance(\"MD5\");\n byte[] buffer = new byte[1024];\n int read;\n do {\n read = fin.read(buffer);\n if (read > 0)\n md5er.update(buffer, 0, read);\n } while (read != -1);\n fin.close();\n byte[] digest = md5er.digest();\n if (digest == null)\n return null;\n String strDigest = \"0x\";\n for (int i = 0; i < digest.length; i++) {\n strDigest += Integer.toString((digest[i] & 0xff) \n + 0x100, 16).substring(1).toUpperCase();\n }\n return strDigest;\n } catch (Exception e) {\n return null;\n }\n}\n"
},
{
"answer_id": 19554280,
"author": "Balaji Boggaram Ramanarayan",
"author_id": 2101290,
"author_profile": "https://Stackoverflow.com/users/2101290",
"pm_score": 2,
"selected": false,
"text": "public static HashCode hash(File file,\n HashFunction hashFunction)\n throws IOException\n\nComputes the hash code of the file using hashFunction.\n\nParameters:\n file - the file to read\n hashFunction - the hash function to use to hash the data\nReturns:\n the HashCode of all of the bytes in the file\nThrows:\n IOException - if an I/O error occurs\nSince:\n 12.0\n"
},
{
"answer_id": 22602793,
"author": "XXX",
"author_id": 991737,
"author_profile": "https://Stackoverflow.com/users/991737",
"pm_score": 2,
"selected": false,
"text": "public static String getMd5OfFile(String filePath)\n{\n String returnVal = \"\";\n try \n {\n InputStream input = new FileInputStream(filePath); \n byte[] buffer = new byte[1024];\n MessageDigest md5Hash = MessageDigest.getInstance(\"MD5\");\n int numRead = 0;\n while (numRead != -1)\n {\n numRead = input.read(buffer);\n if (numRead > 0)\n {\n md5Hash.update(buffer, 0, numRead);\n }\n }\n input.close();\n\n byte [] md5Bytes = md5Hash.digest();\n for (int i=0; i < md5Bytes.length; i++)\n {\n returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 );\n }\n } \n catch(Throwable t) {t.printStackTrace();}\n return returnVal.toUpperCase();\n}\n"
},
{
"answer_id": 26231444,
"author": "assylias",
"author_id": 829571,
"author_profile": "https://Stackoverflow.com/users/829571",
"pm_score": 6,
"selected": false,
"text": "byte[] b = Files.readAllBytes(Paths.get(\"/path/to/file\"));\nbyte[] hash = MessageDigest.getInstance(\"MD5\").digest(b);\n String expected = \"2252290BC44BEAD16AA1BF89948472E8\";\nString actual = DatatypeConverter.printHexBinary(hash);\nSystem.out.println(expected.equalsIgnoreCase(actual) ? \"MATCH\" : \"NO MATCH\");\n"
},
{
"answer_id": 26670214,
"author": "sunil",
"author_id": 474193,
"author_profile": "https://Stackoverflow.com/users/474193",
"pm_score": 5,
"selected": false,
"text": "String path = \"your complete file path\";\nMessageDigest md = MessageDigest.getInstance(\"MD5\");\nmd.update(Files.readAllBytes(Paths.get(path)));\nbyte[] digest = md.digest();\n System.out.println(Arrays.toString(digest));\n String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();\nSystem.out.println(digestInHex);\n"
},
{
"answer_id": 30199239,
"author": "David",
"author_id": 4396234,
"author_profile": "https://Stackoverflow.com/users/4396234",
"pm_score": 3,
"selected": false,
"text": "public String calcMD5() throws Exception{\n byte[] buffer = new byte[8192];\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n\n DigestInputStream dis = new DigestInputStream(new FileInputStream(new File(\"Path to file\")), md);\n try {\n while (dis.read(buffer) != -1);\n }finally{\n dis.close();\n }\n\n byte[] bytes = md.digest();\n\n // bytesToHex-method\n char[] hexChars = new char[bytes.length * 2];\n for ( int j = 0; j < bytes.length; j++ ) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = hexArray[v >>> 4];\n hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n }\n\n return new String(hexChars);\n}\n"
},
{
"answer_id": 39183302,
"author": "Ravikiran kalal",
"author_id": 1545118,
"author_profile": "https://Stackoverflow.com/users/1545118",
"pm_score": 3,
"selected": false,
"text": "String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));\n"
},
{
"answer_id": 41069829,
"author": "stackoverflowuser2010",
"author_id": 4561314,
"author_profile": "https://Stackoverflow.com/users/4561314",
"pm_score": 3,
"selected": false,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\nimport javax.xml.bind.DatatypeConverter;\n\npublic class Checksum {\n\n /**\n * Generates an MD5 checksum as a String.\n * @param file The file that is being checksummed.\n * @return Hex string of the checksum value.\n * @throws NoSuchAlgorithmException\n * @throws IOException\n */\n public static String generate(File file) throws NoSuchAlgorithmException,IOException {\n\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(Files.readAllBytes(file.toPath()));\n byte[] hash = messageDigest.digest();\n\n return DatatypeConverter.printHexBinary(hash).toUpperCase();\n }\n\n public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {\n File file = new File(\"/Users/foo.bar/Documents/file.jar\"); \n String hex = Checksum.generate(file);\n System.out.printf(\"hex=%s\\n\", hex); \n }\n\n\n}\n hex=B117DD0C3CBBD009AC4EF65B6D75C97B\n"
},
{
"answer_id": 52239875,
"author": "BillRobertson42",
"author_id": 359035,
"author_profile": "https://Stackoverflow.com/users/359035",
"pm_score": 3,
"selected": false,
"text": "InputStream.transferTo() OutputStream.nullOutputStream() public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {\n MessageDigest md = MessageDigest.getInstance(algorithm);\n\n try(BufferedInputStream in = new BufferedInputStream((new FileInputStream(f)));\n DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {\n in.transferTo(out);\n }\n\n String fx = \"%0\" + (md.getDigestLength()*2) + \"x\";\n return String.format(fx, new BigInteger(1, md.digest()));\n}\n hashFile(\"SHA-512\", Path.of(\"src\", \"test\", \"resources\", \"some.txt\").toFile());\n \"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29\"\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24998/"
] |
304,270 | <p>Ok, I have one JavaScript that creates rows in a table like this:</p>
<pre><code> function AddRow(text,rowID) {
var tbl = document.getElementById('tblNotePanel');
var row = tbl.insertRow(tbl.rows.length);
var cell = row.insertCell();
var textNode = document.createTextNode(text);
cell.id = rowID;
cell.style.backgroundColor = "gold";
cell.onclick = clickTest;
cell.appendChild(textNode);
}
</code></pre>
<p>In the above function, I set the cell's <code>onclick</code> function to call another JavaScript function called <code>clickTest</code>. My question is when I assign the <code>onclick</code> event to call <code>clickTest</code>, how do I set parameter information to be sent when the <code>clickTest</code> method is called on the cell's <code>onclick</code> event? Or, how do I access the cell's ID in the <code>clickTest</code> function?</p>
<p>Thanks,
Jeff</p>
| [
{
"answer_id": 304282,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 2,
"selected": false,
"text": "this clickTest alert(this.id);\n cell.onclick = function() { alert(this.id); alert(cell.id); };\n cell.id"
},
{
"answer_id": 304283,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": true,
"text": "cell.onclick = function() { clickTest(rowID); };\n"
},
{
"answer_id": 73628173,
"author": "ar2015",
"author_id": 4623526,
"author_profile": "https://Stackoverflow.com/users/4623526",
"pm_score": 0,
"selected": false,
"text": "onclick onclick for(var loopObj of loopObjList)\n mydiv.setAttribute('onclick', 'javascript: pick_option(' + loopObj.id + ', \"' + loopObj.value + '\");' );\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
304,281 | <p>I can't figure out how to get the SCOPE_IDENTITY() back to my variables from an SQL2005 Store Procedure.</p>
<p>My sSQL String:</p>
<pre><code>sSQL = "EXEC [sp_NewClaim] " & Chr(34) & ClaimNumber & Chr(34) & ", " & Request.Cookies("UserID") & ", " & Request.Cookies("MasterID") & ", " & Chr(34) & strRestaurante & Chr(34) & ", " & Chr(34) & Fecha & Chr(34) & ", " & Chr(34) & Hora & Chr(34) & ", " & Chr(34) & Request("Tiempo") & Chr(34) & ", " & Chr(34) & Request("Luz") & Chr(34) & ", " & Chr(34) & Request("Desc") & Chr(34) & ", " & Chr(34) & Request("incidente") & Chr(34) & ", " & Chr(34) & Request("codigos") & Chr(34) & ", False, 0; SELECT RecordNumber = SCOPE_IDENTITY()"
</code></pre>
<p>My sSQL Output:</p>
<pre><code>EXEC [sp_NewClaim] "W200811", 7, 8, "Otro -- WORK PLEASE", "11/19/2008", "01:19 PM", "Nublado", "Mala", "asdasd", "uyiuyui", "C-Junta", False, 0; SELECT RecordNumber = SCOPE_IDENTITY()
</code></pre>
<p>Executing my SQL Command:</p>
<pre><code>Set rsData= Server.CreateObject("ADODB.Recordset")
rsData.Open sSQL, conDB, adOpenKeyset, adLockOptimistic
</code></pre>
<p>Trying to Output the SCOPE_IDENTITY() Produces an Empty Variable (No Output):</p>
<pre><code>Response.Write("<br />Record Number: " & rsData("RecordNumber"))
</code></pre>
<p>The Store Procedure runs correctly. My Information gets stored into my database with out problems. RecordNumber is the Column with the Identity, and the Store Procedure has defined @RecordNumber as an Output:</p>
<pre><code>USE [db_clcinsurance_com]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE sp_NewClaim
(
@ClaimNumber nvarchar(50),
@blah............
.................
@RecordNumber INT OUTPUT
)
AS
BEGIN
INSERT INTO Accidente (ClaimNumber,........., RecordNumber)
VALUES (@ClaimNumber,....., @RecordNumber)
SET @RecordNumber = SCOPE_IDENTITY();
END
</code></pre>
| [
{
"answer_id": 304294,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "CREATE PROCEDURE sp_NewClaim\n (\n @ClaimNumber nvarchar(50),\n @blah............\n .................\n)\nAS\nBEGIN\n SET NOCOUNT ON;\n\n INSERT INTO Accidente (ClaimNumber,........., RecordNumber)\n VALUES (@ClaimNumber,....., @RecordNumber)\n\n SELECT SCOPE_IDENTITY()\nEND\n"
},
{
"answer_id": 304298,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 0,
"selected": false,
"text": "SCOPE_IDENTITY() SELECT @RecordNumber SELECT SCOPE_IDENTITY()"
},
{
"answer_id": 304313,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 0,
"selected": false,
"text": "Return Scope_Identity()\n SqlCommand cmd = new SqlCommand(\"INSERT INTO Foo (Description) VALUES (@Description); SET @Result = SCOPE_IDENTITY()\");\nSqlParameter paramDesc = new SqlParameter(\"@Description\", SqlDbType.Int);\ncmd.Parameters.Add(paramDesc);\nSqlParameter paramResult = new SqlParameter(\"@Result\", SqlDbType.Int);\nparamResult.Direction = ParameterDirection.Output;\ncmd.Parameters.Add(paramResult);\n"
},
{
"answer_id": 304388,
"author": "Richard B",
"author_id": 30214,
"author_profile": "https://Stackoverflow.com/users/30214",
"pm_score": 0,
"selected": false,
"text": "sSQL = \"DECLARE @RecNo int; EXEC [sp_NewClaim] 'param1', 'param2', etc..... @RecNo OUTPUT; SELECT @RecNo;\"\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38678/"
] |
304,290 | <p>Why do I have to specify <code>runat="server"</code> on all my ASP.NET controls when it is a mandatory attribute and <code>server</code> is the only option available in my limited knowledge of ASP.NET, and I get an error if I don't use it?</p>
<p>I do understand that I can optionally use it on my HTML tags, and I do understand the client/server paradigm and what it is actually specifying.</p>
<p>Is it a redundant tag that could just be implied by the control being an ASP.NET control, or is there an underlying reason?</p>
| [
{
"answer_id": 304306,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 4,
"selected": false,
"text": "<INPUT type=\"submit\" runat=server /> <asp:Button runat=server /> <asp:XXX />"
},
{
"answer_id": 304307,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 8,
"selected": true,
"text": "runat=\"server\" <runat=\"server\"> <asp: /> <runat=\"server\"> <runat=client> <runat=client> runat=server <% <!– #include"
},
{
"answer_id": 22119634,
"author": "pointcounterpoint",
"author_id": 3369195,
"author_profile": "https://Stackoverflow.com/users/3369195",
"pm_score": -1,
"selected": false,
"text": "runat=\"Server\" postback .NET MVC postback \"submit\" MVC JQUERY postback .NET \"runat\" .NET MVC \"runat\" runat"
},
{
"answer_id": 29407449,
"author": "ShaileshDev",
"author_id": 4710577,
"author_profile": "https://Stackoverflow.com/users/4710577",
"pm_score": 2,
"selected": false,
"text": "runat=\"server\""
},
{
"answer_id": 36418164,
"author": "Developer Marius Žilėnas",
"author_id": 1737819,
"author_profile": "https://Stackoverflow.com/users/1737819",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\"> <input type=\"text\" id=\"Textbox1\" runat=\"server\"> runat=\"server\""
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
304,317 | <p>Does MySQL index foreign key columns automatically?</p>
| [
{
"answer_id": 33893061,
"author": "Navrattan Yadav",
"author_id": 3665000,
"author_profile": "https://Stackoverflow.com/users/3665000",
"pm_score": 2,
"selected": false,
"text": "Innodb FOREIGN KEY foreign_key_name CONSTRAINT constraint_name\nFOREIGN KEY foreign_key_name (columns)\nREFERENCES parent_table(columns)\nON DELETE action\nON UPDATE action\n"
},
{
"answer_id": 34448500,
"author": "Ali Raza",
"author_id": 5713574,
"author_profile": "https://Stackoverflow.com/users/5713574",
"pm_score": -1,
"selected": false,
"text": "ALTER TABLE (NAME OF THE TABLE) ADD INDEX (FOREIGN KEY)\n photograph_id ALTER TABLE photographs ADD INDEX (photograph_id);\n"
},
{
"answer_id": 45298357,
"author": "Fahmi",
"author_id": 2363434,
"author_profile": "https://Stackoverflow.com/users/2363434",
"pm_score": 4,
"selected": false,
"text": "5.7"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
304,319 | <p>As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name.</p>
<p>Is there an equivalent to the UNIX command 'which'?</p>
<p>On UNIX, <code>which command</code> prints the full path of the given command to easily find and repair these shadowing problems.</p>
| [
{
"answer_id": 304392,
"author": "RexE",
"author_id": 38146,
"author_profile": "https://Stackoverflow.com/users/38146",
"pm_score": 6,
"selected": false,
"text": "($Env:Path).Split(\";\") | Get-ChildItem -filter programName*\n"
},
{
"answer_id": 304441,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": false,
"text": "where c:\\> for %i in (cmd.exe) do @echo. %~$PATH:i\n C:\\WINDOWS\\system32\\cmd.exe\n\nc:\\> for %i in (python.exe) do @echo. %~$PATH:i\n C:\\Python25\\python.exe\n PATH @echo off\nsetlocal enableextensions enabledelayedexpansion\n\n:: Needs an argument.\n\nif \"x%1\"==\"x\" (\n echo Usage: which ^<progName^>\n goto :end\n)\n\n:: First try the unadorned filenmame.\n\nset fullspec=\ncall :find_it %1\n\n:: Then try all adorned filenames in order.\n\nset mypathext=!pathext!\n:loop1\n :: Stop if found or out of extensions.\n\n if \"x!mypathext!\"==\"x\" goto :loop1end\n\n :: Get the next extension and try it.\n\n for /f \"delims=;\" %%j in (\"!mypathext!\") do set myext=%%j\n call :find_it %1!myext!\n\n:: Remove the extension (not overly efficient but it works).\n\n:loop2\n if not \"x!myext!\"==\"x\" (\n set myext=!myext:~1!\n set mypathext=!mypathext:~1!\n goto :loop2\n )\n if not \"x!mypathext!\"==\"x\" set mypathext=!mypathext:~1!\n\n goto :loop1\n:loop1end\n\n:end\nendlocal\ngoto :eof\n\n:: Function to find and print a file in the path.\n\n:find_it\n for %%i in (%1) do set fullspec=%%~$PATH:i\n if not \"x!fullspec!\"==\"x\" @echo. !fullspec!\n goto :eof\n"
},
{
"answer_id": 304447,
"author": "Michael Ratanapintha",
"author_id": 1879,
"author_profile": "https://Stackoverflow.com/users/1879",
"pm_score": 13,
"selected": true,
"text": "where.exe which cd where nt* %PATH% nt where /? where Where-Object where.exe .exe Set-Alias which where.exe\n Get-Command gcm gcm notepad*\n"
},
{
"answer_id": 304508,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": false,
"text": "which"
},
{
"answer_id": 2520500,
"author": "Mawg says reinstate Monica",
"author_id": 192910,
"author_profile": "https://Stackoverflow.com/users/192910",
"pm_score": 3,
"selected": false,
"text": "program Whence (input, output);\n Uses Dos, my_funk;\n Const program_version = '1.00';\n program_date = '17 March 1994';\n VAR path_str : string;\n command_name : NameStr;\n command_extension : ExtStr;\n command_directory : DirStr;\n search_dir : DirStr;\n result : DirStr;\n\n\n procedure Check_for (file_name : string);\n { Check existence of the passed parameter. If exists, then state so }\n { and exit. }\n begin\n if Fsearch(file_name, '') <> '' then\n begin\n WriteLn('DOS command = ', Fexpand(file_name));\n Halt(0); { structured ? whaddayamean structured ? }\n end;\n end;\n\n function Get_next_dir : DirStr;\n { Returns the next directory from the path variable, truncating the }\n { variable every time. Implicit input (but not passed as parameter) }\n { is, therefore, path_str }\n var semic_pos : Byte;\n\n begin\n semic_pos := Pos(';', path_str);\n if (semic_pos = 0) then\n begin\n Get_next_dir := '';\n Exit;\n end;\n\n result := Copy(Path_str, 1, (semic_pos - 1)); { return result }\n { Hmm! although *I* never reference a Root drive (my directory tree) }\n { is 1/2 way structured), some network logon software which I run }\n { does (it adds Z:\\ to the path). This means that I have to allow }\n { path entries with & without a terminating backslash. I'll delete }\n { anysuch here since I always add one in the main program below. }\n if (Copy(result, (Length(result)), 1) = '\\') then\n Delete(result, Length(result), 1);\n\n path_str := Copy(path_str,(semic_pos + 1),\n (length(path_str) - semic_pos));\n Get_next_dir := result;\n end; { Of function get_next_dir }\n\nbegin\n { The following is a kludge which makes the function Get_next_dir easier }\n { to implement. By appending a semi-colon to the end of the path }\n { Get_next_dir doesn't need to handle the special case of the last entry }\n { which normally doesn't have a semic afterwards. It may be a kludge, }\n { but it's a documented kludge (you might even call it a refinement). }\n path_str := GetEnv('Path') + ';';\n\n if (paramCount = 0) then\n begin\n WriteLn('Whence: V', program_version, ' from ', program_date);\n Writeln;\n WriteLn('Usage: WHENCE command[.extension]');\n WriteLn;\n WriteLn('Whence is a ''find file''type utility witha difference');\n Writeln('There are are already more than enough of those :-)');\n Write ('Use Whence when you''re not sure where a command which you ');\n WriteLn('want to invoke');\n WriteLn('actually resides.');\n Write ('If you intend to invoke the command with an extension e.g ');\n Writeln('\"my_cmd.exe param\"');\n Write ('then invoke Whence with the same extension e.g ');\n WriteLn('\"Whence my_cmd.exe\"');\n Write ('otherwise a simple \"Whence my_cmd\" will suffice; Whence will ');\n Write ('then search the current directory and each directory in the ');\n Write ('for My_cmd.com, then My_cmd.exe and lastly for my_cmd.bat, ');\n Write ('just as DOS does');\n Halt(0);\n end;\n\n Fsplit(paramStr(1), command_directory, command_name, command_extension);\n if (command_directory <> '') then\n begin\nWriteLn('directory detected *', command_directory, '*');\n Halt(0);\n end;\n\n if (command_extension <> '') then\n begin\n path_str := Fsearch(paramstr(1), ''); { Current directory }\n if (path_str <> '') then WriteLn('Dos command = \"', Fexpand(path_str), '\"')\n else\n begin\n path_str := Fsearch(paramstr(1), GetEnv('path'));\n if (path_str <> '') then WriteLn('Dos command = \"', Fexpand(path_str), '\"')\n else Writeln('command not found in path.');\n end;\n end\n else\n begin\n { O.K, the way it works, DOS looks for a command firstly in the current }\n { directory, then in each directory in the Path. If no extension is }\n { given and several commands of the same name exist, then .COM has }\n { priority over .EXE, has priority over .BAT }\n\n Check_for(paramstr(1) + '.com'); { won't return if file is found }\n Check_for(paramstr(1) + '.exe');\n Check_for(paramstr(1) + '.bat');\n\n { Not in current directory, search through path ... }\n\n search_dir := Get_next_dir;\n\n while (search_dir <> '') do\n begin\n Check_for(search_dir + '\\' + paramstr(1) + '.com');\n Check_for(search_dir + '\\' + paramstr(1) + '.exe');\n Check_for(search_dir + '\\' + paramstr(1) + '.bat');\n search_dir := Get_next_dir;\n end;\n\n WriteLn('DOS command not found: ', paramstr(1));\n end;\nend.\n"
},
{
"answer_id": 3917177,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 4,
"selected": false,
"text": "which PATH"
},
{
"answer_id": 13654421,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 6,
"selected": false,
"text": "set-alias which where.exe\n"
},
{
"answer_id": 27140194,
"author": "shalomb",
"author_id": 742600,
"author_profile": "https://Stackoverflow.com/users/742600",
"pm_score": 8,
"selected": false,
"text": "Get-Command $Env:PATH $ Get-Command eventvwr\n\nCommandType Name Definition\n----------- ---- ----------\nApplication eventvwr.exe c:\\windows\\system32\\eventvwr.exe\nApplication eventvwr.msc c:\\windows\\system32\\eventvwr.msc\n which $ sal which gcm # short form of `Set-Alias which Get-Command`\n$ which foo\n...\n .exe .ps1 $Env:PATHEXT Get-Command type -a foo where.exe which.exe $ gcm *disk*\n\nCommandType Name Version Source\n----------- ---- ------- ------\nAlias Disable-PhysicalDiskIndication 2.0.0.0 Storage\nAlias Enable-PhysicalDiskIndication 2.0.0.0 Storage\nFunction Add-PhysicalDisk 2.0.0.0 Storage\nFunction Add-VirtualDiskToMaskingSet 2.0.0.0 Storage\nFunction Clear-Disk 2.0.0.0 Storage\nCmdlet Get-PmemDisk 1.0.0.0 PersistentMemory\nCmdlet New-PmemDisk 1.0.0.0 PersistentMemory\nCmdlet Remove-PmemDisk 1.0.0.0 PersistentMemory\nApplication diskmgmt.msc 0.0.0.0 C:\\WINDOWS\\system32\\diskmgmt.msc\nApplication diskpart.exe 10.0.17... C:\\WINDOWS\\system32\\diskpart.exe\nApplication diskperf.exe 10.0.17... C:\\WINDOWS\\system32\\diskperf.exe\nApplication diskraid.exe 10.0.17... C:\\WINDOWS\\system32\\diskraid.exe\n...\n +x $PATH $PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL Get-Command $ $Env:PATHEXT=\"$Env:PATHEXT;.dll;.ps1;.psm1;.py\" # temporary assignment, only for this shell's process\n\n$ gcm user32,kernel32,*WASM*,*http*py\n\nCommandType Name Version Source\n----------- ---- ------- ------\nExternalScript Invoke-WASMProfiler.ps1 C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\Invoke-WASMProfiler.ps1\nApplication http-server.py 0.0.0.0 C:\\Users\\ME\\AppData\\Local\\Microsoft\\WindowsApps\\http-server.py\nApplication kernel32.dll 10.0.17... C:\\WINDOWS\\system32\\kernel32.dll\nApplication user32.dll 10.0.17... C:\\WINDOWS\\system32\\user32.dll\n Get-Command"
},
{
"answer_id": 31742139,
"author": "Fez",
"author_id": 358704,
"author_profile": "https://Stackoverflow.com/users/358704",
"pm_score": 4,
"selected": false,
"text": "function which {\n get-command $args[0]| format-list\n}\n PS C:\\Users\\fez> which python\n\n\nName : python.exe\nCommandType : Application\nDefinition : C:\\Python27\\python.exe\nExtension : .exe\nPath : C:\\Python27\\python.exe\nFileVersionInfo : File: C:\\Python27\\python.exe\n InternalName:\n OriginalFilename:\n FileVersion:\n FileDescription:\n Product:\n ProductVersion:\n Debug: False\n Patched: False\n PreRelease: False\n PrivateBuild: False\n SpecialBuild: False\n Language:\n"
},
{
"answer_id": 32356641,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 2,
"selected": false,
"text": "where whichr gem install whichr\n"
},
{
"answer_id": 32522462,
"author": "vulcan raven",
"author_id": 863980,
"author_profile": "https://Stackoverflow.com/users/863980",
"pm_score": 4,
"selected": false,
"text": "gcm .Source gcm git (gcm git).Source gcm Get-Command Set-Alias which gcm (which git).Source"
},
{
"answer_id": 36355848,
"author": "automatix",
"author_id": 2019043,
"author_profile": "https://Stackoverflow.com/users/2019043",
"pm_score": 5,
"selected": false,
"text": "which where $ where php\nC:\\Program Files\\PHP\\php.exe\n"
},
{
"answer_id": 39682645,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@echo off\necho. \necho PathFind - Finds the first file in in a path\necho ======== = ===== === ===== ==== == == = ====\necho. \necho Searching for %1 in %path%\necho. \nset a=%~$PATH:1\nIf \"%a%\"==\"\" (Echo %1 not found) else (echo %1 found at %a%)\n set /?"
},
{
"answer_id": 42148912,
"author": "David G",
"author_id": 955978,
"author_profile": "https://Stackoverflow.com/users/955978",
"pm_score": 2,
"selected": false,
"text": "which"
},
{
"answer_id": 45453270,
"author": "hamidreza samsami",
"author_id": 1632944,
"author_profile": "https://Stackoverflow.com/users/1632944",
"pm_score": 3,
"selected": false,
"text": "which app-name\n"
},
{
"answer_id": 50635121,
"author": "Giovanni Bassi",
"author_id": 2723305,
"author_profile": "https://Stackoverflow.com/users/2723305",
"pm_score": 2,
"selected": false,
"text": "which which /usr/bin C:\\Program Files\\Git\\usr\\bin\\which.exe which C:\\Program Files\\Git\\usr\\bin\\which.exe"
},
{
"answer_id": 55970371,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "set a=%~$dir:1\nIf \"%for%\"==\"\" (Echo %1 not found) else (echo %1 found at %a%)\n"
},
{
"answer_id": 58285614,
"author": "bobbogo",
"author_id": 470195,
"author_profile": "https://Stackoverflow.com/users/470195",
"pm_score": 3,
"selected": false,
"text": "C:>type wh.cmd\n@for %%f in (%*) do for %%e in (%PATHEXT% .dll .lnk) do for %%b in (%%f%%e) do for %%d in (%PATH%) do if exist %%d\\%%b echo %%d\\%%b\n C:>wh ssh\nC:\\cygwin64\\bin\\ssh.EXE\nC:\\Windows\\System32\\OpenSSH\\\\ssh.EXE\n setlocal enableextensions endlocal"
},
{
"answer_id": 62732469,
"author": "George Ogden",
"author_id": 12103577,
"author_profile": "https://Stackoverflow.com/users/12103577",
"pm_score": 0,
"selected": false,
"text": "which"
},
{
"answer_id": 63257980,
"author": "FreeSoftwareServers",
"author_id": 5079799,
"author_profile": "https://Stackoverflow.com/users/5079799",
"pm_score": -1,
"selected": false,
"text": "@ECHO OFF\nCLS\n\nFOR /F \"skip=2 tokens=1,2* USEBACKQ\" %%N IN (`reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%~1\" /t REG_SZ /v \"Path\"`) DO (\n IF /I \"%%N\" == \"Path\" (\n SET wherepath=%%P%~1\n GoTo Found\n )\n)\n\nFOR /F \"tokens=* USEBACKQ\" %%F IN (`where.exe %~1`) DO (\n SET wherepath=%%F\n GoTo Found\n)\n\nFOR /F \"tokens=* USEBACKQ\" %%F IN (`where.exe /R \"%PROGRAMFILES%\" %~1`) DO (\n SET wherepath=%%F\n GoTo Found\n)\n\nFOR /F \"tokens=* USEBACKQ\" %%F IN (`where.exe /R \"%PROGRAMFILES(x86)%\" %~1`) DO (\n SET wherepath=%%F\n GoTo Found\n)\n\nFOR /F \"tokens=* USEBACKQ\" %%F IN (`where.exe /R \"%WINDIR%\" %~1`) DO (\n SET wherepath=%%F\n GoTo Found\n)\n\n:Found\nSET %2=%wherepath%\n:End\n @ECHO OFF\nCLS\n\nCALL \"app_path_func.cmd\" WINWORD.EXE PROGPATH\nECHO %PROGPATH%\n\nPAUSE\n C:\\Program Files (x86)\\Microsoft Office\\Office15\\\nPress any key to continue . . .\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34596/"
] |
304,322 | <p>Is there a way I can export my Silverlight DataGrid data to excel or csv?</p>
<p>I searched the web but can't find any examples!</p>
<p>Thanks a lot </p>
| [
{
"answer_id": 353671,
"author": "DaniCE",
"author_id": 19046,
"author_profile": "https://Stackoverflow.com/users/19046",
"pm_score": 2,
"selected": false,
"text": "public String ExportDataGrid(DataGrid grid)\n{\n string colPath;\n System.Reflection.PropertyInfo propInfo;\n System.Windows.Data.Binding binding;\n System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();\n System.Collections.IList source = (grid.DataContext as System.Collections.IList);\n if (source == null)\n return \"\";\n\n foreach (Object data in source)\n {\n foreach (DataGridColumn col in datagrid.Columns)\n {\n if (col is DataGridBoundColumn)\n {\n binding = (col as DataGridBoundColumn).Binding;\n colPath = binding.Path.Path;\n propInfo = data.GetType().GetProperty(colPath);\n if (propInfo != null)\n {\n strBuilder.Append(propInfo.GetValue(data, null).ToString());\n strBuilder.Append(\",\");\n } \n }\n\n }\n strBuilder.Append(\"\\r\\n\");\n }\n\n\n return strBuilder.ToString();\n}\n"
},
{
"answer_id": 511746,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 1,
"selected": false,
"text": "ControlTemplate DataSource Columns GetCellContent foreach (YourType item in grid.DataSource)\n{\n foreach (DataGridColumn column in grid.Columns)\n {\n FrameworkElement cellContent = column.GetCellContent(item);\n\n // Now, determine the type of cell content and act accordingly.\n TextBlock block = cellContent as TextBlock;\n if (block != null)\n {\n // Report text value...\n }\n\n // ...etc...\n\n }\n}\n"
},
{
"answer_id": 1221942,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 4,
"selected": false,
"text": "private void exportHistoryButton_Click(object sender, RoutedEventArgs e) \n{\n string data = ExportDataGrid(true, historyDataGrid);\n SaveFileDialog sfd = new SaveFileDialog()\n {\n DefaultExt = \"csv\",\n Filter = \"CSV Files (*.csv)|*.csv|All files (*.*)|*.*\",\n FilterIndex = 1\n };\n if (sfd.ShowDialog() == true)\n {\n using (Stream stream = sfd.OpenFile())\n {\n using (StreamWriter writer = new StreamWriter(stream)) {\n writer.Write(data);\n writer.Close();\n }\n stream.Close();\n }\n }\n}\n\nprivate string FormatCSVField(string data) {\n return String.Format(\"\\\"{0}\\\"\",\n data.Replace(\"\\\"\", \"\\\"\\\"\\\"\")\n .Replace(\"\\n\", \"\")\n .Replace(\"\\r\", \"\")\n );\n}\n\npublic string ExportDataGrid(bool withHeaders, DataGrid grid)\n{\n string colPath;\n System.Reflection.PropertyInfo propInfo;\n System.Windows.Data.Binding binding;\n System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();\n System.Collections.IList source = (grid.ItemsSource as System.Collections.IList);\n if (source == null)\n return \"\";\n\n List<string> headers = new List<string>();\n grid.Columns.ToList().ForEach(col => {\n if (col is DataGridBoundColumn){\n headers.Add(FormatCSVField(col.Header.ToString()));\n }\n });\n strBuilder\n .Append(String.Join(\",\", headers.ToArray()))\n .Append(\"\\r\\n\");\n\n foreach (Object data in source)\n {\n List<string> csvRow = new List<string>();\n foreach (DataGridColumn col in grid.Columns)\n {\n if (col is DataGridBoundColumn)\n {\n binding = (col as DataGridBoundColumn).Binding;\n colPath = binding.Path.Path;\n propInfo = data.GetType().GetProperty(colPath);\n if (propInfo != null)\n {\n csvRow.Add(FormatCSVField(propInfo.GetValue(data, null).ToString()));\n }\n }\n }\n strBuilder\n .Append(String.Join(\",\", csvRow.ToArray()))\n .Append(\"\\r\\n\");\n }\n\n\n return strBuilder.ToString();\n}\n"
},
{
"answer_id": 4235103,
"author": "Andrew",
"author_id": 514714,
"author_profile": "https://Stackoverflow.com/users/514714",
"pm_score": 2,
"selected": false,
"text": " private static void OpenExcelFile(string Path)\n {\n dynamic excelApp;\n excelApp = AutomationFactory.CreateObject(\"Excel.Application\");\n dynamic workbook = excelApp.workbooks;\n object oMissing = Missing.Value;\n\n workbook = excelApp.Workbooks.Open(Path,\n\n oMissing, oMissing, oMissing, oMissing, oMissing,\n\n oMissing, oMissing, oMissing, oMissing, oMissing,\n\n oMissing, oMissing, oMissing, oMissing);\n\n\n\n dynamic sheet = excelApp.ActiveSheet;\n\n\n // open the existing sheet\n\n\n sheet.Cells.EntireColumn.AutoFit();\n excelApp.Visible = true;\n }\n private static string FormatCSVField(string data)\n {\n return String.Format(\"\\\"{0}\\\"\",\n data.Replace(\"\\\"\", \"\\\"\\\"\\\"\")\n .Replace(\"\\n\", \"\")\n .Replace(\"\\r\", \"\")\n );\n }\n public static string ExportDataGrid(DataGrid grid,string SaveFileName,bool AutoOpen)\n {\n string colPath;\n System.Reflection.PropertyInfo propInfo;\n System.Windows.Data.Binding binding;\n System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();\n var source = grid.ItemsSource;\n\n if (source == null)\n return \"\";\n\n List<string> headers = new List<string>();\n grid.Columns.ToList().ForEach(col =>\n {\n if (col is DataGridBoundColumn)\n {\n headers.Add(FormatCSVField(col.Header.ToString()));\n }\n });\n strBuilder\n .Append(String.Join(\",\", headers.ToArray()))\n .Append(\"\\r\\n\");\n\n foreach (var data in source)\n {\n List<string> csvRow = new List<string>();\n foreach (DataGridColumn col in grid.Columns)\n {\n if (col is DataGridBoundColumn)\n {\n binding = (col as DataGridBoundColumn).Binding;\n colPath = binding.Path.Path;\n\n propInfo = data.GetType().GetProperty(colPath);\n if (propInfo != null)\n {\n string valueConverted = \"\";\n if (binding.Converter.GetType().ToString() != \"System.Windows.Controls.DataGridValueConverter\")\n valueConverted = binding.Converter.Convert(propInfo.GetValue(data, null), typeof(System.String), binding.ConverterParameter, System.Globalization.CultureInfo.CurrentCulture).ToString();\n else\n valueConverted = FormatCSVField(propInfo.GetValue(data, null) == null ? \"\" : propInfo.GetValue(data, null).ToString());\n\n csvRow.Add(valueConverted.ToString());\n }\n }\n }\n strBuilder\n .Append(String.Join(\",\", csvRow.ToArray()))\n .Append(\"\\r\\n\");\n }\n\n if (AutomationFactory.IsAvailable)\n {\n var sampleFile = \"\\\\\" + SaveFileName;\n var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n path += \"\\\\Pement\";\n\n\n if (!System.IO.Directory.Exists(path))\n {\n System.IO.Directory.CreateDirectory(path);\n }\n else\n {\n var files = System.IO.Directory.EnumerateFiles(path);\n foreach (var item in files)\n {\n try\n {\n System.IO.File.Delete(item);\n }\n catch { }\n }\n }\n\n StreamWriter sw = File.CreateText(path + sampleFile);\n sw.WriteLine(strBuilder.ToString());\n sw.Close();\n\n if (AutoOpen)\n OpenExcelFile(path + sampleFile, true, true);\n }\n else\n {\n SaveFileDialog sfd = new SaveFileDialog()\n {\n DefaultExt = \"csv\",\n Filter = \"CSV Files (*.csv)|*.csv|All files (*.*)|*.*\",\n FilterIndex = 1\n };\n if (sfd.ShowDialog() == true)\n {\n using (Stream stream = sfd.OpenFile())\n {\n using (StreamWriter writer = new StreamWriter(stream))\n {\n writer.Write(strBuilder.ToString());\n writer.Close();\n }\n stream.Close();\n }\n } \n }\n return strBuilder.ToString();\n }\n"
},
{
"answer_id": 5222389,
"author": "VenerableAgents",
"author_id": 585006,
"author_profile": "https://Stackoverflow.com/users/585006",
"pm_score": 1,
"selected": false,
"text": " public void SaveAs(string csvPath)\n {\n string data = ExportDataGrid(true, _flexGrid);\n StreamWriter sw = new StreamWriter(csvPath, false, Encoding.UTF8);\n sw.Write(data);\n sw.Close();\n }\n\n public string ExportDataGrid(bool withHeaders, Microsoft.Windows.Controls.DataGrid grid) \n {\n System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();\n System.Collections.IEnumerable source = (grid.ItemsSource as System.Collections.IEnumerable);\n\n if (source == null) return \"\";\n\n List<string> headers = new List<string>();\n\n grid.Columns.ToList().ForEach(col =>\n {\n if (col is Microsoft.Windows.Controls.DataGridBoundColumn)\n {\n headers.Add(col.Header.ToString());\n }\n });\n\n strBuilder.Append(String.Join(\",\", headers.ToArray())).Append(\"\\r\\n\");\n foreach (Object data in source)\n {\n System.Data.DataRowView d = (System.Data.DataRowView)data;\n strBuilder.Append(String.Join(\",\", d.Row.ItemArray)).Append(\"\\r\\n\");\n }\n\n return strBuilder.ToString();\n }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,323 | <p>What is the best way to integrate an external script into the Zend Framework? Let me explain because I may be asking this the wrong way. I have a script that downloads and parses an XML file. This script, which runs as a daily cron job, needs to dump its data into the database.</p>
<p>I am using Zend Framework for the site which uses this script and it seems to me that it would be best to use my subclassed model of <code>Zend_Db_Abstract</code> to do the adding and updating of the database. How does one go about doing this? Does my script go in the library next to the Zend Components (i.e. library/Mine/Xmlparse.php) and thus have access to the various ZF components? Do I simply need to include the correct model files and the Zend DB component in the file itself? What is the best way to handle this sort of integration?</p>
| [
{
"answer_id": 304838,
"author": "smack0007",
"author_id": 26566,
"author_profile": "https://Stackoverflow.com/users/26566",
"pm_score": 1,
"selected": false,
"text": "require_once('Zend/Loader.php');\nZend_Loader::registerAutoload();\n"
},
{
"answer_id": 305761,
"author": "Sebastian Hoitz",
"author_id": 9535,
"author_profile": "https://Stackoverflow.com/users/9535",
"pm_score": 2,
"selected": false,
"text": "My_Db_Abstract will map to My/Db/Abstract.php .\n"
},
{
"answer_id": 1485650,
"author": "David Weinraub",
"author_id": 131824,
"author_profile": "https://Stackoverflow.com/users/131824",
"pm_score": 1,
"selected": false,
"text": "class App_Model_User App/Model/User.php public/index.php APPLICATION_PATH public/index.php Application Bootstrap $application->run();"
},
{
"answer_id": 1485683,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 3,
"selected": true,
"text": "require_once 'Zend/Loader/Autoloader.php';\n$loader = Zend_Loader_Autoloader::getInstance();\n$loader->registerNamespace('Project_');\n$loader->setFallbackAutoloader(true);\nif ($configSection == 'development')\n{\n $loader->suppressNotFoundWarnings(false);\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
] |
304,356 | <p>I've written a script which takes the summary of an order and stores in into an XML file, except the problem is that I don't want people to be able to open the XML file in their browser, obviously.</p>
<p>I'm hosted on a very dodgy shared server with limited abilities: no SSH, for starters.</p>
<p><strong>Is there a place I can put this file so that PHP will still be able to read/write to it, but web browsers won't be able to get to it?</strong></p>
<p>Ordinarily, I'd create a folder outside the document root and put it there, but I get a "Permission denied" message when I try that.</p>
<p>The folders which <em>are</em> there are:</p>
<ul>
<li>anon_ftp</li>
<li>bin</li>
<li>cert</li>
<li>cgi-bin</li>
<li>conf</li>
<li>error_docs</li>
<li>etc</li>
<li>httpdocs</li>
<li>httpsdocs</li>
<li>pd</li>
<li>private</li>
<li>statistics</li>
<li>subdomains</li>
<li>web_users</li>
</ul>
<p>PHP can't access the file when it's in the <code>private</code> folder. Would this be possible using .htaccess?</p>
| [
{
"answer_id": 304380,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": true,
"text": "<Files ~ \"myfile.xml\">\n Order allow,deny\n Deny from all\n</Files>\n"
},
{
"answer_id": 304439,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 3,
"selected": false,
"text": ".htaccess Deny from all\n Limit AllowOverride"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
304,371 | <p>I'm looking to get some help on using the <a href="http://malsup.com/jquery/cycle/" rel="nofollow noreferrer">cycle</a> library for jQuery. I'm in the <a href="http://malsup.com/jquery/cycle/begin.html" rel="nofollow noreferrer">beginner</a> demos, and I got the absolute first one completed. This is the second one on the page.</p>
<pre><code><script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.cycle.all.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.pics').cycle({
fx: 'scrollDown',
speed: 300,
timeout: 2000
});
</script>
</code></pre>
<p>My CSS is identical to the one on the page, that's why I put .pics in the quotes.</p>
| [
{
"answer_id": 304475,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function() { \n $('.pics').cycle({ \n fx: 'scrollDown', \n speed: 300, \n timeout: 2000 \n });\n});\n"
},
{
"answer_id": 309975,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n\n$(document).ready(function() {\n $('.text')\n .before('<div id=\"slidenav\">')\n .cycle({\n fx: 'fade',\n speed: 'slow',\n timeout: 6000,\n pager: '#slidenav',\n pause: 1\n });\n});\n\n</script>\n <div id=\"featured\">\n <div class=\"text\">\n <txp:article_custom form=\"slidetext\" section=\"slide\" limit=\"5\" />\n </div>\n</div>\n .text { width: 600px; height: 200px; border: 1px solid #ddd; background-color: green; }\n.text div { width: 500px; height: 200px; padding: 15px; color: #333; text-align: left; font-size: 16px; background-color:red; }\n.text div img {width: 200px; height: 200px; padding: 3px; background: orange }\n.text div p{ background-color:black;}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,373 | <p>I have the following .aspx page, and I want to view it in web browsers such as IE or Google Chrome by opening it directly in those browsers:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
</code></pre>
<p>But somehow the browsers can't render it. In IE, the error is </p>
<blockquote>
<p>Cannot view XML input using XSL style
sheet. Please correct the error and
then click the Refresh button, or try
again later. A name was started with
an invalid character. Error processing
resource 'file:/</p>
</blockquote>
<pre><code> <%@ Page Language="C#"AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> -^*
</code></pre>
<p>What did I do wrong?</p>
| [
{
"answer_id": 304379,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 3,
"selected": true,
"text": "%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"WebApplication1._Default\" %>"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
304,383 | <p>Is there a way to edit the log message of a certain revision in Subversion? I accidentally wrote the wrong filename in my commit message which could be confusing later.</p>
<p>I've seen <em><a href="https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git">How do I edit an incorrect commit message in Git?</a></em>, but the solution to that question doesn't seem to be similar for Subversion (according to <code>svn help commit</code>).</p>
| [
{
"answer_id": 304390,
"author": "Kamil Kisiel",
"author_id": 15061,
"author_profile": "https://Stackoverflow.com/users/15061",
"pm_score": 10,
"selected": true,
"text": "$svn propedit -r N --revprop svn:log URL \n$svn propset -r N --revprop svn:log \"new log message\" URL \n $ svnadmin setlog REPOS_PATH -r N FILE\n"
},
{
"answer_id": 304394,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt\n"
},
{
"answer_id": 304894,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 4,
"selected": false,
"text": "svn propedit --revprop -r 1234 svn:log url://to/repository\n"
},
{
"answer_id": 742472,
"author": "mcqwerty",
"author_id": 2115,
"author_profile": "https://Stackoverflow.com/users/2115",
"pm_score": 6,
"selected": false,
"text": "svn propedit svn:log --revprop -r N --editor-cmd vim\n"
},
{
"answer_id": 1015407,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": 7,
"selected": false,
"text": "svn propedit svn:log --revprop -r NNN \n cd ~/svn/reponame/hooks\n mv pre-revprop-change.tmpl pre-revprop-change\n chmod 755 pre-revprop-change\n pre-revprop-change.bat"
},
{
"answer_id": 11848436,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 2,
"selected": false,
"text": "REPOS_PATH svn-commit.tmp svn propedit -r N --revprop svn:log svn:log pre-revprop-change svn info ~/svnrepo cd ~/svnrepo/hooks pre-revprop-change pre-revprop-change.bat svn:log pre-revprop-change.bat copy con pre-revprop-change.bat\n^Z\n echo '#!/bin/sh' > pre-revprop-change\nchmod +x pre-revprop-change\n svn propedit -r N --revprop svn:log ~/svnrepo/hooks/svn-revprop-change .bat"
},
{
"answer_id": 18005347,
"author": "Josh Weatherly",
"author_id": 57592,
"author_profile": "https://Stackoverflow.com/users/57592",
"pm_score": 4,
"selected": false,
"text": "pre-revprop-change.bat @ECHO OFF\n\nset repos=%1\nset rev=%2\nset user=%3\nset propname=%4\nset action=%5\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow changes to svn:log. The author, date and other revision\n:: properties cannot be changed\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%propname%'=='svn:log' goto ERROR_PROPNAME\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow modifications to svn:log (no addition/overwrite or deletion)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%action%'=='M' goto ERROR_ACTION\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow user to modify their own log messages\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset AUTHOR=\nfor /f \"delims=\" %%a in ('svnlook author -r %REV% %REPOS%') do @set AUTHOR=%%a\n\nif /I not '%AUTHOR%'=='%user%' goto ERROR_WRONGUSER\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow user to modify log messages from today, old messages locked down\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset DATESTAMP=\nfor /f \"delims=\" %%a in ('svnlook date -r %REV% %REPOS%') do @set DATESTAMP=%%a\n\nfor /F \"tokens=1-2 delims= \" %%a in (\"%DATESTAMP%\") do (\n set DATESTAMPDATE=%%a\n set DATESTAMPTIME=%%b )\n\n:: Expects DATESTAMPDATE in the format: 2012-02-24\nfor /F \"tokens=1-3 delims=-\" %%a in (\"%DATESTAMPDATE%\") do (\n set DATESTAMPYEAR=%%a\n set DATESTAMPMONTH=%%b\n set DATESTAMPDAY=%%c )\n\n:: Expects date in the format: Thu 08/01/2013\nfor /F \"tokens=1-4 delims=/ \" %%a in (\"%date%\") do (\n set YEAR=%%d\n set MONTH=%%b\n set DAY=%%c )\n\nif /I not '%DATESTAMPYEAR%'=='%YEAR%' goto ERROR_MSGTOOOLD\nif /I not '%DATESTAMPMONTH%'=='%MONTH%' goto ERROR_MSGTOOOLD\nif /I not '%DATESTAMPDAY%'=='%DAY%' goto ERROR_MSGTOOOLD\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (\n set bIsEmpty=false\n)\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\ngoto :eof\n\n:ERROR_EMPTY\necho Empty svn:log properties are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_WRONGUSER\necho You are not allowed to modify other user's log messages. >&2\ngoto ERROR_EXIT\n\n:ERROR_MSGTOOOLD\necho You are not allowed to modify log messages older than today. >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1 \n"
},
{
"answer_id": 20784016,
"author": "mani_nz",
"author_id": 1095863,
"author_profile": "https://Stackoverflow.com/users/1095863",
"pm_score": 4,
"selected": false,
"text": "Right click on the project -> Team - Show history\n right click on the revision id for your commit and select 'Set commit properties'"
},
{
"answer_id": 71945337,
"author": "Andrius R.",
"author_id": 5050045,
"author_profile": "https://Stackoverflow.com/users/5050045",
"pm_score": 1,
"selected": false,
"text": "pre-revprop-change @ECHO OFF\n\nset reposPath=%1\nset rev=%2\nset user=%3\nset propName=%4\nset action=%5\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow changes to svn:log. The author, date and other revision\n:: properties cannot be changed\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%propName%'=='svn:log' goto ERROR_PROPNAME\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow modifications to svn:log (no addition/overwrite or deletion)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%action%'=='M' goto ERROR_ACTION\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow user to modify their own log messages\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset author=\nfor /f \"delims=\" %%a in ('svnlook author -r %rev% %reposPath%') do set author=%%a\n\nif /I not '%author%'=='%user%' goto ERROR_WRONGUSER\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow user to modify log messages from today, old messages locked down\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset minDate=\nset revDate=\nset revDateStr=\nfor /f \"delims=\" %%a in ('svnlook date -r %rev% %reposPath%') do set revDateStr=%%a\n\n:: Expects revDateStr in the format: 2012-02-24 ...\n:: https://svnbook.red-bean.com/en/1.7/svn.ref.svnlook.c.date.html\nfor /F \"tokens=1-3 delims=- \" %%a in (\"%revDateStr%\") do set revDate=%%a%%b%%c\n:: Note that PowerShell calls like this can be slow and a window can show up while they run.\nfor /f %%i in ('\"powershell (Get-Date).AddDays(-1).ToString(\\\"yyyyMMdd\\\")\"') do set minDate=%%i\nif \"%revDate%\" LSS \"%minDate%\" goto ERROR_MSGTOOOLD\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do set bIsEmpty=false\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\ngoto :eof\n\n:ERROR_EMPTY\necho Empty svn:log properties are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_WRONGUSER\necho You are not allowed to modify other user's log messages. >&2\ngoto ERROR_EXIT\n\n:ERROR_MSGTOOOLD\necho You are not allowed to modify log messages that are too old (2+ days). >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
304,384 | <p>How do I compare two images & recognize the pattern in an image irrespective of its size and pattern size, and using .Net C#? Also, which algorithms are used for doing so from Image Processing?</p>
| [
{
"answer_id": 9443757,
"author": "Mandah Mr.",
"author_id": 1228884,
"author_profile": "https://Stackoverflow.com/users/1228884",
"pm_score": 1,
"selected": false,
"text": " ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f);\n // find all matchings with specified above similarity\n\n TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template);\n // highlight found matchings\n\n BitmapData data = sourceImage.LockBits(\n new Rectangle(0, 0, sourceImage.Width, sourceImage.Height),\n ImageLockMode.ReadWrite, sourceImage.PixelFormat);\n foreach (TemplateMatch m in matchings)\n {\n\n Drawing.Rectangle(data, m.Rectangle, Color.White);\n\n MessageBox.Show(m.Rectangle.Location.ToString());\n // do something else with matching\n }\n sourceImage.UnlockBits(data);\n enter code here"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,386 | <p>I am trying to develop a plug-in for <a href="http://trac.webkit.org/wiki/QtWebKit" rel="nofollow noreferrer">QtWebkit</a>. But I am not able to find how to develop a plugin for QtWebKit, hopefully one that can be invoked by JavaScript. Does anyone know of any tutorials or documents that explain how to do this?</p>
<p>Webkit has been intregated into Qt and this integrated package is called QtWebkit. They have provided new method for for plugin creation.</p>
<p>-Regards, Vivek Gupta</p>
| [
{
"answer_id": 420163,
"author": "Henrik Hartz",
"author_id": 50830,
"author_profile": "https://Stackoverflow.com/users/50830",
"pm_score": 2,
"selected": false,
"text": "QWebPage webview createPlugin protected:\n QObject* createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues)\n {\n if (classid==\"lineedit\") {\n QLineEdit *lineedit = new QLineEdit;\n return lineedit;\n }\n return 0;\n}\n <object type=\"application/x-qt-plugin\" classid=\"lineedit\" id=\"lineedit\">\ncan't load plugin\n</object>\n QWebSettings QWebPluginFactory"
},
{
"answer_id": 8020425,
"author": "Kurt Pattyn",
"author_id": 52568,
"author_profile": "https://Stackoverflow.com/users/52568",
"pm_score": 0,
"selected": false,
"text": "this->mainFrame()->addToJavaScriptWindowObject(\"lineedit\", this);\n lineedit"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,389 | <p>In VB.NET, which is better to use: function overloading or default parameters?</p>
| [
{
"answer_id": 304484,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "Process ProcessStartInfo Person jon = new Person.Builder { Name=\"Jon\", Age=32,\n Spouse=\"Holly\", Kids=3 }.Build();\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
304,391 | <p>Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?</p>
<p>Note: I am rewriting an existing system that is painfully slow.</p>
| [
{
"answer_id": 304411,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "$string = '0123456789012345';\n$sets = str_split($string, 4);\nprint_r($sets);\n Array\n(\n [0] => 0123\n [1] => 4567\n [2] => 8901\n [3] => 2345\n)\n echo implode('-', $sets); // echoes '0123-4567-8901-2345'\n"
},
{
"answer_id": 312070,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 0,
"selected": false,
"text": "preg_replace('/^(\\d{4})(\\d{4})(\\d{4})(\\d{4})$/', '\\1-\\2-\\3-\\4', '0123456789012345');\n"
},
{
"answer_id": 312742,
"author": "Hugh Bothwell",
"author_id": 33258,
"author_profile": "https://Stackoverflow.com/users/33258",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n// arr[string] = strChunk(string, length [, length [...]] );\nfunction strChunk() {\n $n = func_num_args();\n $str = func_get_arg(0);\n $ret = array();\n\n if ($n >= 2) {\n for($i=1, $offs=0; $i<$n; ++$i) {\n $chars = abs( func_get_arg($i) );\n $ret[] = substr($str, $offs, $chars);\n $offs += $chars;\n }\n }\n\n return $ret;\n}\n\necho join('-', strChunk('0123456789012345', 4, 4, 4, 4) );\n\n?>\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
304,393 | <p>One of the <a href="http://www.sqlite.org/whentouse.html" rel="noreferrer">appropriate uses</a> for <a href="http://www.sqlite.org" rel="noreferrer">sqlite3</a> is "in-memory databases". This sounds like a really useful tool for my C++ applications. Does anyone have an example of how this is done in C or C++? I'm specifically looking for a canonical way to slurp several flat-files into an in-memory database, then do some joins.</p>
| [
{
"answer_id": 304402,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "ATTACH foo.db AS foo\n SELECT * FROM foo.users\n"
},
{
"answer_id": 333057,
"author": "Danielb",
"author_id": 39040,
"author_profile": "https://Stackoverflow.com/users/39040",
"pm_score": 3,
"selected": false,
"text": "PRAGMA temp_store=MEMORY;\nPRAGMA journal_mode=MEMORY;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167/"
] |
304,396 | <p>I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order. Can anyone help?</p>
<p>Here is a sample list for people to work with:</p>
<pre><code><ul class="alphaList">
<li>apples</li>
<li>cats</li>
<li>bears</li>
</ul>
</code></pre>
| [
{
"answer_id": 304428,
"author": "Chatu",
"author_id": 39203,
"author_profile": "https://Stackoverflow.com/users/39203",
"pm_score": 8,
"selected": true,
"text": "var items = $('.alphaList > li').get();\nitems.sort(function(a,b){\n var keyA = $(a).text();\n var keyB = $(b).text();\n\n if (keyA < keyB) return -1;\n if (keyA > keyB) return 1;\n return 0;\n});\nvar ul = $('.alphaList');\n$.each(items, function(i, li){\n ul.append(li); /* This removes li from the old spot and moves it */\n});\n"
},
{
"answer_id": 18784256,
"author": "Ergec",
"author_id": 153723,
"author_profile": "https://Stackoverflow.com/users/153723",
"pm_score": 3,
"selected": false,
"text": "$('.submenu > li').tsort({\n charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'\n});\n $('.submenu > li').tsort();\n tinysort('.submenu > li', {\n charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'\n});\n"
},
{
"answer_id": 40238823,
"author": "berniecc",
"author_id": 1898287,
"author_profile": "https://Stackoverflow.com/users/1898287",
"pm_score": 3,
"selected": false,
"text": "var elems = $('.alphalist li').detach().sort(function (a, b) {\n return ($(a).text() < $(b).text() ? -1 \n : $(a).text() > $(b).text() ? 1 : 0);\n}); \n$('.alphalist').append(elems);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
304,430 | <p>When running the following code it leaves out one row. When I do a files.Count it says there are 4 rows but there is no data stored for the 4th row. When I run the stored procedure from within SQL Manager it returns all 4 rows and all the data. Any help?</p>
<pre><code> List<File> files = new List<File>();
SqlConnection active_connection = new SqlConnection(m_connection_string);
SqlCommand cmd = new SqlCommand();
SqlDataReader dr = null;
try
{
active_connection.Open();
cmd.Connection = active_connection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dalsp_Select_Organization_Files";
SqlParameter param;
param = cmd.Parameters.Add("@p_organization_guid", SqlDbType.UniqueIdentifier);
param.Value = new Guid(organization_guid);
param = cmd.Parameters.Add("@p_file_type", SqlDbType.NVarChar, 50);
param.Value = file_type;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
File file = new File();
file.OrganizationGuid = dr["OrganizationGuid"].ToString();
file.FileGuid = dr["FileGuid"].ToString();
file.FileLocation = dr["FileLocation"].ToString();
file.FileName = dr["FileName"].ToString();
file.FileType = (FileTypeEnum)Enum.Parse(typeof(FileTypeEnum), dr["FileType"].ToString());
file.FileExtension = dr["FileExtension"].ToString();
file.FileDescription = dr["FileDescription"].ToString();
file.ThumbnailPath = dr["ThumbnailPath"].ToString();
files.Add(file);
}
}
dr.Close();
dr = null;
active_connection.Close();
cmd = null;
}
catch (Exception)
{
throw;
}
finally
{
if (active_connection.State != ConnectionState.Closed)
{
active_connection.Close();
active_connection.Dispose();
}
}
return files;
</code></pre>
| [
{
"answer_id": 304465,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 1,
"selected": false,
"text": "SqlParameter param = new SqlParameter(); \n// set param stuff - here or in ctor \ncmd.Parameters.Add(param); \n"
},
{
"answer_id": 304479,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 4,
"selected": true,
"text": "for(int x = 1; x < files.length; x++)\n{\n files[x]\n}\n using (SqlConnection connection = new SqlConnection(conn_string))\n{\n connection.Open();\n using (SqlCommand cmd = new SqlCommand(\"SELECT * FROM MyTable\", connection))\n {\n using (SqlDataReader dr = cmd.ExecuteReader())\n {\n return result;\n }\n }\n}\n"
},
{
"answer_id": 304647,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 2,
"selected": false,
"text": "using (SqlCommand cmd = new SqlCommand()) {\n //use the connection\n}\n catch (Exception) { throw; } \n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36798/"
] |
304,451 | <p>I'm trying to avoid code like this when reusing the same ViewUserControl in ASP.NET MVC. Any suggestions?</p>
<pre><code><% if (ViewContext.ViewData["editMode"].ToString() == "edit"){ %>
<%= Html.SubmitButton("submit", "Update Brand")%><span class="or">Or</span><a href="#" class="cancel">Cancel</a>
<% } else { %>
<%= Html.SubmitButton("submit", "Create New Brand")%><span class="or">Or</span><a href="#" class="cancel">Cancel</a>
<%} %>
</code></pre>
<p>And ...</p>
<pre><code><% if (ViewContext.ViewData["editMode"].ToString() == "edit"){ %>
<h1 class="edit">Edit Brand Details</h1>
<% } else { %>
<h1 class="create">Create A New Brand</h1>
<%} %>
</code></pre>
| [
{
"answer_id": 401913,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<% string submitLabel = (ViewData[\"editMode\"].ToString() == \"edit\") ? \"Update Brand\" : \"Create New Brand\" %>\n<%= Html.SubmitButton(\"submit\", submitLabel)%><span class=\"or\">Or</span><a href=\"#\" class=\"cancel\">Cancel</a>\n <% \n string submitLabel = (ViewData[\"editMode\"].ToString() == \"edit\") ? \"Update Brand\" : \"Create New Brand\";\n string h1Class = (ViewData[\"editMode\"].ToString() == \"edit\") ? \"edit\" : \"create\";\n string h1Label = (ViewData[\"editMode\"].ToString() == \"edit\") ? \"Edit Brand Details\" : \"Create a New Brand\";\n%>\n\n\n<h1 class=\"<%= h1Class %>\"><%= h1Label %></h1>\n"
},
{
"answer_id": 767891,
"author": "Nasser",
"author_id": 86627,
"author_profile": "https://Stackoverflow.com/users/86627",
"pm_score": 3,
"selected": false,
"text": "<asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n<%= Html.ValidationSummary(\"Create was unsuccessful. Please correct the errors and try again.\") %>\n<% using (Html.BeginForm())\n { %>\n<fieldset>\n <legend>Create a new contact</legend>\n <div id=\"pagecontent\">\n <div id=\"left\">\n </div>\n <div id=\"center\">\n <% Html.RenderPartial(\"PersonalInfo\", Model); %>\n </div>\n </div>\n\n <p>\n <input type=\"submit\" value=\"Create\" />\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n<%= Html.ValidationSummary(\"Edit was unsuccessful. Please correct the errors and try again.\") %>\n<% using (Html.BeginForm())\n { %>\n<fieldset>\n <legend>Edit existing contact</legend>\n <div id=\"pagecontent\">\n <div id=\"left\">\n <% Html.RenderPartial(\"IdChange\", Model); %>\n </div>\n <div id=\"center\">\n <% Html.RenderPartial(\"PersonalInfo\", Model); %>\n </div>\n </div>\n\n <p>\n <input type=\"submit\" value=\"Edit\" />\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34133/"
] |
304,461 | <p>I need to do a join with a table/result-set/whatever that has the integers <code>n</code> to <code>m</code> inclusive. Is there a trivial way to get that without just building the table?</p>
<p>(BTW what would that type of construct be called, a "<em>Meta query</em>"?)</p>
<p><code>m-n</code> is bounded to something reasonable ( < 1000's)</p>
| [
{
"answer_id": 304644,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 5,
"selected": true,
"text": "AUTO_INCREMENT"
},
{
"answer_id": 304711,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "create table two select null foo union all select null;\ncreate temporary table seq ( foo int primary key auto_increment ) auto_increment=9 select a.foo from two a, two b, two c, two d;\nselect * from seq where foo <= 23;\n"
},
{
"answer_id": 307986,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "select 9 colname union all select 10 union all select 11 union all select 12 union all select 13 ...\n"
},
{
"answer_id": 400978,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 3,
"selected": false,
"text": "SELECT @rn:=@rn+1 as n\nFROM (select @rn:=2)t, `order` rows_1, `order` rows_2 --, rows_n as needed...\nLIMIT 4\n order"
},
{
"answer_id": 401097,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 1,
"selected": false,
"text": "mysql> CREATE TABLE `tmp_keys` (`k` INTEGER UNSIGNED, PRIMARY KEY (`k`));\nQuery OK, 0 rows affected (0.11 sec)\n\nmysql> INSERT INTO `tmp_keys` VALUES (0),(1),(2),(3),(4),(5),(6),(7);\nQuery OK, 8 rows affected (0.03 sec)\nRecords: 8 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+8 from `tmp_keys`;\nQuery OK, 8 rows affected (0.02 sec)\nRecords: 8 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+16 from `tmp_keys`;\nQuery OK, 16 rows affected (0.03 sec)\nRecords: 16 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+32 from `tmp_keys`;\nQuery OK, 32 rows affected (0.03 sec)\nRecords: 32 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+64 from `tmp_keys`;\nQuery OK, 64 rows affected (0.03 sec)\nRecords: 64 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+128 from `tmp_keys`;\nQuery OK, 128 rows affected (0.05 sec)\nRecords: 128 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+256 from `tmp_keys`;\nQuery OK, 256 rows affected (0.03 sec)\nRecords: 256 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO `tmp_keys` SELECT k+512 from `tmp_keys`;\nQuery OK, 512 rows affected (0.11 sec)\nRecords: 512 Duplicates: 0 Warnings: 0\n\nmysql> INSERT INTO inttable SELECT k+10000 FROM `tmp_keys` WHERE k<700;\nQuery OK, 700 rows affected (0.16 sec)\nRecords: 700 Duplicates: 0 Warnings: 0\n"
},
{
"answer_id": 904110,
"author": "David Poor",
"author_id": 111796,
"author_profile": "https://Stackoverflow.com/users/111796",
"pm_score": 7,
"selected": false,
"text": "SET @row := 0;\nSELECT @row := @row + 1 as row, t.*\nFROM some_table t, (SELECT @row := 0) r\n @row"
},
{
"answer_id": 2652051,
"author": "Unreason",
"author_id": 207036,
"author_profile": "https://Stackoverflow.com/users/207036",
"pm_score": 5,
"selected": false,
"text": "SELECT @row := @row + 1 AS row FROM \n(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,\n(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, \n(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, \n(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4, \n(SELECT @row:=0) numbers;\n"
},
{
"answer_id": 4872738,
"author": "CorvusCorax",
"author_id": 599745,
"author_profile": "https://Stackoverflow.com/users/599745",
"pm_score": 3,
"selected": false,
"text": "SELECT 0 as b UNION SELECT 1 as b;\n CREATE VIEW ViewBoolean AS SELECT 0 as b UNION SELECT 1 as b;\n CREATE VIEW ViewByteValues AS\nSELECT b0.b + b1.b*2 + b2.b*4 + b3.b*8 + b4.b*16 + b5.b*32 + b6.b*64 + b7.b*128 as v FROM\nViewBoolean b0,ViewBoolean b1,ViewBoolean b2,ViewBoolean b3,ViewBoolean b4,ViewBoolean b5,ViewBoolean b6,ViewBoolean b7;\n CREATE VIEW ViewInt16 AS\nSELECT b0.v + b1.v*256 as v FROM\nViewByteValues b0,ViewByteValues b1;\n SELECT v+MIN as x FROM ViewInt16 WHERE v<MAX-MIN;\n CREATE VIEW ViewByteValues AS\nSELECT 0 as v UNION SELECT 1 as v UNION SELECT ...\n...\n...254 as v UNION SELECT 255 as v;\n SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE v<NumDays;\n SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE day<'end_date';\n SELECT MAKEDATE(start_year,1+v) as day FRON ViewInt16 WHERE day>'start_date' AND day<'end_date';\n SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM\nViewByteValues b0,\nViewByteValues b1,\nViewByteValues b2,\nViewByteValues b3\nWHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < MAX-MIN;\n SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM\nViewByteValues b0\nINNER JOIN ViewByteValues b1 ON (b1.v*256<(MAX-MIN))\nINNER JOIN ViewByteValues b2 ON (b2.v*65536<(MAX-MIN))\nINNER JOIN ViewByteValues b3 ON (b3.v*16777216<(MAX-MIN)\nWHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < (MAX-MIN);\n"
},
{
"answer_id": 38394562,
"author": "Tobia",
"author_id": 517371,
"author_profile": "https://Stackoverflow.com/users/517371",
"pm_score": 2,
"selected": false,
"text": "select ((((((b7.0 << 1 | b6.0) << 1 | b5.0) << 1 | b4.0) \n << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n\nfrom (select 0 union all select 1) as b0,\n (select 0 union all select 1) as b1,\n (select 0 union all select 1) as b2,\n (select 0 union all select 1) as b3,\n (select 0 union all select 1) as b4,\n (select 0 union all select 1) as b5,\n (select 0 union all select 1) as b6,\n (select 0 union all select 1) as b7\n"
},
{
"answer_id": 39918568,
"author": "lynx_74",
"author_id": 3342245,
"author_profile": "https://Stackoverflow.com/users/3342245",
"pm_score": 3,
"selected": false,
"text": "SELECT e*10000+d*1000+c*100+b*10+a n FROM\n(select 0 a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t1,\n(select 0 b union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,\n(select 0 c union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3,\n(select 0 d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,\n(select 0 e union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t5\norder by 1\n select * from (\n select 121 id\n union all select 123\n union all select 125\n union all select 126\n union all select 127\n union all select 128\n union all select 129\n) a\nright join (\n SELECT e*10000+d*1000+c*100+b*10+a n FROM\n (select 0 a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t1,\n (select 0 b union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,\n (select 0 c union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3,\n (select 0 d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,\n (select 0 e union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t5\n order by 1\n) seq on seq.n=a.id\nwhere seq.n between 121 and 129\nand id is null\n id n\n---- ---\nnull 122\nnull 124\n"
},
{
"answer_id": 41532888,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 5,
"selected": false,
"text": "SEQUENCE SELECT seq FROM seq_1_to_1000;\n SELECT seq FROM seq_0_to_11;\n SELECT FROM_DAYS(seq + TO_DAYS(CURDATE)) dateseq FROM seq_0_to_6\n DATE SELECT FROM_DAYS(seq + TO_DAYS('2010-01-01')) dateseq\n FROM seq_0_to_3800\n WHERE FROM_DAYS(seq + TO_DAYS('2010-01-01')) < '2010-01-01' + INTERVAL 10 YEAR\n"
},
{
"answer_id": 42534412,
"author": "George Polevoy",
"author_id": 177317,
"author_profile": "https://Stackoverflow.com/users/177317",
"pm_score": 2,
"selected": false,
"text": "select\n i0.i\n +i1.i*2\n +i2.i*4\n +i3.i*8\n +i4.i*16\n +i5.i*32\n +i6.i*64\n +i7.i*128\n +i8.i*256\n +i9.i*512\n as i\nfrom\n (select 0 as i union select 1) as i0\n cross join (select 0 as i union select 1) as i1\n cross join (select 0 as i union select 1) as i2\n cross join (select 0 as i union select 1) as i3\n cross join (select 0 as i union select 1) as i4\n cross join (select 0 as i union select 1) as i5\n cross join (select 0 as i union select 1) as i6\n cross join (select 0 as i union select 1) as i7\n cross join (select 0 as i union select 1) as i8\n cross join (select 0 as i union select 1) as i9\n"
},
{
"answer_id": 51420474,
"author": "simhumileco",
"author_id": 4217744,
"author_profile": "https://Stackoverflow.com/users/4217744",
"pm_score": 2,
"selected": false,
"text": "SET @seq := 0;\nSELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*\nFROM your_table yt;\n SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*\nFROM (SELECT @seq := 0) s, your_table yt;\n FLOOR() INTEGER FLOAT"
},
{
"answer_id": 54688139,
"author": "Ajay Venkata Raju",
"author_id": 9634563,
"author_profile": "https://Stackoverflow.com/users/9634563",
"pm_score": 4,
"selected": false,
"text": "WITH recursive numbers AS (\n select 0 as Date\n union all\n select Date + 1\n from numbers\n where Date < 10)\nselect * from numbers;\n"
},
{
"answer_id": 56232728,
"author": "Max Makhrov",
"author_id": 5372400,
"author_profile": "https://Stackoverflow.com/users/5372400",
"pm_score": 3,
"selected": false,
"text": " select tt.row from\n (\n SELECT cast( concat(t.0,t2.0,t3.0) + 1 As UNSIGNED) as 'row' FROM \n (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t,\n (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2, \n (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3\n ) tt\n order by tt.row\n"
},
{
"answer_id": 67996449,
"author": "deesolie",
"author_id": 13296497,
"author_profile": "https://Stackoverflow.com/users/13296497",
"pm_score": 1,
"selected": false,
"text": "with t1 as (\nselect 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9\n)\nSELECT ROW_NUMBER() over ()\nFROM\nt1,\nt1 as t2;\n"
},
{
"answer_id": 73864248,
"author": "craigmj",
"author_id": 924653,
"author_profile": "https://Stackoverflow.com/users/924653",
"pm_score": 1,
"selected": false,
"text": "with recursive numbers (n) as (\n select 1 as n\n union\n select n+1 from numbers where n<100\n)\nselect * from numbers\n numbers"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.