qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
54,579 |
<p>Does anyone know of a good example of how to expose a WCF service programatically without the use of a configuration file? I know the service object model is much richer now with WCF, so I know it's possible. I just have not seen an example of how to do so. Conversely, I would like to see how consuming without a configuration file is done as well.</p>
<p>Before anyone asks, I have a very specific need to do this without configuration files. I would normally not recommend such a practice, but as I said, there is a very specific need in this case.</p>
|
[
{
"answer_id": 292810,
"author": "devios1",
"author_id": 238948,
"author_profile": "https://Stackoverflow.com/users/238948",
"pm_score": 8,
"selected": true,
"text": "internal static MyServiceSoapClient CreateWebServiceInstance() {\n BasicHttpBinding binding = new BasicHttpBinding();\n // I think most (or all) of these are defaults--I just copied them from app.config:\n binding.SendTimeout = TimeSpan.FromMinutes( 1 );\n binding.OpenTimeout = TimeSpan.FromMinutes( 1 );\n binding.CloseTimeout = TimeSpan.FromMinutes( 1 );\n binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 );\n binding.AllowCookies = false;\n binding.BypassProxyOnLocal = false;\n binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;\n binding.MessageEncoding = WSMessageEncoding.Text;\n binding.TextEncoding = System.Text.Encoding.UTF8;\n binding.TransferMode = TransferMode.Buffered;\n binding.UseDefaultWebProxy = true;\n return new MyServiceSoapClient( binding, new EndpointAddress( \"http://www.mysite.com/MyService.asmx\" ) );\n}\n"
},
{
"answer_id": 8925111,
"author": "S. M. Khaled Reza",
"author_id": 1158316,
"author_profile": "https://Stackoverflow.com/users/1158316",
"pm_score": 4,
"selected": false,
"text": "public class ValidatorClass\n{\n WSHttpBinding BindingConfig;\n EndpointIdentity DNSIdentity;\n Uri URI;\n ContractDescription ConfDescription;\n\n public ValidatorClass()\n { \n // In constructor initializing configuration elements by code\n BindingConfig = ValidatorClass.ConfigBinding();\n DNSIdentity = ValidatorClass.ConfigEndPoint();\n URI = ValidatorClass.ConfigURI();\n ConfDescription = ValidatorClass.ConfigContractDescription();\n }\n\n\n public void MainOperation()\n {\n var Address = new EndpointAddress(URI, DNSIdentity);\n var Client = new EvalServiceClient(BindingConfig, Address);\n Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;\n Client.Endpoint.Contract = ConfDescription;\n Client.ClientCredentials.UserName.UserName = \"companyUserName\";\n Client.ClientCredentials.UserName.Password = \"companyPassword\";\n Client.Open();\n\n string CatchData = Client.CallServiceMethod();\n\n Client.Close();\n }\n\n\n\n public static WSHttpBinding ConfigBinding()\n {\n // ----- Programmatic definition of the SomeService Binding -----\n var wsHttpBinding = new WSHttpBinding();\n\n wsHttpBinding.Name = \"BindingName\";\n wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);\n wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.BypassProxyOnLocal = false;\n wsHttpBinding.TransactionFlow = false;\n wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;\n wsHttpBinding.MaxBufferPoolSize = 524288;\n wsHttpBinding.MaxReceivedMessageSize = 65536;\n wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;\n wsHttpBinding.TextEncoding = Encoding.UTF8;\n wsHttpBinding.UseDefaultWebProxy = true;\n wsHttpBinding.AllowCookies = false;\n\n wsHttpBinding.ReaderQuotas.MaxDepth = 32;\n wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;\n wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;\n wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;\n wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;\n\n wsHttpBinding.ReliableSession.Ordered = true;\n wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);\n wsHttpBinding.ReliableSession.Enabled = false;\n\n wsHttpBinding.Security.Mode = SecurityMode.Message;\n wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;\n wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;\n wsHttpBinding.Security.Transport.Realm = \"\";\n\n wsHttpBinding.Security.Message.NegotiateServiceCredential = true;\n wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;\n wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;\n // ----------- End Programmatic definition of the SomeServiceServiceBinding --------------\n\n return wsHttpBinding;\n\n }\n\n public static Uri ConfigURI()\n {\n // ----- Programmatic definition of the Service URI configuration -----\n Uri URI = new Uri(\"http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/\");\n\n return URI;\n }\n\n public static EndpointIdentity ConfigEndPoint()\n {\n // ----- Programmatic definition of the Service EndPointIdentitiy configuration -----\n EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity(\"tempCert\");\n\n return DNSIdentity;\n }\n\n\n public static ContractDescription ConfigContractDescription()\n {\n // ----- Programmatic definition of the Service ContractDescription Binding -----\n ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));\n\n return Contract;\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
54,585 |
<p>In what scenarios is it better to use a <code>struct</code> vs a <code>class</code> in C++?</p>
|
[
{
"answer_id": 54596,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 11,
"selected": true,
"text": "class struct struct public class private public protected private struct class private protected"
},
{
"answer_id": 54628,
"author": "mbyrne215",
"author_id": 5241,
"author_profile": "https://Stackoverflow.com/users/5241",
"pm_score": 5,
"selected": false,
"text": "typedef struct\n{\n int messageId;\n int messageCounter;\n int messageData;\n} tMessageType;\n\nvoid processMessage(unsigned char *rawMessage)\n{\n tMessageType *messageFields = (tMessageType *)rawMessage;\n printf(\"MessageId is %d\\n\", messageFields->messageId);\n}\n"
},
{
"answer_id": 54830,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 4,
"selected": false,
"text": "template <typename T> struct type_traits {\n typedef T type;\n typedef T::iterator_type iterator_type;\n ...\n};\n"
},
{
"answer_id": 54870,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": -1,
"selected": false,
"text": "class PublicInputData {\n //data members\n };\n"
},
{
"answer_id": 54902,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 6,
"selected": false,
"text": "struct Compare { bool operator() { ... } };\nstd::sort(collection.begin(), collection.end(), Compare()); \n"
},
{
"answer_id": 1191852,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 2,
"selected": false,
"text": "class struct"
},
{
"answer_id": 1191880,
"author": "quark",
"author_id": 29057,
"author_profile": "https://Stackoverflow.com/users/29057",
"pm_score": 8,
"selected": false,
"text": "struct class struct public class private public struct public class struct struct class class X\n{\n public:\n\n // ...\n};\n\nstruct X\n{\n // ...\n};\n"
},
{
"answer_id": 1191966,
"author": "Maciek",
"author_id": 142168,
"author_profile": "https://Stackoverflow.com/users/142168",
"pm_score": 1,
"selected": false,
"text": "#include <string>\n#include <map>\nusing namespace std;\n\nstruct student\n{\n int age;\n string name;\n map<string, int> grades\n};\n\nclass ClassRoom\n{\n typedef map<string, student> student_map;\n public :\n student getStudentByName(string name) const \n { student_map::const_iterator m_it = students.find(name); return m_it->second; }\n private :\n student_map students;\n};\n"
},
{
"answer_id": 1195156,
"author": "ogoid",
"author_id": 1608293,
"author_profile": "https://Stackoverflow.com/users/1608293",
"pm_score": 4,
"selected": false,
"text": "struct myvec {\n int x;\n int y;\n int z;\n\n int length() {return x+y+z;}\n};\n"
},
{
"answer_id": 1196597,
"author": "Khaled Alshaya",
"author_id": 127893,
"author_profile": "https://Stackoverflow.com/users/127893",
"pm_score": 1,
"selected": false,
"text": "struct functors POD class // '()' is public by default!\nstruct mycompare : public std::binary_function<int, int, bool>\n{\n bool operator()(int first, int second)\n { return first < second; }\n};\n\nclass mycompare : public std::binary_function<int, int, bool>\n{\npublic:\n bool operator()(int first, int second)\n { return first < second; }\n};\n"
},
{
"answer_id": 1628357,
"author": "Adisak",
"author_id": 14904,
"author_profile": "https://Stackoverflow.com/users/14904",
"pm_score": 5,
"selected": false,
"text": "// C access Header to a C++ library\n#ifdef __cpp\nextern \"C\" {\n#endif\n\n// Put your C struct's here\nstruct foo\n{\n ...\n};\n// NOTE: the typedef is used because C does not automatically generate\n// a typedef with the same name as a struct like C++.\ntypedef struct foo foo;\n\n// Put your C API functions here\nvoid bar(foo *fun);\n\n#ifdef __cpp\n}\n#endif\n"
},
{
"answer_id": 36917400,
"author": "Lightness Races in Orbit",
"author_id": 560648,
"author_profile": "https://Stackoverflow.com/users/560648",
"pm_score": 8,
"selected": false,
"text": "class struct struct class private struct Foo\n{\n int x;\n};\n\nclass Bar\n{\npublic:\n int x;\n};\n class Foo;\nstruct Bar;\n std::is_class<Foo>::value\nstd::is_class<Bar>::value\n const int member; int const member; class struct"
},
{
"answer_id": 47168608,
"author": "farhan",
"author_id": 5832798,
"author_profile": "https://Stackoverflow.com/users/5832798",
"pm_score": 2,
"selected": false,
"text": "class test_one {\n int main_one();\n};\n class test_one {\n private:\n int main_one();\n};\n int two = one.main_one();\n main_one is private class test_one {\n public:\n int main_one();\n};\n struct test_one {\n int main_one;\n};\n main_one class test_one {\n public:\n int main_one;\n};\n"
},
{
"answer_id": 47295230,
"author": "Vorac",
"author_id": 1145760,
"author_profile": "https://Stackoverflow.com/users/1145760",
"pm_score": 3,
"selected": false,
"text": "struct class class struct class class struct class"
},
{
"answer_id": 52366333,
"author": "pasbi",
"author_id": 4248972,
"author_profile": "https://Stackoverflow.com/users/4248972",
"pm_score": 3,
"selected": false,
"text": "class X; struct X { ... }"
},
{
"answer_id": 58945793,
"author": "Richard Chambers",
"author_id": 1466970,
"author_profile": "https://Stackoverflow.com/users/1466970",
"pm_score": 3,
"selected": false,
"text": "struct class struct class private public struct class struct #include struct struct private public struct struct struct struct"
},
{
"answer_id": 65944568,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 2,
"selected": false,
"text": "class struct union class struct class public struct private class enum union union class struct struct class union struct class"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5436/"
] |
54,586 |
<p>I have a windows laptop (thinkpad) and somewhat recently rediscovered emacs and the benefit that all those wacky shortcuts can be when the arrow keys are located somewhere near you right armpit.</p>
<p>I was discouraged after php-mode, css-mode, etc, under mmm-mode was inconsistent, buggy, and refused to properly interpret some of my files. (In all fairness, I'm most likely doin' it wrong) So I eventually found the nxhtml package which worked pretty well.</p>
<p>However, nxhtml causes weird bugs and actually crashes on certain files (certain combinations of nested modes I supposed) under linux! (using Ubuntu 7.10 and Kubuntu 8.04)</p>
<p>I'd like to be able to work on the laptop as well as the home linux pc without having to deal with inconsistent implementations of something that shouldn't be this hard. I've googled and looked around and there's a good chance I'm the only human on the planet having these problems... Anyone got some advice?</p>
<p>(in lieu of an emacs solutions, a good enough cross-platform lightweight text editor with the dev features would also work I suppose...)</p>
|
[
{
"answer_id": 64703,
"author": "insipid",
"author_id": 8649,
"author_profile": "https://Stackoverflow.com/users/8649",
"pm_score": 2,
"selected": false,
"text": "mumamo-mode nxhtml-mode mumamo nxhtml mumamo-mode nxhtml"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2570347/"
] |
54,612 |
<p>Is there a way to have Linux read ahead when cloning a disk? I use the program named "dd" to clone disks. The last time I did this it seemed as though the OS was reading then writing but never at the same time. Ideally, the destination disk would be constantly writing without waiting that's of course if the source disk can keep up.</p>
<p>UPDATE: I normally choose a large block size when cloning (ex. 16M or 32MB).</p>
|
[
{
"answer_id": 54631,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 1,
"selected": false,
"text": "dd if=indevfile | dd of=outdevfile\n"
},
{
"answer_id": 54642,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 3,
"selected": false,
"text": "dd if=/dev/sda of=/dev/sdb bs=1M\n"
},
{
"answer_id": 55793,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 4,
"selected": true,
"text": "dd if=/dev/sda of=/dev/sdb bs=1M\n # blockdev --getra /dev/sda\n256\n# blockdev --setra 1024 /dev/sda\n# blockdev --getra /dev/sda\n1024\n# blockdev --help\nUsage:\n blockdev -V\n blockdev --report [devices]\n blockdev [-v|-q] commands devices\nAvailable commands:\n --getsz (get size in 512-byte sectors)\n --setro (set read-only)\n --setrw (set read-write)\n --getro (get read-only)\n --getss (get sectorsize)\n --getbsz (get blocksize)\n --setbsz BLOCKSIZE (set blocksize)\n --getsize (get 32-bit sector count)\n --getsize64 (get size in bytes)\n --setra READAHEAD (set readahead)\n --getra (get readahead)\n --flushbufs (flush buffers)\n --rereadpt (reread partition table)\n --rmpart PARTNO (disable partition)\n --rmparts (disable all partitions)\n#\n"
},
{
"answer_id": 13249678,
"author": "SteveMenard",
"author_id": 1802853,
"author_profile": "https://Stackoverflow.com/users/1802853",
"pm_score": 3,
"selected": false,
"text": "dd if=/dev/sda bs=1M iflag=direct | dd of=/dev/sdb bs=1M oflag=direct\n watch -n 60 killall -USR1 dd\n"
},
{
"answer_id": 24758991,
"author": "Paolinux",
"author_id": 1901651,
"author_profile": "https://Stackoverflow.com/users/1901651",
"pm_score": 2,
"selected": false,
"text": "dd"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778/"
] |
54,626 |
<p>This code is from <em>Prototype.js</em>. I've looked at probably 20 different tutorials, and I can't figure out why this is not working. The response I get is null.</p>
<pre><code>new Ajax.Request(/path/to / xml / file.xml, {
method: "get",
contentType: "application/xml",
onSuccess: function(transport) {
alert(transport.responseXML);
}
});
</code></pre>
<p>If I change the <code>responseXML</code> to <code>responseText</code>, then it alerts to me the XML file as a string. This is not a PHP page serving up XML, but an actual XML file, so I know it is not the response headers.</p>
|
[
{
"answer_id": 12488558,
"author": "riverX",
"author_id": 1682030,
"author_profile": "https://Stackoverflow.com/users/1682030",
"pm_score": 1,
"selected": false,
"text": "application/xml xml xsl gpx\n AddType application/xml xml xsl gpx\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
54,658 |
<p>The <a href="http://msdn.microsoft.com/en-us/library/kx145dw2.aspx" rel="noreferrer">ClientScriptManager.RegisterClientScriptInclude</a> method allows you to register a JavaScript reference with the Page object (checking for duplicates).</p>
<p>Is there an equivalent of this method for CSS references?</p>
<p>Similar questions apply for <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx" rel="noreferrer">ClientScriptManager.RegisterClientScriptBlock</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptresource.aspx" rel="noreferrer">ClientScriptManager.RegisterClientScriptResource</a></p>
|
[
{
"answer_id": 112189,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 3,
"selected": false,
"text": "HtmlLink link = new HtmlLink();\nlink.Href = \"Cases/EditStyles.css\";\nlink.Attributes.Add(\"type\", \"text/css\");\nlink.Attributes.Add(\"rel\", \"stylesheet\");\nthis.Header.Controls.Add(link);\n"
},
{
"answer_id": 112745,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "<div class=\"SmillerControls_Toolbar\">\n <a class=\"SmillerControls_Button\" ...>...</a>\n ...\n</div>\n <div class=\"SmillerControls\">\n <div class=\"Toolbar\">\n <a class=\"Button\" ...>...</a>\n </div>\n </div>\n div.SmillerControls div.Toolbar\n {\n ...\n }\n\n div.SmillerControls div.Toolbar a.Button\n {\n ...\n }\n"
},
{
"answer_id": 3241134,
"author": "guillem",
"author_id": 351975,
"author_profile": "https://Stackoverflow.com/users/351975",
"pm_score": 0,
"selected": false,
"text": "<asp:Literal id=\"cssliteral\" runat=\"server\" /> \n StingBuilder str = new StringBuilder();\nstr.Append(\"<style type=\"text/css\">\");\nstr.Append(\".myclass {background-color:#\" + mycolor);\nstr.Append(\"</style>\");\n\ncssLiteral.Text = str.ToString();\n"
},
{
"answer_id": 3522817,
"author": "mindless",
"author_id": 425364,
"author_profile": "https://Stackoverflow.com/users/425364",
"pm_score": 2,
"selected": false,
"text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n With Page.ClientScript\n If Not .IsClientScriptIncludeRegistered(\"JQuery\") Then \n .RegisterClientScriptInclude(\"JQuery\", \"Scripts/jquery-1.4.2.min.js\")\n Dim l As New Literal()\n l.Text = \"<link href='Uploadify/uploadify.css' rel='stylesheet' type='text/css' />\"\n sender.controls.add(l)\n End If\n End With\nEnd Sub\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247/"
] |
54,669 |
<p>The job at hand:</p>
<p>I want to make sure that my website's users view a page before they start a download. If they have not looked at the page but try to hotlink to the files directly they should go to the webpage before the download is allowed.</p>
<p>Any suggestions that are better than my idea to send out a cookie and - before the download starts - check if the cookie exists (via .htaccess)?</p>
<p>The webpage and the download files will be located on different servers.</p>
<p>Environment:</p>
<ul>
<li>Apache 2 on all machines</li>
<li>PHP 5 on all machines</li>
<li>MySQL 5 available on the "webpage" server (no access from the download servers)</li>
</ul>
<p>Nathan asked what the problem is that I try to solve, and in fact it is that I want to prevent hotlinks from - for example - forums. If people download from our server, using our bandwidth, I want to show them an page with an ad before the download starts. It doesn't need to be totally secure, but we need to make some money to finance the servers, right? :)</p>
|
[
{
"answer_id": 54801,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "RewriteEngine on\nRewriteCond %{HTTP_REFERER} !^http://www.example.com/page.html$\nRewriteRule file.exe http://www.example.com/page.html [R=301,L]\n file.exe page.html page.html"
},
{
"answer_id": 59069,
"author": "Nathan",
"author_id": 6062,
"author_profile": "https://Stackoverflow.com/users/6062",
"pm_score": 1,
"selected": false,
"text": "cookievalue = sha1('secretvalue'.date('z-H'));\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
54,674 |
<p>i'm wondering if there is any nice and neat tool to replace the GNU Autotools or Make to build a very large C++ project, which are such a complicated thing to use. </p>
<p>It is simple to generate all the files that de Autotools require if the project is small, but if the source code is divided in many directories, with multiple third party libraries and many dependencies, you fall into the "Autotools Hell"..</p>
<p>thanks for any recommendations</p>
|
[
{
"answer_id": 55525,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 4,
"selected": false,
"text": "~$ ./waf configure && ./waf && ./waf install\n set_options() configure(conf) build(bld)"
},
{
"answer_id": 529562,
"author": "Kristian",
"author_id": 3608,
"author_profile": "https://Stackoverflow.com/users/3608",
"pm_score": 2,
"selected": false,
"text": "scons all -j8"
},
{
"answer_id": 530960,
"author": "Frank",
"author_id": 60628,
"author_profile": "https://Stackoverflow.com/users/60628",
"pm_score": 1,
"selected": false,
"text": "XML available formats are:\n autoconf GNU autoconf Makefile.in files\n borland Borland C/C++ makefiles\n dmars Digital Mars makefiles\n dmars_smake Digital Mars makefiles for SMAKE\n gnu GNU toolchain makefiles (Unix)\n mingw MinGW makefiles (mingw32-make)\n msevc4prj MS eMbedded Visual C++ 4 project files\n msvc MS Visual C++ nmake makefiles\n msvc6prj MS Visual C++ 6.0 project files\n msvs2003prj MS Visual Studio 2003 project files\n msvs2005prj MS Visual Studio 2005 project files\n symbian Symbian development files\n watcom OpenWatcom makefiles\n xcode2 Xcode 2.4 project files\n configure.ac ./configure && make && make install\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876/"
] |
54,686 |
<p>Does any one know how do I get the current open windows or process of a local machine using Java? </p>
<p>What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.</p>
|
[
{
"answer_id": 54696,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "Process proc = Runtime.getRuntime().exec (\"tasklist.exe\");\nInputStream procOutput = proc.getInputStream ();\nif (0 == proc.waitFor ()) {\n // TODO scan the procOutput for your data\n}\n"
},
{
"answer_id": 54950,
"author": "ràmäyác",
"author_id": 4358,
"author_profile": "https://Stackoverflow.com/users/4358",
"pm_score": 7,
"selected": false,
"text": "try {\n String line;\n Process p = Runtime.getRuntime().exec(\"ps -e\");\n BufferedReader input =\n new BufferedReader(new InputStreamReader(p.getInputStream()));\n while ((line = input.readLine()) != null) {\n System.out.println(line); //<-- Parse data here.\n }\n input.close();\n} catch (Exception err) {\n err.printStackTrace();\n}\n Process p = Runtime.getRuntime().exec\n (System.getenv(\"windir\") +\"\\\\system32\\\\\"+\"tasklist.exe\");\n"
},
{
"answer_id": 9463010,
"author": "Emmanuel Bourg",
"author_id": 525725,
"author_profile": "https://Stackoverflow.com/users/525725",
"pm_score": 5,
"selected": false,
"text": "import com.sun.jna.Native;\nimport com.sun.jna.platform.win32.*;\nimport com.sun.jna.win32.W32APIOptions;\n\npublic class ProcessList {\n\n public static void main(String[] args) {\n WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);\n\n WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));\n\n Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();\n\n while (winNT.Process32Next(snapshot, processEntry)) {\n System.out.println(processEntry.th32ProcessID + \"\\t\" + Native.toString(processEntry.szExeFile));\n }\n\n winNT.CloseHandle(snapshot);\n }\n}\n"
},
{
"answer_id": 10638518,
"author": "James Oravec",
"author_id": 1190934,
"author_profile": "https://Stackoverflow.com/users/1190934",
"pm_score": 2,
"selected": false,
"text": "ps aux tasklist ps aux grep"
},
{
"answer_id": 16828521,
"author": "Panchotiya Vipul",
"author_id": 2114999,
"author_profile": "https://Stackoverflow.com/users/2114999",
"pm_score": 0,
"selected": false,
"text": "package com.vipul;\n\nimport java.applet.Applet;\nimport java.awt.Checkbox;\nimport java.awt.Choice;\nimport java.awt.Font;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BatchExecuteService extends Applet {\n public Choice choice;\n\n public void init() \n {\n setFont(new Font(\"Helvetica\", Font.BOLD, 36));\n choice = new Choice();\n }\n\n public static void main(String[] args) {\n BatchExecuteService batchExecuteService = new BatchExecuteService();\n batchExecuteService.run();\n }\n\n List<String> processList = new ArrayList<String>();\n\n public void run() {\n try {\n Runtime runtime = Runtime.getRuntime();\n Process process = runtime.exec(\"D:\\\\server.bat\");\n process.getOutputStream().close();\n InputStream inputStream = process.getInputStream();\n InputStreamReader inputstreamreader = new InputStreamReader(\n inputStream);\n BufferedReader bufferedrReader = new BufferedReader(\n inputstreamreader);\n BufferedReader bufferedrReader1 = new BufferedReader(\n inputstreamreader);\n\n String strLine = \"\";\n String x[]=new String[100];\n int i=0;\n int t=0;\n while ((strLine = bufferedrReader.readLine()) != null) \n {\n // System.out.println(strLine);\n String[] a=strLine.split(\",\");\n x[i++]=a[0];\n }\n // System.out.println(\"Length : \"+i);\n\n for(int j=2;j<i;j++)\n {\n System.out.println(x[j]);\n }\n }\n catch (IOException ioException) \n {\n ioException.printStackTrace();\n }\n\n }\n}\n You can create batch file like \n"
},
{
"answer_id": 35390242,
"author": "profesor_falken",
"author_id": 1774614,
"author_profile": "https://Stackoverflow.com/users/1774614",
"pm_score": 3,
"selected": false,
"text": "List<ProcessInfo> processesList = JProcesses.getProcessList();\n\nfor (final ProcessInfo processInfo : processesList) {\n System.out.println(\"Process PID: \" + processInfo.getPid());\n System.out.println(\"Process Name: \" + processInfo.getName());\n System.out.println(\"Process Used Time: \" + processInfo.getTime());\n System.out.println(\"Full command: \" + processInfo.getCommand());\n System.out.println(\"------------------\");\n}\n"
},
{
"answer_id": 41634959,
"author": "Stepan Yakovenko",
"author_id": 517073,
"author_profile": "https://Stackoverflow.com/users/517073",
"pm_score": 2,
"selected": false,
"text": "Process process = new ProcessBuilder(\"tasklist.exe\", \"/fo\", \"csv\", \"/nh\").start();\nnew Thread(() -> {\n Scanner sc = new Scanner(process.getInputStream());\n if (sc.hasNextLine()) sc.nextLine();\n while (sc.hasNextLine()) {\n String line = sc.nextLine();\n String[] parts = line.split(\",\");\n String unq = parts[0].substring(1).replaceFirst(\".$\", \"\");\n String pid = parts[1].substring(1).replaceFirst(\".$\", \"\");\n System.out.println(unq + \" \" + pid);\n }\n}).start();\nprocess.waitFor();\nSystem.out.println(\"Done\");\n"
},
{
"answer_id": 45068036,
"author": "Hugues M.",
"author_id": 6730571,
"author_profile": "https://Stackoverflow.com/users/6730571",
"pm_score": 7,
"selected": true,
"text": "ProcessHandle public static void main(String[] args) {\n ProcessHandle.allProcesses()\n .forEach(process -> System.out.println(processDetails(process)));\n}\n\nprivate static String processDetails(ProcessHandle process) {\n return String.format(\"%8d %8s %10s %26s %-40s\",\n process.pid(),\n text(process.parent().map(ProcessHandle::pid)),\n text(process.info().user()),\n text(process.info().startInstant()),\n text(process.info().commandLine()));\n}\n\nprivate static String text(Optional<?> optional) {\n return optional.map(Object::toString).orElse(\"-\");\n}\n 1 - root 2017-11-19T18:01:13.100Z /sbin/init\n ...\n 639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start\n ...\n23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo\n"
},
{
"answer_id": 51379205,
"author": "wax_lyrical",
"author_id": 3987353,
"author_profile": "https://Stackoverflow.com/users/3987353",
"pm_score": 2,
"selected": false,
"text": "C:\\Dev\\build\\SomeJavaApp\\jre-9.0.1\\bin\\javaw.exe\n public static void main(String[] args) {\n AtomicBoolean isRunning = new AtomicBoolean(false);\n ProcessHandle.allProcesses()\n .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains(\"SomeJavaApp\"))\n .forEach((process) -> {\n isRunning.set(true);\n });\n if (isRunning.get()) System.out.println(\"SomeJavaApp is running already\");\n}\n"
},
{
"answer_id": 53966059,
"author": "Dylan Wedman",
"author_id": 10844972,
"author_profile": "https://Stackoverflow.com/users/10844972",
"pm_score": 0,
"selected": false,
"text": "private static final DefaultListModel tasks = new DefaultListModel();\n\npublic static void getTasks()\n{\n new Thread()\n {\n @Override\n public void run()\n {\n try \n {\n File batchFile = File.createTempFile(\"batchFile\", \".bat\");\n File logFile = File.createTempFile(\"log\", \".txt\");\n String logFilePath = logFile.getAbsolutePath();\n try (PrintWriter fileCreator = new PrintWriter(batchFile)) \n {\n String[] linesToPrint = {\"@echo off\", \"tasklist.exe >>\" + logFilePath, \"exit\"};\n for(String string:linesToPrint)\n {\n fileCreator.println(string);\n }\n fileCreator.close();\n }\n int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();\n if(task == 0)\n {\n FileReader fileOpener = new FileReader(logFile);\n try (BufferedReader reader = new BufferedReader(fileOpener))\n {\n String line;\n while(true)\n {\n line = reader.readLine();\n if(line != null)\n {\n if(line.endsWith(\"K\"))\n {\n if(line.contains(\".exe\"))\n {\n int index = line.lastIndexOf(\".exe\", line.length());\n String taskName = line.substring(0, index + 4);\n if(! taskName.equals(\"tasklist.exe\") && ! taskName.equals(\"cmd.exe\") && ! taskName.equals(\"java.exe\"))\n {\n tasks.addElement(taskName);\n }\n }\n }\n }\n else\n {\n reader.close();\n break;\n }\n }\n }\n }\n batchFile.deleteOnExit();\n logFile.deleteOnExit();\n } \n catch (FileNotFoundException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n } \n catch (IOException | InterruptedException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n }\n catch (NullPointerException ex)\n {\n // This stops errors from being thrown on an empty line\n }\n }\n }.start();\n}\n\npublic static void killTask(String taskName)\n{\n new Thread()\n {\n @Override\n public void run()\n {\n try \n {\n Runtime.getRuntime().exec(\"taskkill.exe /IM \" + taskName);\n } \n catch (IOException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }.start();\n}\n"
},
{
"answer_id": 58663666,
"author": "Nallamachu",
"author_id": 2159525,
"author_profile": "https://Stackoverflow.com/users/2159525",
"pm_score": 2,
"selected": false,
"text": "public class CurrentProcess {\n public static void main(String[] args) {\n ProcessHandle handle = ProcessHandle.current();\n System.out.println(\"Current Running Process Id: \"+handle.pid());\n ProcessHandle.Info info = handle.info();\n System.out.println(\"ProcessHandle.Info : \"+info);\n }\n}\n import java.util.List;\nimport java.util.stream.Collectors;\n\npublic class AllProcesses {\n public static void main(String[] args) {\n ProcessHandle.allProcesses().forEach(processHandle -> {\n System.out.println(processHandle.pid()+\" \"+processHandle.info());\n });\n }\n}\n"
},
{
"answer_id": 60378892,
"author": "Jijo Joy",
"author_id": 12954467,
"author_profile": "https://Stackoverflow.com/users/12954467",
"pm_score": 2,
"selected": false,
"text": " String line;\n Process process = Runtime.getRuntime().exec(\"ps -e\");\n process.getOutputStream().close();\n BufferedReader input =\n new BufferedReader(new InputStreamReader(process.getInputStream()));\n while ((line = input.readLine()) != null) {\n System.out.println(line); //<-- Parse data here.\n }\n input.close(); process.getOutputStream.close()"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358/"
] |
54,708 |
<p>This is an ASP.Net 2.0 web app. The Item template looks like this, for reference:</p>
<pre><code><ItemTemplate>
<tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field1") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field2") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field3") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field4") %></td>
</tr>
</ItemTemplate>
</code></pre>
<p>Using this in codebehind:</p>
<pre><code>foreach (RepeaterItem item in rptrFollowupSummary.Items)
{
string val = ((DataBoundLiteralControl)item.Controls[0]).Text;
Trace.Write(val);
}
</code></pre>
<p>I produce this:</p>
<pre><code><tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1">23</td>
<td class="class1">1/1/2000</td>
<td class="class1">-2</td>
<td class="class1">11</td>
</tr>
</code></pre>
<p>What I need is the data from Field1 and Field4</p>
<p>I can't seem to get at the data the way I would in say a DataList or a GridView, and I can't seem to come up with anything else on Google or quickly leverage this one to do what I want. The only way I can see to get at the data is going to be using a regex to go and get it (Because a man takes what he wants. He takes it all. And I'm a man, aren't I? Aren't I?). </p>
<p>Am I on the right track (not looking for the specific regex to do this; forging that might be a followup question ;) ), or am I missing something?</p>
<hr>
<p>The Repeater in this case is set in stone so I can't switch to something more elegant. Once upon a time I did something similar to what Alison Zhou suggested using DataLists, but it's been some time (2+ years) and I just completely forgot about doing it this way. Yeesh, talk about overlooking something obvious. . .</p>
<p>So I did as Alison suggested and it works fine. I don't think the viewstate is an issue here, even though this repeater can get dozens of rows. I can't really speak to the question if doing it that way versus using the instead (but that seems like a fine solution to me otherwise). Obviously the latter is less of a viewstate footprint, but I'm not experienced enough to say when one approach might be preferrable to another without an extreme example in front of me. Alison, one question: why literals and not labels?</p>
<p>Euro Micelli, I was trying to avoid a return trip to the database. Since I'm still a little green relative to the rest of the development world, I admit I don't necessarily have a good grasp of how many database trips is "just right". There wouldn't be a performance issue here (I know the app's load enough to know this), but I suppose I was trying to avoid it out of habit, since my boss tends to emphasize fewer trips where possible.</p>
|
[
{
"answer_id": 54738,
"author": "ern",
"author_id": 5609,
"author_profile": "https://Stackoverflow.com/users/5609",
"pm_score": 2,
"selected": false,
"text": "runat=\"server\" InnerText"
},
{
"answer_id": 54745,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 4,
"selected": true,
"text": "<ItemTemplate>\n <tr>\n <td \"class1\"><asp:Literal ID=\"litField1\" runat=\"server\" Text='<%# Bind(\"Field1\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField2\" runat=\"server\" Text='<%# Bind(\"Field2\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField3\" runat=\"server\" Text='<%# Bind(\"Field3\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField4\" runat=\"server\" Text='<%# Bind(\"Field4\") %>'/></td>\n </tr>\n</ItemTemplate>\n foreach (RepeaterItem item in rptrFollowupSummary.Items)\n{ \n Literal lit1 = (Literal)item.FindControl(\"litField1\");\n string value1 = lit1.Text;\n Literal lit4 = (Literal)item.FindControl(\"litField4\");\n string value4 = lit4.Text;\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734/"
] |
54,709 |
<p>Multiple approaches exist to write your unit tests when using Rhino Mocks:</p>
<ul>
<li>The Standard Syntax</li>
<li>Record/Replay Syntax</li>
<li>The Fluent Syntax</li>
</ul>
<p>What is the ideal and most frictionless way?</p>
|
[
{
"answer_id": 54893,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "using(mocks.Record())\n{\n Expect.Call(foo.Bar());\n}\nusing(mocks.Playback())\n{\n MakeItAllHappen();\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
54,725 |
<p>Sending a message from the Unix command line using <code>mail TO_ADDR</code> results in an email from <code>$USER@$HOSTNAME</code>. Is there a way to change the "From:" address inserted by <code>mail</code>?</p>
<p>For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL).</p>
<p>[EDIT]</p>
<pre>
$ mail -s Testing [email protected]
Cc:
From: [email protected]
Testing
.
</pre>
<p>yields</p>
<pre>
Subject: Testing
To: <[email protected]>
X-Mailer: mail (GNU Mailutils 1.1)
Message-Id: <E1KdTJj-00025z-RK@localhost>
From: <chris@localhost>
Date: Wed, 10 Sep 2008 13:17:23 -0400
From: [email protected]
Testing
</pre>
<p>The "From: [email protected]" line is part of the message body, not part of the header.</p>
|
[
{
"answer_id": 380573,
"author": "cms",
"author_id": 28532,
"author_profile": "https://Stackoverflow.com/users/28532",
"pm_score": 8,
"selected": true,
"text": "export [email protected]\nmail -aFrom:[email protected] -s 'Testing'\n -r -a"
},
{
"answer_id": 1353352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "echo \"hi root\"|mail [email protected] -s'testinggg' root\n"
},
{
"answer_id": 2059055,
"author": "Beau",
"author_id": 60371,
"author_profile": "https://Stackoverflow.com/users/60371",
"pm_score": 5,
"selected": false,
"text": "mail -s \"Subject\" [email protected] -- -f [email protected] < body\n"
},
{
"answer_id": 4519341,
"author": "ubuntu-fanboy",
"author_id": 552429,
"author_profile": "https://Stackoverflow.com/users/552429",
"pm_score": 5,
"selected": false,
"text": "echo \"Hello there\" | mail -s \"testing\" -r [email protected] [email protected]\n"
},
{
"answer_id": 6118894,
"author": "gbla",
"author_id": 768791,
"author_profile": "https://Stackoverflow.com/users/768791",
"pm_score": 2,
"selected": false,
"text": "mail -s \"Subject\" [email protected] -- -f [email protected]\n -f"
},
{
"answer_id": 6124477,
"author": "Ryan Barong",
"author_id": 769550,
"author_profile": "https://Stackoverflow.com/users/769550",
"pm_score": 2,
"selected": false,
"text": "mail to-addr ... -sendmail-options ...\n mail [email protected] -f [email protected]\n"
},
{
"answer_id": 8483239,
"author": "artickl",
"author_id": 1094841,
"author_profile": "https://Stackoverflow.com/users/1094841",
"pm_score": 3,
"selected": false,
"text": "-F option mail -s \"$SUBJECT\" $MAILTO -- -F $MAILFROM -f ${MAILFROM}@somedomain.com\n"
},
{
"answer_id": 11656356,
"author": "MoSs",
"author_id": 1552560,
"author_profile": "https://Stackoverflow.com/users/1552560",
"pm_score": 4,
"selected": false,
"text": "mail -s \"$(echo -e \"This is the subject\\nFrom: Paula <[email protected]>\\n\nReply-to: [email protected]\\nContent-Type: text/html\\n\")\" \[email protected] < htmlFileMessage.txt\n"
},
{
"answer_id": 19007441,
"author": "Alcanzar",
"author_id": 2785358,
"author_profile": "https://Stackoverflow.com/users/2785358",
"pm_score": 3,
"selected": false,
"text": " echo test | mail -s \"test\" [email protected] -- -F'Some Name<[email protected]>' -t\n -F'Some Name' [email protected] -t"
},
{
"answer_id": 21856390,
"author": "Céline Aussourd",
"author_id": 2339082,
"author_profile": "https://Stackoverflow.com/users/2339082",
"pm_score": 2,
"selected": false,
"text": "echo \"email body\" | mail -s \"Subject here\" -r from_email_address email_address_to\n"
},
{
"answer_id": 24032988,
"author": "keypress",
"author_id": 1961303,
"author_profile": "https://Stackoverflow.com/users/1961303",
"pm_score": -1,
"selected": false,
"text": "export [email protected]\nexport [email protected]\nmutt -s Testing [email protected]\n"
},
{
"answer_id": 26114710,
"author": "deepak.prathapani",
"author_id": 2165897,
"author_profile": "https://Stackoverflow.com/users/2165897",
"pm_score": 2,
"selected": false,
"text": "echo \"This is the body of the mail\" | mail -s 'This is the subject' '<[email protected]>,<[email protected]>' -- -F '<SenderName>' -f '<[email protected]>'\n"
},
{
"answer_id": 28788959,
"author": "jelloir",
"author_id": 837163,
"author_profile": "https://Stackoverflow.com/users/837163",
"pm_score": 2,
"selected": false,
"text": "apt-get install heirloom-mailx\n update-alternatives --config mailx\n mail -s \"Testing from & replyto\" -r \"sender <[email protected]>\" -S replyto=\"[email protected]\" [email protected] < <(echo \"Test message\")\n"
},
{
"answer_id": 36642906,
"author": "Andrew Backeby",
"author_id": 6208343,
"author_profile": "https://Stackoverflow.com/users/6208343",
"pm_score": 1,
"selected": false,
"text": "echo \"body\" | mail -S [email protected] \"Hello\""
},
{
"answer_id": 44888449,
"author": "Stephane",
"author_id": 958373,
"author_profile": "https://Stackoverflow.com/users/958373",
"pm_score": 0,
"selected": false,
"text": "Ubuntu 16.04 UTF-8 sudo apt-get install heirloom-mailx\n sudo vim /etc/ssmtp/ssmtp.conf\nmailhub=smtp.gmail.com:587\nFromLineOverride=YES\[email protected]\nAuthPass=???\nUseSTARTTLS=YES\n sender='[email protected]'\nrecipient='[email protected]'\nzipfile=\"results/file.zip\"\ntoday=`date +\\%d-\\%m-\\%Y`\nmailSubject='My subject on the '$today\nread -r -d '' mailBody << EOM\nFind attached the zip file.\n\nRegards,\nEOM\nmail -s \"$mailSubject\" -r \"Name <$sender>\" -S replyto=\"$sender\" -a $zipfile $recipient < <(echo $mailBody)\n"
},
{
"answer_id": 54215803,
"author": "JazzCat",
"author_id": 972966,
"author_profile": "https://Stackoverflow.com/users/972966",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\n# Message\necho \"My message\" > message.txt\n\n# Mail\nsubject=\"Test\"\nmail_header=\"From: John Smith <[email protected]>\"\nrecipients=\"[email protected]\"\n\n#######################################################################\ncat message.txt | mail -s \"$subject\" -a \"$mail_header\" -t \"$recipients\"\n"
},
{
"answer_id": 67505477,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 0,
"selected": false,
"text": "mail mail -r [email protected] Return-Path: <[email protected]> From: [email protected]"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
54,753 |
<p>I have a large legacy codebase with very complicated makefiles, with lots of variables. Sometimes I need to change them, and I find that it's very difficult to figure out why the change isn't working the way I expect. What I'd like to find is a tool that basically does step-through-debugging of the "make" process, where I would give it a directory, and I would be able to see the value of different variables at different points in the process. None of the debug flags to make seem to show me what I want, although it's possible that I'm missing something. Does anyone know of a way to do this?</p>
|
[
{
"answer_id": 54767,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 6,
"selected": false,
"text": "make -n make -np make -nd gmake"
},
{
"answer_id": 15522386,
"author": "GuruM",
"author_id": 452885,
"author_profile": "https://Stackoverflow.com/users/452885",
"pm_score": 5,
"selected": false,
"text": "-n, --just-print, --dry-run, --recon \nPrint the commands that would be executed, but do not execute them. \n\n-d Print debugging information in addition to normal processing. \nThe debugging information says \nwhich files are being considered for remaking, \nwhich file-times are being compared and with what results, \nwhich files actually need to be remade, \nwhich implicit rules are considered and which are applied--- \neverything interesting about how make decides what to do. \n\n--debug[=FLAGS] Print debugging information in addition to normal processing. \nIf the FLAGS are omitted, then the behaviour is the same as if -d was specified. \nFLAGS may be: \n'a' for all debugging output same as using -d, \n'b' for basic debugging, \n'v' for more verbose basic debugging, \n'i' for showing implicit rules, \n'j' for details on invocation of commands, and \n'm' for debugging while remaking makefiles. \n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5241/"
] |
54,754 |
<p>For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?</p>
|
[
{
"answer_id": 54773,
"author": "NotMyself",
"author_id": 303,
"author_profile": "https://Stackoverflow.com/users/303",
"pm_score": 5,
"selected": false,
"text": "(from c in nwnd.Customers select c.CustomerID)\n .Skip(10).Take(10).ToList(); \n"
},
{
"answer_id": 54777,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 8,
"selected": true,
"text": "ICriteria SetFirstResult(int i) SetMaxResults(int i) criteria.SetFirstResult(0).SetMaxResults(10);\n"
},
{
"answer_id": 54858,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 3,
"selected": false,
"text": "public class Page {\n\n private List results;\n private int pageSize;\n private int page;\n\n public Page(Query query, int page, int pageSize) {\n\n this.page = page;\n this.pageSize = pageSize;\n results = query.setFirstResult(page * pageSize)\n .setMaxResults(pageSize+1)\n .list();\n\n }\n\n public List getNextPage()\n\n public List getPreviousPage()\n\n public int getPageCount()\n\n public int getCurrentPage()\n\n public void setPageSize()\n\n}\n"
},
{
"answer_id": 138024,
"author": "zadam",
"author_id": 410357,
"author_profile": "https://Stackoverflow.com/users/410357",
"pm_score": 4,
"selected": false,
"text": "IMultiQuery multiQuery = s.CreateMultiQuery()\n .Add(s.CreateQuery(\"from Item i where i.Id > ?\")\n .SetInt32(0, 50).SetFirstResult(10))\n .Add(s.CreateQuery(\"select count(*) from Item i where i.Id > ?\")\n .SetInt32(0, 50));\nIList results = multiQuery.List();\nIList items = (IList)results[0];\nlong count = (long)((IList)results[1])[0];\n"
},
{
"answer_id": 433210,
"author": "Barbaros Alp",
"author_id": 51734,
"author_profile": "https://Stackoverflow.com/users/51734",
"pm_score": 5,
"selected": false,
"text": "public IList<Customer> GetPagedData(int page, int pageSize, out long count)\n {\n try\n {\n var all = new List<Customer>();\n\n ISession s = NHibernateHttpModule.CurrentSession;\n IList results = s.CreateMultiCriteria()\n .Add(s.CreateCriteria(typeof(Customer)).SetFirstResult(page * pageSize).SetMaxResults(pageSize))\n .Add(s.CreateCriteria(typeof(Customer)).SetProjection(Projections.RowCountInt64()))\n .List();\n\n foreach (var o in (IList)results[0])\n all.Add((Customer)o);\n\n count = (long)((IList)results[1])[0];\n return all;\n }\n catch (Exception ex) { throw new Exception(\"GetPagedData Customer da hata\", ex); }\n }\n"
},
{
"answer_id": 1329082,
"author": "Jeremy D",
"author_id": 2096983,
"author_profile": "https://Stackoverflow.com/users/2096983",
"pm_score": 6,
"selected": false,
"text": " // Get the total row count in the database.\nvar rowCount = this.Session.CreateCriteria(typeof(EventLogEntry))\n .Add(Expression.Between(\"Timestamp\", startDate, endDate))\n .SetProjection(Projections.RowCount()).FutureValue<Int32>();\n\n// Get the actual log entries, respecting the paging.\nvar results = this.Session.CreateCriteria(typeof(EventLogEntry))\n .Add(Expression.Between(\"Timestamp\", startDate, endDate))\n .SetFirstResult(pageIndex * pageSize)\n .SetMaxResults(pageSize)\n .Future<EventLogEntry>();\n int iRowCount = rowCount.Value;\n"
},
{
"answer_id": 5073510,
"author": "Leandro de los Santos",
"author_id": 627627,
"author_profile": "https://Stackoverflow.com/users/627627",
"pm_score": 6,
"selected": false,
"text": "QueryOver<T> var pageRecords = nhSession.QueryOver<TEntity>()\n .Skip((PageNumber - 1) * PageSize)\n .Take(PageSize)\n .List();\n var pageRecords = nhSession.QueryOver<TEntity>()\n .OrderBy(t => t.AnOrderFieldLikeDate).Desc\n .Skip((PageNumber - 1) * PageSize)\n .Take(PageSize)\n .List();\n"
},
{
"answer_id": 61224560,
"author": "Marcin",
"author_id": 8537786,
"author_profile": "https://Stackoverflow.com/users/8537786",
"pm_score": 0,
"selected": false,
"text": "var criteria = ... (your criteria initializations)...;\nvar countCrit = (ICriteria)criteria.Clone();\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
54,760 |
<p>Is there a way to unfilter an NSPasteboard for what the source application specifically declared it would provide?</p>
<p>I'm attempting to serialize pasteboard data in my application. When another application places an RTF file on a pasteboard and then I ask for the available types, I get eleven different flavors of said RTF, everything from the original RTF to plain strings to dyn.* values. </p>
<p>Saving off all that data into a plist or raw data on disk isn't usually a problem as it's pretty small, but when an image of any considerable size is placed on the pasteboard, the resulting output can be tens of times larger than the source data (with multiple flavors of TIFF and PICT data being made available via filtering).</p>
<p>I'd like to just be able to save off what the original app made available if possible.</p>
<hr>
<p>John, you are far more observant than myself or the gentleman I work with who's been doing Mac programming since dinosaurs roamed the earth. Neither of us ever noticed the text you highlighted... and I've not a clue why. Starting too long at the problem, apparently.</p>
<p>And while I accepted your answer as the correct answer, it doesn't exactly answer my original question. What I was looking for was a way to identify flavors that can become other flavors simply by placing them on the pasteboard <strong>AND</strong> to know which of these types were originally offered by the provider. While walking the types list will get me the preferred order for the application that provided them, it won't tell me which ones I can safely ignore as they'll be recreated when I refill the pasteboard later.</p>
<p>I've come to the conclusion that there isn't a "good" way to do this. <code>[NSPasteboard declaredTypesFromOwner]</code> would be fabulous, but it doesn't exist.</p>
|
[
{
"answer_id": 57771,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 3,
"selected": true,
"text": "-[NSPasteboard types] -[NSPasteboard declareTypes:owner:] [pb dataForType:[[pb types] objectAtIndex:0]]\n"
},
{
"answer_id": 59715,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 0,
"selected": false,
"text": "+[NSPasteboard typesFilterableTo:] NSArray *allTypes = [pb types];\nNSAssert([allTypes count] > 0, @\"expected at least one type\");\n\n// We always require the first declared type, as a starting point.\nNSMutableSet *requiredTypes = [NSMutableSet setWithObject:[allTypes objectAtIndex:0]];\n\nfor (NSUInteger index = 1; index < [allTypes count]; index++) {\n NSString *aType = [allTypes objectAtIndex:index];\n NSSet *filtersFrom = [NSSet setWithArray:[NSPasteboard typesFilterableTo:aType]];\n\n // If this type can't be re-created with a filter we already use, add it to the\n // set of required types.\n if (![requiredTypes intersectsSet:filtersFrom])\n [requiredTypes addObject:aType];\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4233/"
] |
54,789 |
<p>I have an Asset object that has a property AssignedSoftware, which is a collection. </p>
<p>I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception. </p>
<p>Is there a standard .NET exception that I should be throwing? Or does best practices dictate I create my own custom exception?</p>
|
[
{
"answer_id": 55852,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": false,
"text": "InvalidOperationException ArgumentException InvalidOperationException"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
54,790 |
<p>Is it possible to build Visual Studio solutions without having to fire up MonoDevelop?</p>
|
[
{
"answer_id": 56113,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 7,
"selected": true,
"text": "xbuild msbuild rmdir xcopy MONO_IOMAP=case xbuild foo.sln MONO_IOMAP=all mdtool build -f:project.sln man mdtool"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
54,851 |
<p>In a follow-up to a <a href="https://stackoverflow.com/questions/54789/what-is-the-correct-net-exception-to-throw-when-try-to-insert-a-duplicate-objec">previous question</a> regarding exceptions, what are best practices for creating a custom exception in .NET? </p>
<p>More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?</p>
|
[
{
"answer_id": 54856,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "System.Exception System.ApplicationException System.ApplicationException"
},
{
"answer_id": 54942,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 5,
"selected": false,
"text": "throw new Exception(\"Bar happened in Foo\"); throw new FooException(\"Bar happened\"); throw new FooBarException(); class FooException : Exception \n{\n public FooException(string message) ... \n}\n class FooBarException : FooException \n{\n public FooBarException() \n : base (\"Bar happened\") \n {\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
54,861 |
<p>I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc".</p>
<p>How can I make this work? I'm not averse to canning the whole piece of code... but I'd rather not replace it with a third party library that calls JNI.</p>
<pre><code>public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
</code></pre>
<p><strong>EDIT:</strong> When I run it with the errant file windows complains about finding the file. But... when I run the command line directly from the command line it runs just fine.</p>
|
[
{
"answer_id": 55018,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 0,
"selected": false,
"text": "List<String> command = new ArrayList<String>();\ncommand.add(someExecutable);\ncommand.add(someArguemnt0);\ncommand.add(someArgument1);\ncommand.add(someArgument2);\nProcessBuilder builder = new ProcessBuilder(command);\ntry {\nfinal Process process = builder.start();\n... \n} catch (IOException ioe) {}\n"
},
{
"answer_id": 55059,
"author": "KeithL",
"author_id": 5478,
"author_profile": "https://Stackoverflow.com/users/5478",
"pm_score": 0,
"selected": false,
"text": "import java.io.IOException;\nimport java.io.File;\n\npublic class test {\n\n public static void openDocument(String path) throws IOException {\n path = \"\\\"\" + path + \"\\\"\";\n File f = new File( path );\n String command = \"C:\\\\Windows\\\\System32\\\\cmd.exe /c \" + f.getPath() + \"\";\n Runtime.getRuntime().exec(command); \n }\n\n public static void main( String[] argv ) {\n test thisApp = new test();\n try {\n thisApp.openDocument( \"c:\\\\so\\\\My Doc.doc\");\n }\n catch( IOException e ) {\n e.printStackTrace();\n }\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
54,866 |
<p>I have string like this</p>
<pre><code> /c SomeText\MoreText "Some Text\More Text\Lol" SomeText
</code></pre>
<p>I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design.</p>
<p>This is in C# btw.</p>
<p><strong>EDIT:</strong> My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx.</p>
<pre><code>private string[] tokenize(string input)
{
string[] tokens = input.Split(' ');
List<String> output = new List<String>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].StartsWith("\""))
{
string temp = tokens[i];
int k = 0;
for (k = i + 1; k < tokens.Length; k++)
{
if (tokens[k].EndsWith("\""))
{
temp += " " + tokens[k];
break;
}
else
{
temp += " " + tokens[k];
}
}
output.Add(temp);
i = k + 1;
}
else
{
output.Add(tokens[i]);
}
}
return output.ToArray();
}
</code></pre>
|
[
{
"answer_id": 54880,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Text.RegularExpressions;\n\npublic class Test\n{\n\n public static void Main ()\n {\n\n // Define a regular expression for repeated words.\n Regex rx = new Regex(@\"\\b(?<word>\\w+)\\s+(\\k<word>)\\b\",\n RegexOptions.Compiled | RegexOptions.IgnoreCase);\n\n // Define a test string. \n string text = \"The the quick brown fox fox jumped over the lazy dog dog.\";\n\n // Find matches.\n MatchCollection matches = rx.Matches(text);\n\n // Report the number of matches found.\n Console.WriteLine(\"{0} matches found in:\\n {1}\", \n matches.Count, \n text);\n\n // Report on each match.\n foreach (Match match in matches)\n {\n GroupCollection groups = match.Groups;\n Console.WriteLine(\"'{0}' repeated at positions {1} and {2}\", \n groups[\"word\"].Value, \n groups[0].Index, \n groups[1].Index);\n }\n\n }\n\n}\n// The example produces the following output to the console:\n// 3 matches found in:\n// The the quick brown fox fox jumped over the lazy dog dog.\n// 'The' repeated at positions 0 and 4\n// 'fox' repeated at positions 20 and 25\n// 'dog' repeated at positions 50 and 54\n"
},
{
"answer_id": 54928,
"author": "Todd Myhre",
"author_id": 5626,
"author_profile": "https://Stackoverflow.com/users/5626",
"pm_score": 5,
"selected": true,
"text": "([^\"^\\s]+)\\s*|\"([^\"]+)\"\\s*\n Dim token As String\nDim r As Regex = New Regex(\"([^\"\"^\\s]+)\\s*|\"\"([^\"\"]+)\"\"\\s*\")\nDim m As Match = r.Match(\"this is a \"\"test string\"\"\")\n\nWhile m.Success\n token = m.Groups(1).ToString\n If token.length = 0 And m.Groups.Count > 1 Then\n token = m.Groups(2).ToString\n End If\n m = m.NextMatch\nEnd While\n"
},
{
"answer_id": 55064,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "string[] tokens = System.Text.RegularExpressions.Regex.Split(this.BuildArgs, @\"[^\\t]+\\t|\"\"[^\"\"]+\"\"\\t\");\n"
},
{
"answer_id": 55201,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 2,
"selected": false,
"text": " private enum State\n {\n None = 0,\n InTokin,\n InQuote\n }\n\n private static IEnumerable<string> Tokinize(string input)\n {\n input += ' '; // ensure we end on whitespace\n State state = State.None;\n State? next = null; // setting the next state implies that we have found a tokin\n StringBuilder sb = new StringBuilder();\n foreach (char c in input)\n {\n switch (state)\n {\n default:\n case State.None:\n if (char.IsWhiteSpace(c))\n continue;\n else if (c == '\"')\n {\n state = State.InQuote;\n continue;\n }\n else\n state = State.InTokin;\n break;\n case State.InTokin:\n if (char.IsWhiteSpace(c))\n next = State.None;\n else if (c == '\"')\n next = State.InQuote;\n break;\n case State.InQuote:\n if (c == '\"')\n next = State.None;\n break;\n }\n if (next.HasValue)\n {\n yield return sb.ToString();\n sb = new StringBuilder();\n state = next.Value;\n next = null;\n }\n else\n sb.Append(c);\n }\n }\n IEnumerable<string> input"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
54,867 |
<p>What is the difference between old style and new style classes in Python? When should I use one or the other?</p>
|
[
{
"answer_id": 54873,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 10,
"selected": true,
"text": "x x.__class__ x type(x) <type\n 'instance'> type(x) x.__class__ x.__class__ object"
},
{
"answer_id": 242700,
"author": "Halo",
"author_id": 5306,
"author_profile": "https://Stackoverflow.com/users/5306",
"pm_score": 3,
"selected": false,
"text": "object class Classname(object): class Classname:"
},
{
"answer_id": 1203997,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 8,
"selected": false,
"text": "class NewStyleClass(object):\n pass\n\nclass AnotherNewStyleClass(NewStyleClass):\n pass\n class OldStyleClass():\n pass\n"
},
{
"answer_id": 16193572,
"author": "Xiao Hanyu",
"author_id": 2310396,
"author_profile": "https://Stackoverflow.com/users/2310396",
"pm_score": 5,
"selected": false,
"text": "object super"
},
{
"answer_id": 16295402,
"author": "jamylak",
"author_id": 1219006,
"author_profile": "https://Stackoverflow.com/users/1219006",
"pm_score": 3,
"selected": false,
"text": "super(Foo, self) Foo self super(type[, object-or-type]) super()"
},
{
"answer_id": 19273761,
"author": "ychaouche",
"author_id": 212044,
"author_profile": "https://Stackoverflow.com/users/212044",
"pm_score": 5,
"selected": false,
"text": "class Person():\n _names_cache = {}\n def __init__(self,name):\n self.name = name\n def __new__(cls,name):\n return cls._names_cache.setdefault(name,object.__new__(cls,name))\n\nahmed1 = Person(\"Ahmed\")\nahmed2 = Person(\"Ahmed\")\nprint ahmed1 is ahmed2\nprint ahmed1\nprint ahmed2\n\n\n>>> False\n<__main__.Person instance at 0xb74acf8c>\n<__main__.Person instance at 0xb74ac6cc>\n>>>\n\n class Person(object):\n _names_cache = {}\n def __init__(self,name):\n self.name = name\n def __new__(cls,name):\n return cls._names_cache.setdefault(name,object.__new__(cls,name))\n\nahmed1 = Person(\"Ahmed\")\nahmed2 = Person(\"Ahmed\")\nprint ahmed2 is ahmed1\nprint ahmed1\nprint ahmed2\n\n>>> True\n<__main__.Person object at 0xb74ac66c>\n<__main__.Person object at 0xb74ac66c>\n>>>\n"
},
{
"answer_id": 19950198,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 8,
"selected": false,
"text": "Exception __slots__ __mro__ class C: i = 0\nclass C1(C): pass\nclass C2(C): i = 2\nclass C12(C1, C2): pass\nclass C21(C2, C1): pass\n\nassert C12().i == 0\nassert C21().i == 2\n\ntry:\n C12.__mro__\nexcept AttributeError:\n pass\nelse:\n assert False\n __mro__ class C(object): i = 0\nclass C1(C): pass\nclass C2(C): i = 2\nclass C12(C1, C2): pass\nclass C21(C2, C1): pass\n\nassert C12().i == 2\nassert C21().i == 2\n\nassert C12.__mro__ == (C12, C1, C2, C, object)\nassert C21.__mro__ == (C21, C2, C1, C, object)\n Exception # OK, old:\nclass Old: pass\ntry:\n raise Old()\nexcept Old:\n pass\nelse:\n assert False\n\n# TypeError, new not derived from `Exception`.\nclass New(object): pass\ntry:\n raise New()\nexcept TypeError:\n pass\nelse:\n assert False\n\n# OK, derived from `Exception`.\nclass New(Exception): pass\ntry:\n raise New()\nexcept New:\n pass\nelse:\n assert False\n\n# `'str'` is a new style object, so you can't raise it:\ntry:\n raise 'str'\nexcept TypeError:\n pass\nelse:\n assert False\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
54,877 |
<p>I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to <code>append a div</code> to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:</p>
<pre><code>$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());
</code></pre>
<p>This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original <code>#somediv > ul</code> selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the <code>after</code> and put my <code>#someotherdiv</code> into it?</p>
|
[
{
"answer_id": 54897,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "after() .nextAll( [expr] ) Find all sibling elements after the current element.\n Use an optional expression to filter the matched set. $(\"#somediv > ul\")\n .after(\"<div id='xxx'></div>\")\n .nextAll('#xxx')\n .append($(\"#someotherdiv\").clone());\n"
},
{
"answer_id": 54949,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "$(\"<div id='xxx'></div>\").insertAfter(\"#somediv > ul\").append($(\"#someotherdiv\").clone())\n"
},
{
"answer_id": 54970,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 4,
"selected": true,
"text": "insertAfter() $(\"<div id='xxx'></div>\")\n .append($(\"#someotherdiv\").clone())\n .insertAfter(\"#somediv > ul\")\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] |
54,882 |
<p>What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.</p>
|
[
{
"answer_id": 54887,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 2,
"selected": false,
"text": "e.getStackTrace();\n e.printStackTrace()\n"
},
{
"answer_id": 54892,
"author": "Johan Lübcke",
"author_id": 4220,
"author_profile": "https://Stackoverflow.com/users/4220",
"pm_score": 2,
"selected": false,
"text": "System.out.println(\"Oops, the bad thing happened\");\nnew IllegalStateException().printStackTrace();\n"
},
{
"answer_id": 56284,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "String exception = \"\";\nfor (StackTraceElement element : e.getStackTrace())\n exception += element.toString() + \"\\n\";\n"
},
{
"answer_id": 59775,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 4,
"selected": false,
"text": "Exception e = new Exception();\nlog.error(\"error here\", e);\n"
},
{
"answer_id": 1742636,
"author": "sleske",
"author_id": 43681,
"author_profile": "https://Stackoverflow.com/users/43681",
"pm_score": 1,
"selected": false,
"text": "StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()\n Thread.dumpStack()"
},
{
"answer_id": 36439329,
"author": "minipif",
"author_id": 1440076,
"author_profile": "https://Stackoverflow.com/users/1440076",
"pm_score": 2,
"selected": false,
"text": "Thread.dumpStack();\n new Exception(\"Stack trace\").printStackTrace();\n System.out printStackTrace() new Exception(\"Stack trace\").printStackTrace(System.out);\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220/"
] |
54,886 |
<p>Alright it can be a lame question, but everybody uses these things differently. What's some of the best time savers out there for this IDE.
<BR><BR>Tom</p>
|
[
{
"answer_id": 59413,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 4,
"selected": false,
"text": "JdbcTemplate createJdbcTemplate() void someQuery() {\n createJdbcTemplate()\n}\n createJdbcTemplate() void someQuery() {\n JdbcTemplate myTemplate = createJdbcTemplate();\n}\n"
},
{
"answer_id": 104569,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 5,
"selected": false,
"text": "if(i==0|)\n if(i==0) {|\n"
},
{
"answer_id": 133850,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 5,
"selected": false,
"text": "CWAR ClassWithAReallyLongName"
},
{
"answer_id": 548271,
"author": "Ascalonian",
"author_id": 65230,
"author_profile": "https://Stackoverflow.com/users/65230",
"pm_score": 1,
"selected": false,
"text": "//FIXME: This accidentally deletes user accounts\nuser.account().delete();\n\n//TODO: Add some validation before assigning everyone as admin\nuser.setPrivilege(\"Admin\");\n public class SomeBean {\n private static int FIRST_VALUE = 0;\n private static int SECOND_VALUE = 1;\n ...\n private static int THOUSANDTH_VALUE = 1000;\n}\n"
},
{
"answer_id": 591345,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "RuntimeException NullPointerException"
},
{
"answer_id": 602021,
"author": "jtgameover",
"author_id": 65927,
"author_profile": "https://Stackoverflow.com/users/65927",
"pm_score": 3,
"selected": false,
"text": "Breakpoint Properties Enable Condition"
},
{
"answer_id": 628785,
"author": "Andrey Tarantsov",
"author_id": 58146,
"author_profile": "https://Stackoverflow.com/users/58146",
"pm_score": 7,
"selected": false,
"text": "Display display = new |\n new Display()|\n Display display = new Display()|\n if (${arg:localVar} == null)\n throw new ${exception:link(NullPointerException,IllegalArgumentException)}(\"${arg:localVar} is null\");\n public class MyClass {\n public MyClass(int something|) {\n }\n}\n public class MyClass {\n private final Object something;\n public MyClass(Object something) {\n this.something = something;\n }\n}\n public class MyClass {\n private final Object something;\n public MyClass(Object something) {\n npe|\n this.something = something;\n }\n}\n public class MyClass {\n private final Object something;\n public MyClass(Object something) {\n if (something == null)\n throw new NullPointerException(\"something is null\");\n this.something = something;\n }\n}\n"
},
{
"answer_id": 681562,
"author": "Ma99uS",
"author_id": 20390,
"author_profile": "https://Stackoverflow.com/users/20390",
"pm_score": 3,
"selected": false,
"text": "Eclipse 3 Favorite Keyboard Shortcuts. \nby -=MaGGuS=-\n\nNavigate:\n\n• Ctrl + Shift + L – Shows useful keyboard shortcuts in popup window \n• Ctrl + H – Search.\n• Ctrl + K – Goes to next search match in a single file. Shift + Ctrl + K – goes to previous match.\n• F3 - Goes to ‘declaration’ of something. Same as Ctrl + Click.\n• Ctrl + Shift + G - Use this on a method name or variable. It will search for references in the code (all the code) to that item.\n• Ctrl + O – Shows outline view of the current class or interface.\n• Ctrl + T – Shows class hierarchy of the current class or interface. F4 – shows the same in separate tab.\n• Ctrl + Shift + T - Open Type. Search for any type globally in the workspace.\n• Ctrl + Shift + R – Open Resource. Search for any file inside workspace.\n• Ctrl + J – Incremental search. Similar to the search in firefox. It shows you results as you type. Shift + Ctrl +J - Reverse incremental search.\n• Ctrl + Q – Goes to the last edit location.\n• Ctrl + Left|Right – Go Back/Forward in history.\n• Ctrl + L – Go to line number.\n• Ctrl + E – This will give you a list of all the source code windows that are currently open. You can arrow up or down on the items to go to a tab.\n• Ctrl +PgUp|PgDown – Cycles through editor tabs.\n• Ctrl + Shift + Up|Down - Bounces you up and down through the methods in the source code.\n• Ctrl + F7 – Switches between panes (views).\n• Ctrl + ,|. – Go to the previous/next error. Great in combination with Ctrl + 1.\n• Ctrl + 1 on an error – Brings up suggestions for fixing the error. The suggestions can be clicked.\n• Ctrl + F4 – Close one source window.\n\nEdit:\n\n• Ctrl + Space – Auto-completion.\n• Ctrl + / – Toggle comment selected lines.\n• Ctrl + Shift + /|\\ – Block comment/uncomment selected lines.\n• Ctrl + Shift + F – Quickly ‘formats’ your java code based on your preferences set up under Window –> Preferences.\n• Ctrl + I – Correct indentations.\n• Alt + Up|Down – move the highlighted code up/down one line. If nothing is selected, selects the current line.\n• Ctrl + D – Delete row.\n• Alt + Shift + Up|Down|Left|Right – select increasing semantic units.\n• Ctrl + Shift + O – Organize Imports.\n• Alt + Shift + S – Brings up “Source” menu.\no Shift + Alt + S, R – Generate getter/setter.\no Shift + Alt + S, O – Generate constructor using fields.\no Shift + Alt + S, C – Generate constructor from superclass.\n• Alt + Shift + T – Brings up “Refactor” menu.\n• Alt + Shift + J – Insert javadoc comment.\n• F2 – Display javadoc popup for current item. Shift + F2 – Display javadoc in external browser.\n\nRun/Debug:\n\n• F11 / Ctrl + F11 – Execute/debug.\n• Ctrl + Shift +B – Toggle breakpoint.\n• When paused: F5 – Step into, F6 – Step over, F7 – Step out, F8 – Resume.\n• Ctrl + F2 – Terminate.\n\nEOF\n"
},
{
"answer_id": 923471,
"author": "Peter Perháč",
"author_id": 81520,
"author_profile": "https://Stackoverflow.com/users/81520",
"pm_score": 2,
"selected": false,
"text": "Alt + /\n"
},
{
"answer_id": 1369376,
"author": "Trevor Harrison",
"author_id": 131795,
"author_profile": "https://Stackoverflow.com/users/131795",
"pm_score": 5,
"selected": false,
"text": "1: public void foo()\n2: {\n3: somecode();\n4: if ( blah ) return;\n5:\n6: bar();\n7: }\n"
},
{
"answer_id": 3014198,
"author": "Abhinav Sarkar",
"author_id": 126916,
"author_profile": "https://Stackoverflow.com/users/126916",
"pm_score": 4,
"selected": false,
"text": "import X;\n\n...\nX.callSomething();\n import static X.callSomething;\n\n...\ncallSomething();\n"
},
{
"answer_id": 3164102,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 3,
"selected": false,
"text": " \"hello world!\"\n\nbecomes\nSystem.out.println(\"hello world!\");\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5659/"
] |
54,909 |
<p>I have an <code>ArrayList<String></code> that I'd like to return a copy of. <code>ArrayList</code> has a clone method which has the following signature:</p>
<pre><code>public Object clone()
</code></pre>
<p>After I call this method, how do I cast the returned Object back to <code>ArrayList<String></code>?</p>
|
[
{
"answer_id": 54911,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 1,
"selected": false,
"text": "ArrayList first = new ArrayList ();\nArrayList copy = (ArrayList) first.clone ();\n"
},
{
"answer_id": 54912,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "ArrayList newArrayList = (ArrayList) oldArrayList.clone();\n"
},
{
"answer_id": 54917,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 4,
"selected": false,
"text": "ArrayList<String> copy = new ArrayList<String>();\ncopy.addAll(original);\n"
},
{
"answer_id": 54922,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 2,
"selected": false,
"text": "ArrayList<String> orig = new ArrayList<String>();\nArrayList<String> copy = (ArrayList<String>) orig.clone()\n"
},
{
"answer_id": 55132,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 4,
"selected": false,
"text": "//assume oldList exists and has data in it.\nList<String> newList = new ArrayList<String>();\nCollections.copy(newList, oldList);\n"
},
{
"answer_id": 56383,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 8,
"selected": false,
"text": "List<String> strs;\n...\nList<String> newStrs = new ArrayList<>(strs);\n"
},
{
"answer_id": 8971483,
"author": "Petr",
"author_id": 1164753,
"author_profile": "https://Stackoverflow.com/users/1164753",
"pm_score": 1,
"selected": false,
"text": " public static <T extends Object> List<T> clone(List<T> list) {\n try {\n List<T> c = list.getClass().newInstance();\n for(T t: list) {\n T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);\n c.add(copy);\n }\n return c;\n } catch(Exception e) {\n throw new RuntimeException(\"List cloning unsupported\",e);\n }\n}\n"
},
{
"answer_id": 10251692,
"author": "GeRmAn",
"author_id": 1347278,
"author_profile": "https://Stackoverflow.com/users/1347278",
"pm_score": 4,
"selected": false,
"text": "ArrayList copy = new ArrayList (original.size());\nCollections.copy(copy, original);\n"
},
{
"answer_id": 25785306,
"author": "Ahmed Hamdy",
"author_id": 319876,
"author_profile": "https://Stackoverflow.com/users/319876",
"pm_score": 2,
"selected": false,
"text": "java.util.List List list = new ArrayList();\nList list2 = ((List) ( (ArrayList) list).clone());\n List List ArrayList"
},
{
"answer_id": 35014446,
"author": "Simon Jenkins",
"author_id": 5763141,
"author_profile": "https://Stackoverflow.com/users/5763141",
"pm_score": 4,
"selected": false,
"text": "import static java.util.stream.Collectors.toList;\n List<AnObject> clone = myList.stream().collect(toList());\n"
},
{
"answer_id": 35430941,
"author": "Uri Shalit",
"author_id": 5019818,
"author_profile": "https://Stackoverflow.com/users/5019818",
"pm_score": 3,
"selected": false,
"text": "ImmutableList.copyOf(list);\n"
},
{
"answer_id": 54040913,
"author": "Robert",
"author_id": 6113110,
"author_profile": "https://Stackoverflow.com/users/6113110",
"pm_score": 3,
"selected": false,
"text": "List<String> shallowClonedList = new ArrayList<>(listOfStrings);\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
54,926 |
<p>Is it possible, in Java, to make a <code>JPanel</code> skip drawing its background thus being transparent except for the components on it?</p>
|
[
{
"answer_id": 54927,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 6,
"selected": true,
"text": "setOpaque(false)"
},
{
"answer_id": 22712998,
"author": "user9349193413",
"author_id": 736999,
"author_profile": "https://Stackoverflow.com/users/736999",
"pm_score": 1,
"selected": false,
"text": "class TransparentJPanel extends JPanel\n{\n TransparentJPanel()\n {\n super() ;\n this.setOpaque( false ) ; // this will make the JPanel transparent \n // but not its components (JLabel, TextField etc.)\n this.setLayout( null ) ;\n }\n}\n"
},
{
"answer_id": 44391870,
"author": "Mustajeeb ur Rehman",
"author_id": 6716774,
"author_profile": "https://Stackoverflow.com/users/6716774",
"pm_score": 2,
"selected": false,
"text": "JPanel JPanel JPanel JFrame"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
54,929 |
<blockquote>
<p>This question exists because it has
historical significance, but it is not
considered a good, on-topic question
for this site, <strong>so please do not use it
as evidence that you can ask similar
questions here.</strong></p>
<p>More info: <a href="https://stackoverflow.com/faq">https://stackoverflow.com/faq</a></p>
</blockquote>
<hr>
<p>There are always features that would be useful in fringe scenarios, but for that very reason most people don't know them. I am asking for features that are not typically taught by the text books.</p>
<p>What are the ones that you know?</p>
|
[
{
"answer_id": 55112,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 6,
"selected": false,
"text": "#ifdef DEBUG \n if (Context.Request.QueryString[\"DoTrace\"] == \"true\")\n {\n Trace.IsEnabled = true;\n Trace.Write(\"Application:TraceStarted\");\n }\n#endif\n public class Class1:System.Web.UI.Page\n {\n public TextBox tbLogin;\n\n protected void Page_Load(object sender, EventArgs e)\n {\n\n if (tbLogin!=null)\n tbLogin.Text = \"Hello World\";\n }\n }\n <%@ Page Language=\"C#\" AutoEventWireup=\"true\" Inherits=\"Namespace.Class1\" %>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:TextBox ID=\"tbLogin\" runat=\"server\"></asp: TextBox >\n </div>\n </form>\n"
},
{
"answer_id": 55176,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": false,
"text": " Request.Params[Control.UniqueId] \n"
},
{
"answer_id": 55195,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "<httpHandlers>"
},
{
"answer_id": 55229,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 7,
"selected": false,
"text": "throw new HttpException(404, \"Article not found\");\n"
},
{
"answer_id": 55259,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": " protected override void AddParsedSubObject(object obj)\n { var literal = obj as LiteralControl;\n if (literal != null) Controls.Add(parseControl(literal.Text));\n else base.AddParsedSubObject(obj);\n }\n <uc:MyControl runat='server'>\n ...this text is parsed as a LiteralControl...\n </uc:MyControl>\n"
},
{
"answer_id": 55348,
"author": "Kevin Goff",
"author_id": 1940,
"author_profile": "https://Stackoverflow.com/users/1940",
"pm_score": 4,
"selected": false,
"text": "<@Page>"
},
{
"answer_id": 58445,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 5,
"selected": false,
"text": "<asp:Label runat=\"server\" ID=\"labelText\" \n ie:Text=\"This is IE text\" \n mozilla:Text=\"This is Firefox text\" \n Text=\"This is general text\" \n/>\n"
},
{
"answer_id": 61100,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 4,
"selected": false,
"text": "HttpContext.RewritePath(\"PageHandler.aspx?Param1=SomeParms1&Param2=SomeParams2\");\n"
},
{
"answer_id": 75170,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 8,
"selected": false,
"text": "<system.net>\n <mailSettings>\n <smtp deliveryMethod=\"SpecifiedPickupDirectory\">\n <specifiedPickupDirectory pickupDirectoryLocation=\"c:\\Temp\\\" />\n </smtp>\n </mailSettings>\n</system.net>\n"
},
{
"answer_id": 170091,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 2,
"selected": false,
"text": "Label label = (Label)Page.FindControl(\"UserControl1$Label1\");\n"
},
{
"answer_id": 194142,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 5,
"selected": false,
"text": "<%--\n <div>\n <asp:Button runat=\"server\" id=\"btnOne\"/>\n </div>\n--%>\n"
},
{
"answer_id": 194153,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": false,
"text": "<input type=\"checkbox\" name=\"roles\" value='<%# Eval(\"Name\") %>' \n <%# ((bool) Eval(\"InRole\")) ? \"checked\" : \"\" %> \n <%# ViewData.Model.IsInRole(\"Admin\") ? \"\" : \"disabled\" %> />\n"
},
{
"answer_id": 384970,
"author": "Craig McKeachie",
"author_id": 48175,
"author_profile": "https://Stackoverflow.com/users/48175",
"pm_score": 5,
"selected": false,
"text": "void Page_Init (object sender, EventArgs e) {\n ViewStateUserKey = Session.SessionID;\n}\n"
},
{
"answer_id": 491233,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 5,
"selected": false,
"text": "<%@ webhandler language=\"C#\" class=\"MyNamespace.MyHandler\" %>\n using System;\nusing System.IO;\nusing System.Web;\n\nnamespace MyNamespace\n{\n public class MyHandler: IHttpHandler\n {\n public void ProcessRequest (HttpContext context)\n { \n context.Response.ContentType = \"text/xml\";\n string myString = SomeLibrary.SomeClass.SomeMethod();\n context.Response.Write(myString);\n }\n\n public bool IsReusable\n {\n get { return true; }\n }\n }\n}\n"
},
{
"answer_id": 491262,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 6,
"selected": false,
"text": "<%@ MasterType VirtualPath=\"~/Masters/MyMainMasterPage.master\" %>\n <%@ MasterType TypeName=\"MyMainMasterPage\" %>\n"
},
{
"answer_id": 572275,
"author": "andleer",
"author_id": 64262,
"author_profile": "https://Stackoverflow.com/users/64262",
"pm_score": 5,
"selected": false,
"text": "Text = '<%$ Code: GetText() %>'\nText = '<%$ Code: MyStaticClass.MyStaticProperty %>'\nText = '<%$ Code: DateTime.Now.ToShortDateString() %>'\nMaxLenth = '<%$ Code: 30 + 40 %>'\n <system.web> \n <compilation debug=\"true\">\n <expressionBuilders>\n <add expressionPrefix=\"Code\" type=\"CodeExpressionBuilder\" />\n [ExpressionPrefix(\"Code\")]\npublic class CodeExpressionBuilder : ExpressionBuilder\n{\n public override CodeExpression GetCodeExpression(\n BoundPropertyEntry entry,\n object parsedData,\n ExpressionBuilderContext context)\n { \n return new CodeSnippetExpression(entry.Expression);\n }\n} \n"
},
{
"answer_id": 818365,
"author": "Troy Hunt",
"author_id": 73948,
"author_profile": "https://Stackoverflow.com/users/73948",
"pm_score": 6,
"selected": false,
"text": "<configuration>\n <system.web>\n <deployment retail=\"true\"/>\n </system.web>\n</configuration>\n"
},
{
"answer_id": 989225,
"author": "Khaled Musaied",
"author_id": 90657,
"author_profile": "https://Stackoverflow.com/users/90657",
"pm_score": 3,
"selected": false,
"text": "if (Request.Browser.Crawler){\n HideArticleComments();\n"
},
{
"answer_id": 1069756,
"author": "Graham",
"author_id": 131785,
"author_profile": "https://Stackoverflow.com/users/131785",
"pm_score": 4,
"selected": false,
"text": "WebRequest myRequest = WebRequest.Create(\"http://www.google.com\");\nWebResponse myResponse = myRequest.GetResponse();\nStreamReader sr = new StreamReader(myResponse.GetResponseStream());\n\n// here's page's response loaded into a string for further use\n\nString thisReturn = sr.ReadToEnd().Trim();\n"
},
{
"answer_id": 1078420,
"author": "Scott Hanselman",
"author_id": 6380,
"author_profile": "https://Stackoverflow.com/users/6380",
"pm_score": 6,
"selected": false,
"text": "<compilation optimizeCompilations=\"true\">\n"
},
{
"answer_id": 1161881,
"author": "Dan Diplo",
"author_id": 140392,
"author_profile": "https://Stackoverflow.com/users/140392",
"pm_score": 6,
"selected": false,
"text": "[System.Web.Services.WebMethod()] \n[System.Web.Script.Services.ScriptMethod()] \npublic static List<string> GetFruitBeginingWith(string letter)\n{\n List<string> products = new List<string>() \n { \n \"Apple\", \"Banana\", \"Blackberry\", \"Blueberries\", \"Orange\", \"Mango\", \"Melon\", \"Peach\"\n };\n\n return products.Where(p => p.StartsWith(letter)).ToList();\n}\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePageMethods=\"true\" />\n <input type=\"button\" value=\"Get Fruit\" onclick=\"GetFruit('B')\" />\n </div>\n</form>\n <script type=\"text/javascript\">\n function GetFruit(l)\n {\n PageMethods.GetFruitBeginingWith(l, OnGetFruitComplete);\n }\n\n function OnGetFruitComplete(result)\n {\n alert(\"You got fruit: \" + result);\n }\n</script>\n"
},
{
"answer_id": 1205724,
"author": "CraigTP",
"author_id": 57477,
"author_profile": "https://Stackoverflow.com/users/57477",
"pm_score": 5,
"selected": false,
"text": "<pages>\n <tagMapping>\n <clear />\n <add tagType=\"System.Web.UI.WebControls.DropDownList\"\n mappedTagType=\"SmartDropDown\"/>\n </tagMapping>\n</pages>\n"
},
{
"answer_id": 1355965,
"author": "MRG",
"author_id": 46281,
"author_profile": "https://Stackoverflow.com/users/46281",
"pm_score": 3,
"selected": false,
"text": "if( Request.IsLocal )\n{\n LoadLocalAdminMailSettings();\n}\nelse\n{\n LoadServerAdminMailSettings();\n}\n"
},
{
"answer_id": 1738028,
"author": "RickNZ",
"author_id": 211378,
"author_profile": "https://Stackoverflow.com/users/211378",
"pm_score": 6,
"selected": false,
"text": "if (this.Response.IsClientConnected)\n{\n // long-running task\n}\n"
},
{
"answer_id": 1810914,
"author": "Wagner Danda da Silva Filho",
"author_id": 222328,
"author_profile": "https://Stackoverflow.com/users/222328",
"pm_score": 3,
"selected": false,
"text": " <system.web>\n ....\n <compilation debug=\"true\" tempDirectory=\"R:\\ASP_NET_TempFiles\\\">\n ....\n </compilation>\n ....\n </system.web>\n"
},
{
"answer_id": 2138151,
"author": "womp",
"author_id": 63756,
"author_profile": "https://Stackoverflow.com/users/63756",
"pm_score": 4,
"selected": false,
"text": "ApplicationHost HttpRuntime HttpApplication HostingClass host = ApplicationHost.CreateApplicationHost(typeof(HostingClass), \n \"/virtualpath\", \"physicalPath\");\nhost.ProcessPage(urlToAspxFile); \n public class HostingClass : MarshalByRefObject\n{\n public void ProcessPage(string url)\n {\n using (StreamWriter sw = new StreamWriter(\"C:\\temp.html\"))\n {\n SimpleWorkerRequest worker = new SimpleWorkerRequest(url, null, sw);\n HttpRuntime.ProcessRequest(worker);\n }\n // Ta-dah! C:\\temp.html has some html for you.\n }\n}\n"
},
{
"answer_id": 3002736,
"author": "Diego C.",
"author_id": 80268,
"author_profile": "https://Stackoverflow.com/users/80268",
"pm_score": 2,
"selected": false,
"text": "<script runat=\"server\">\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Response.Write(\"Look Ma', I didn't even had to build!\")\n End Sub\n\n</script>\n"
},
{
"answer_id": 3011857,
"author": "Dave",
"author_id": 69039,
"author_profile": "https://Stackoverflow.com/users/69039",
"pm_score": -1,
"selected": false,
"text": "Trim(rsData(\"FieldName\").Value & \" \") CLng(\"0\" & Trim(rsData(\"FieldName\").Value & \" \"))"
},
{
"answer_id": 3163868,
"author": "Ramesh",
"author_id": 168464,
"author_profile": "https://Stackoverflow.com/users/168464",
"pm_score": -1,
"selected": false,
"text": "new Protected void button_click(sender object, e System.EventArgs) \n {\n Response.Write(\"Look Ma', I Am code behind code!\") \n }\n <script runat=\"server\"> \n Protected void new button_click(sender object, e System.EventArgs) \n {\n Response.Write(\"Look Ma', I am overrided method!\") \n }\n\n</script\n"
},
{
"answer_id": 4412956,
"author": "Ryan Shripat",
"author_id": 1943,
"author_profile": "https://Stackoverflow.com/users/1943",
"pm_score": 4,
"selected": false,
"text": " <appSettings>\n <add key=\"webServiceURL\" value=\"https://some/ws.url\" />\n <!-- some more keys -->\n </appSettings>\n web.config <appSettings configSource=\"myAppSettings.config\" />\n myAppSettings.config <appSettings> \n <add key=\"webServiceURL\" value=\"https://some/ws.url\" />\n <!-- some more keys -->\n </appSettings>\n"
},
{
"answer_id": 7574607,
"author": "roland",
"author_id": 313353,
"author_profile": "https://Stackoverflow.com/users/313353",
"pm_score": 3,
"selected": false,
"text": "System.Web.UI.Page System.Web.UI.Page web.config <system.web>\n <pages pageBaseType=\"MyBasePageClass\" />\n</system.web>\n <%@ Page Language=\"C#\" AutoEventWireup=\"true\" %>"
},
{
"answer_id": 8461437,
"author": "Michiel van Oosterhout",
"author_id": 4830,
"author_profile": "https://Stackoverflow.com/users/4830",
"pm_score": 0,
"selected": false,
"text": "<%@ Control Language=\"C#\" CodeFile=\"TemplatedControl.ascx.cs\" Inherits=\"TemplatedControl\" %>\n\n<div class=\"header\">\n <asp:PlaceHolder ID=\"HeaderPlaceHolder\" runat=\"server\" />\n</div>\n<div class=\"body\">\n <asp:PlaceHolder ID=\"BodyPlaceHolder\" runat=\"server\" />\n</div>\n ITemplate [ParseChildren] [PersistenceMode] using System.Web.UI;\n\n[ParseChildren(true)]\npublic partial class TemplatedControl : System.Web.UI.UserControl\n{\n [PersistenceMode(PersistenceMode.InnerProperty)]\n public ITemplate Header { get; set; }\n\n [PersistenceMode(PersistenceMode.InnerProperty)]\n public ITemplate Body { get; set; }\n\n void Page_Init()\n {\n if (Header != null)\n Header.InstantiateIn(HeaderPlaceHolder);\n\n if (Body != null)\n Body.InstantiateIn(BodyPlaceHolder);\n }\n}\n <%@ Register TagPrefix=\"uc\" TagName=\"TemplatedControl\" Src=\"TemplatedControl.ascx\" %>\n\n<uc:TemplatedControl runat=\"server\">\n <Header>Lorem ipsum</Header>\n <Body>\n // You can add literal text, HTML and server controls to the templates\n <p>Hello <asp:Label runat=\"server\" Text=\"world\" />!</p>\n </Body>\n</uc:TemplatedControl>\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] |
54,952 |
<p>We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized logs.</p>
<p>It is possible to configure the JVM so it generates UTF-8, using <code>-Dfile.encoding=UTF-8</code> as arguments to the JVM. It works fine, but the output on a Windows console is garbled.</p>
<p>Then, we can set the code page of the console to 65001 (<code>chcp 65001</code>), but in this case, the <code>.bat</code> files do not work. This means that when we try to launch our application through our script (named start.bat), absolutely nothing happens. The command simple returns:</p>
<pre><code>C:\Application> chcp 65001
Activated code page: 65001
C:\Application> start.bat
C:\Application>
</code></pre>
<p>But without <code>chcp 65001</code>, there is no problem, and the application can be launched.</p>
<p>Any hints about that?</p>
|
[
{
"answer_id": 55307,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "chcp 65001 && start.bat chcp"
},
{
"answer_id": 265734,
"author": "Renato Soffiatto",
"author_id": 30477,
"author_profile": "https://Stackoverflow.com/users/30477",
"pm_score": 0,
"selected": false,
"text": "lang=pt_BR.ISO-8859-1 /usr/local/xxxx\n"
},
{
"answer_id": 8921509,
"author": "YIN SHAN",
"author_id": 1157731,
"author_profile": "https://Stackoverflow.com/users/1157731",
"pm_score": 3,
"selected": false,
"text": "import com.sun.jna.Native;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.ptr.IntByReference;\nimport com.sun.jna.win32.StdCallLibrary;\n\n/** For unicode output on windows platform\n * @author Sandy_Yin\n * \n */\npublic class Console {\n private static Kernel32 INSTANCE = null;\n\n public interface Kernel32 extends StdCallLibrary {\n public Pointer GetStdHandle(int nStdHandle);\n\n public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer,\n int nNumberOfCharsToWrite,\n IntByReference lpNumberOfCharsWritten, Pointer lpReserved);\n }\n\n static {\n String os = System.getProperty(\"os.name\").toLowerCase();\n if (os.startsWith(\"win\")) {\n INSTANCE = (Kernel32) Native\n .loadLibrary(\"kernel32\", Kernel32.class);\n }\n }\n\n public static void println(String message) {\n boolean successful = false;\n if (INSTANCE != null) {\n Pointer handle = INSTANCE.GetStdHandle(-11);\n char[] buffer = message.toCharArray();\n IntByReference lpNumberOfCharsWritten = new IntByReference();\n successful = INSTANCE.WriteConsoleW(handle, buffer, buffer.length,\n lpNumberOfCharsWritten, null);\n if(successful){\n System.out.println();\n }\n }\n if (!successful) {\n System.out.println(message);\n }\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430323/"
] |
54,957 |
<p>I have lots and lots of data in various structures. Are there any better platforms other than Excel charts which can help me. </p>
<p>thanks</p>
|
[
{
"answer_id": 9612148,
"author": "mikera",
"author_id": 214010,
"author_profile": "https://Stackoverflow.com/users/214010",
"pm_score": 0,
"selected": false,
"text": "(view (histogram (sample-normal 1000)))\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5663/"
] |
54,963 |
<p>I've got a lot of ugly code that looks like this:</p>
<pre><code>if (!string.IsNullOrEmpty(ddlFileName.SelectedItem.Text))
results = results.Where(x => x.FileName.Contains(ddlFileName.SelectedValue));
if (chkFileName.Checked)
results = results.Where(x => x.FileName == null);
if (!string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text))
results = results.Where(x => x.IpAddress.Contains(ddlIPAddress.SelectedValue));
if (chkIPAddress.Checked)
results = results.Where(x => x.IpAddress == null);
...etc.
</code></pre>
<p><code>results</code> is an <code>IQueryable<MyObject></code>.<br>
The idea is that for each of these innumerable dropdowns and checkboxes, if the dropdown has something selected, the user wants to match that item. If the checkbox is checked, the user wants specifically those records where that field is null or an empty string. (The UI doesn't let both be selected at the same time.) This all adds to the LINQ Expression which gets executed at the end, after we've added all the conditions.</p>
<p>It <em>seems</em> like there ought to be some way to pull out an <code>Expression<Func<MyObject, bool>></code> or two so that I can put the repeated parts in a method and just pass in what changes. I've done this in other places, but this set of code has me stymied. (Also, I'd like to avoid "Dynamic LINQ", because I want to keep things type-safe if possible.) Any ideas?</p>
|
[
{
"answer_id": 54981,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "results = results.Where(x => \n (string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) || x.FileName.Contains(ddlFileName.SelectedValue))\n && (!chkFileName.Checked || string.IsNullOrEmpty(x.FileName))\n && ...);\n"
},
{
"answer_id": 55069,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "var results =\n //get your inital results\n from x in GetInitialResults()\n //either we don't need to check, or the check passes\n where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue)\n where !chkFileName.Checked ||\n string.IsNullOrEmpty(x.FileName)\n where string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n x.FileName.Contains(ddlIPAddress.SelectedValue)\n where !chkIPAddress.Checked ||\n string.IsNullOrEmpty(x. IpAddress)\n select x;\n"
},
{
"answer_id": 55443,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "static public IQueryable<Activity> AddCondition(\n this IQueryable<Activity> results,\n DropDownList ddl, \n Expression<Func<Activity, bool>> containsCondition)\n{\n if (!string.IsNullOrEmpty(ddl.SelectedItem.Text))\n results = results.Where(containsCondition);\n return results;\n}\nstatic public IQueryable<Activity> AddCondition(\n this IQueryable<Activity> results,\n CheckBox chk, \n Expression<Func<Activity, bool>> emptyCondition)\n{\n if (chk.Checked)\n results = results.Where(emptyCondition);\n return results;\n}\n results = results.AddCondition(ddlFileName, x => x.FileName.Contains(ddlFileName.SelectedValue));\nresults = results.AddCondition(chkFileName, x => x.FileName == null || x.FileName.Equals(string.Empty));\n\nresults = results.AddCondition(ddlIPAddress, x => x.IpAddress.Contains(ddlIPAddress.SelectedValue));\nresults = results.AddCondition(chkIPAddress, x => x.IpAddress == null || x.IpAddress.Equals(string.Empty));\n"
},
{
"answer_id": 55955,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "//list of predicate functions to check\nvar conditions = new List<Predicate<MyClass>> \n{\n x => string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue),\n x => !chkFileName.Checked ||\n string.IsNullOrEmpty(x.FileName),\n x => string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n x.IpAddress.Contains(ddlIPAddress.SelectedValue),\n x => !chkIPAddress.Checked ||\n string.IsNullOrEmpty(x.IpAddress)\n}\n\n//now get results\nvar results =\n from x in GetInitialResults()\n //all the condition functions need checking against x\n where conditions.All( cond => cond(x) )\n select x;\n ListBoxControl lbc;\nCheckBoxControl cbc;\nforeach( Control c in this.Controls)\n if( (lbc = c as ListBoxControl ) != null )\n conditions.Add( ... );\n else if ( (cbc = c as CheckBoxControl ) != null )\n conditions.Add( ... );\n"
},
{
"answer_id": 130791,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 0,
"selected": false,
"text": "// from Keith\nfrom x in GetInitialResults()\n //either we don't need to check, or the check passes\n where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue)\n // my search parameters encapsulate all valid ways of searching.\npublic class MySearchParameter\n{\n public string FileName { get; private set; }\n public bool FindNullFileNames { get; private set; }\n public void ConditionallySearchFileName(bool getNullFileNames, string fileName)\n {\n FindNullFileNames = getNullFileNames;\n FileName = null;\n\n // enforce either/or and disallow empty string\n if(!getNullFileNames && !string.IsNullOrEmpty(fileName) )\n {\n FileName = fileName;\n }\n }\n // ...\n}\n\n// search method in a business logic layer.\npublic IQueryable<MyClass> Search(MySearchParameter searchParameter)\n{\n IQueryable<MyClass> result = ...; // something to get the initial list.\n\n // search on Filename.\n if (searchParameter.FindNullFileNames)\n {\n result = result.Where(o => o.FileName == null);\n }\n else if( searchParameter.FileName != null )\n { // intermixing a different style, just to show an alternative.\n result = from o in result\n where o.FileName.Contains(searchParameter.FileName)\n select o;\n }\n // search on other stuff...\n\n return result;\n}\n\n// code in the UI ... \nMySearchParameter searchParameter = new MySearchParameter();\nsearchParameter.ConditionallySearchFileName(chkFileNames.Checked, drpFileNames.SelectedItem.Text);\nsearchParameter.ConditionallySearchIPAddress(chkIPAddress.Checked, drpIPAddress.SelectedItem.Text);\n\nIQueryable<MyClass> result = Search(searchParameter);\n\n// inform control to display results.\nsearchResults.Display( result );\n"
},
{
"answer_id": 132157,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 0,
"selected": false,
"text": "public static class MyObjectExtensions\n{\n public static bool IsMatchFor(this string property, string ddlText, bool chkValue)\n {\n if(ddlText!=null && ddlText!=\"\")\n {\n return property!=null && property.Contains(ddlText);\n }\n else if(chkValue==true)\n {\n return property==null || property==\"\";\n }\n // no filtering selected\n return true;\n }\n}\n var filters = new List<Expression<Func<MyObject,bool>>>\n{\n x=>x.Filename.IsMatchFor(ddlFileName.SelectedItem.Text,chkFileName.Checked),\n x=>x.IPAddress.IsMatchFor(ddlIPAddress.SelectedItem.Text,chkIPAddress.Checked),\n x=>x.Other.IsMatchFor(ddlOther.SelectedItem.Text,chkOther.Checked),\n // ... innumerable associations\n};\n var filteredResults = filters.Aggregate(results, (r,f) => r.Where(f));\n"
},
{
"answer_id": 142632,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "<empty> <null> interface IDomainObjectFilter {\n bool ShouldInclude( DomainObject o, string target );\n}\n sealed class FileNameFilter : IDomainObjectFilter {\n public bool ShouldInclude( DomainObject o, string target ) {\n return string.IsNullOrEmpty( target )\n || o.FileName.Contains( target );\n }\n}\n\n...\nddlFileName.Tag = new FileNameFilter( );\n var finalResults = ddlControls.Aggregate( initialResults, ( c, r ) => {\n var filter = c.Tag as IDomainObjectFilter;\n var target = c.SelectedValue;\n return r.Where( o => filter.ShouldInclude( o, target ) );\n} );\n sealed class DomainObjectFilter {\n private readonly Func<DomainObject,string> memberSelector_;\n public DomainObjectFilter( Func<DomainObject,string> memberSelector ) {\n this.memberSelector_ = memberSelector;\n }\n\n public bool ShouldInclude( DomainObject o, string target ) {\n string member = this.memberSelector_( o );\n return string.IsNullOrEmpty( target )\n || member.Contains( target );\n }\n}\n\n...\nddlFileName.Tag = new DomainObjectFilter( o => o.FileName );\n"
},
{
"answer_id": 142688,
"author": "loudej",
"author_id": 6056,
"author_profile": "https://Stackoverflow.com/users/6056",
"pm_score": 1,
"selected": false,
"text": "IQueryable<MyObject> results = ...;\n\nresults = results\n .Where(TestFileNameText)\n .Where(TestFileNameChecked)\n .Where(TestIPAddressText)\n .Where(TestIPAddressChecked);\n bool TestFileNameText(MyObject x)\n{\n return string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue);\n}\n\nbool TestIPAddressChecked(MyObject x)\n{\n return !chkIPAddress.Checked ||\n x.IpAddress == null;\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
54,966 |
<p>How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?</p>
<p>I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible?</p>
|
[
{
"answer_id": 55021,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CLASSES_ROOT\\Directory\\shell]\n@=\"open_x2\"\n [HKEY_CLASSES_ROOT\\Directory\\shell\\open\\command]\n@=\"C:\\Program files\\zabkat\\xplorer2\\xplorer2_UC.exe\" /T /1 \"%1\"\n xplorer2.exe \"%1\" /T /1"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] |
54,978 |
<p>My team has a command parsing library for console apps. Each team around us has their own as well. There isn't anything in the BCL so I suppose this is natural.</p>
<p>I've looked at the the module in Mono, which seems solid, and the one on CodePlex looks fine as well. There are probably others out there that will work (and I would love to hear your suggestions).</p>
<p>The real question is: how do I get my team, and others around us, to commit to just using one? </p>
|
[
{
"answer_id": 65210,
"author": "damageboy",
"author_id": 9172,
"author_profile": "https://Stackoverflow.com/users/9172",
"pm_score": 0,
"selected": false,
"text": "var p = new OptionSet () {\n { \"file=\", v => data = v },<br>\n { \"v|verbose\", v => { ++verbose } },<br>\n { \"h|?|help\", v => help = v != null },<br>\n};\nList<string> extra = p.Parse (args);\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4593/"
] |
54,989 |
<p>Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?</p>
|
[
{
"answer_id": 55004,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 1,
"selected": false,
"text": "sNewName = \"put new name here\" \n\nSet oShell = CreateObject (\"WSCript.shell\" ) \n\nsCCS = \"HKLM\\SYSTEM\\CurrentControlSet\\\" \nsTcpipParamsRegPath = sCCS & \"Services\\Tcpip\\Parameters\\\" \nsCompNameRegPath = sCCS & \"Control\\ComputerName\\\" \n\nWith oShell \n.RegDelete sTcpipParamsRegPath & \"Hostname\" \n.RegDelete sTcpipParamsRegPath & \"NV Hostname\" \n\n.RegWrite sCompNameRegPath & \"ComputerName\\ComputerName\", sNewName \n.RegWrite sCompNameRegPath & \"ActiveComputerName\\ComputerName\", sNewName \n.RegWrite sTcpipParamsRegPath & \"Hostname\", sNewName \n.RegWrite sTcpipParamsRegPath & \"NV Hostname\", sNewName \nEnd With ' oShell \n\nMsgBox \"Computer name changed, please reboot your computer\" \n"
},
{
"answer_id": 55213,
"author": "axk",
"author_id": 578,
"author_profile": "https://Stackoverflow.com/users/578",
"pm_score": 1,
"selected": false,
"text": "Set objWMIService = GetObject(\"Winmgmts:root\\cimv2\")\n\nFor Each objComputer in _\n objWMIService.InstancesOf(\"Win32_ComputerSystem\")\n\n objComputer.rename \"NewComputerName\", NULL, NULL \nNext\n"
},
{
"answer_id": 3738620,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 6,
"selected": false,
"text": "wmic wmic computersystem where name=\"%COMPUTERNAME%\" \n call rename name=\"NEW-NAME\"\n"
},
{
"answer_id": 20087946,
"author": "litao",
"author_id": 2646189,
"author_profile": "https://Stackoverflow.com/users/2646189",
"pm_score": 4,
"selected": false,
"text": "netdom renamecomputer %COMPUTERNAME% /Newname \"NEW-NAME\"\n netdom renamecomputer \"$env:COMPUTERNAME\" /Newname \"NEW-NAME\"\n"
},
{
"answer_id": 25141066,
"author": "Swapnil Gangrade",
"author_id": 2257531,
"author_profile": "https://Stackoverflow.com/users/2257531",
"pm_score": 1,
"selected": false,
"text": "psexec.exe -h -e \\\\\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force"
},
{
"answer_id": 32301265,
"author": "codechurn",
"author_id": 107762,
"author_profile": "https://Stackoverflow.com/users/107762",
"pm_score": 0,
"selected": false,
"text": "setcomputername [newname]"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
54,991 |
<p>When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later.</p>
<p>The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e.</p>
<pre><code>Guid.NewGuid().ToString("d").Substring(1,8)
</code></pre>
<p>Suggesstions? thoughts?</p>
|
[
{
"answer_id": 54994,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 5,
"selected": false,
"text": "///////////////////////////////////////////////////////////////////////////////\n// SAMPLE: Generates random password, which complies with the strong password\n// rules and does not contain ambiguous characters.\n//\n// To run this sample, create a new Visual C# project using the Console\n// Application template and replace the contents of the Class1.cs file with\n// the code below.\n//\n// THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n// \n// Copyright (C) 2004 Obviex(TM). All rights reserved.\n// \nusing System;\nusing System.Security.Cryptography;\n\n/// <summary>\n/// This class can generate random passwords, which do not include ambiguous \n/// characters, such as I, l, and 1. The generated password will be made of\n/// 7-bit ASCII symbols. Every four characters will include one lower case\n/// character, one upper case character, one number, and one special symbol\n/// (such as '%') in a random order. The password will always start with an\n/// alpha-numeric character; it will not start with a special symbol (we do\n/// this because some back-end systems do not like certain special\n/// characters in the first position).\n/// </summary>\npublic class RandomPassword\n{\n // Define default min and max password lengths.\n private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;\n private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;\n\n // Define supported password characters divided into groups.\n // You can add (or remove) characters to (from) these groups.\n private static string PASSWORD_CHARS_LCASE = \"abcdefgijkmnopqrstwxyz\";\n private static string PASSWORD_CHARS_UCASE = \"ABCDEFGHJKLMNPQRSTWXYZ\";\n private static string PASSWORD_CHARS_NUMERIC= \"23456789\";\n private static string PASSWORD_CHARS_SPECIAL= \"*$-+?_&=!%{}/\";\n\n /// <summary>\n /// Generates a random password.\n /// </summary>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n /// <remarks>\n /// The length of the generated password will be determined at\n /// random. It will be no shorter than the minimum default and\n /// no longer than maximum default.\n /// </remarks>\n public static string Generate()\n {\n return Generate(DEFAULT_MIN_PASSWORD_LENGTH, \n DEFAULT_MAX_PASSWORD_LENGTH);\n }\n\n /// <summary>\n /// Generates a random password of the exact length.\n /// </summary>\n /// <param name=\"length\">\n /// Exact password length.\n /// </param>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n public static string Generate(int length)\n {\n return Generate(length, length);\n }\n\n /// <summary>\n /// Generates a random password.\n /// </summary>\n /// <param name=\"minLength\">\n /// Minimum password length.\n /// </param>\n /// <param name=\"maxLength\">\n /// Maximum password length.\n /// </param>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n /// <remarks>\n /// The length of the generated password will be determined at\n /// random and it will fall with the range determined by the\n /// function parameters.\n /// </remarks>\n public static string Generate(int minLength,\n int maxLength)\n {\n // Make sure that input parameters are valid.\n if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)\n return null;\n\n // Create a local array containing supported password characters\n // grouped by types. You can remove character groups from this\n // array, but doing so will weaken the password strength.\n char[][] charGroups = new char[][] \n {\n PASSWORD_CHARS_LCASE.ToCharArray(),\n PASSWORD_CHARS_UCASE.ToCharArray(),\n PASSWORD_CHARS_NUMERIC.ToCharArray(),\n PASSWORD_CHARS_SPECIAL.ToCharArray()\n };\n\n // Use this array to track the number of unused characters in each\n // character group.\n int[] charsLeftInGroup = new int[charGroups.Length];\n\n // Initially, all characters in each group are not used.\n for (int i=0; i<charsLeftInGroup.Length; i++)\n charsLeftInGroup[i] = charGroups[i].Length;\n\n // Use this array to track (iterate through) unused character groups.\n int[] leftGroupsOrder = new int[charGroups.Length];\n\n // Initially, all character groups are not used.\n for (int i=0; i<leftGroupsOrder.Length; i++)\n leftGroupsOrder[i] = i;\n\n // Because we cannot use the default randomizer, which is based on the\n // current time (it will produce the same \"random\" number within a\n // second), we will use a random number generator to seed the\n // randomizer.\n\n // Use a 4-byte array to fill it with random bytes and convert it then\n // to an integer value.\n byte[] randomBytes = new byte[4];\n\n // Generate 4 random bytes.\n RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\n rng.GetBytes(randomBytes);\n\n // Convert 4 bytes into a 32-bit integer value.\n int seed = BitConverter.ToInt32(randomBytes, 0);\n\n // Now, this is real randomization.\n Random random = new Random(seed);\n\n // This array will hold password characters.\n char[] password = null;\n\n // Allocate appropriate memory for the password.\n if (minLength < maxLength)\n password = new char[random.Next(minLength, maxLength+1)];\n else\n password = new char[minLength];\n\n // Index of the next character to be added to password.\n int nextCharIdx;\n\n // Index of the next character group to be processed.\n int nextGroupIdx;\n\n // Index which will be used to track not processed character groups.\n int nextLeftGroupsOrderIdx;\n\n // Index of the last non-processed character in a group.\n int lastCharIdx;\n\n // Index of the last non-processed group.\n int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n\n // Generate password characters one at a time.\n for (int i=0; i<password.Length; i++)\n {\n // If only one character group remained unprocessed, process it;\n // otherwise, pick a random character group from the unprocessed\n // group list. To allow a special character to appear in the\n // first position, increment the second parameter of the Next\n // function call by one, i.e. lastLeftGroupsOrderIdx + 1.\n if (lastLeftGroupsOrderIdx == 0)\n nextLeftGroupsOrderIdx = 0;\n else\n nextLeftGroupsOrderIdx = random.Next(0, \n lastLeftGroupsOrderIdx);\n\n // Get the actual index of the character group, from which we will\n // pick the next character.\n nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];\n\n // Get the index of the last unprocessed characters in this group.\n lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;\n\n // If only one unprocessed character is left, pick it; otherwise,\n // get a random character from the unused character list.\n if (lastCharIdx == 0)\n nextCharIdx = 0;\n else\n nextCharIdx = random.Next(0, lastCharIdx+1);\n\n // Add this character to the password.\n password[i] = charGroups[nextGroupIdx][nextCharIdx];\n\n // If we processed the last character in this group, start over.\n if (lastCharIdx == 0)\n charsLeftInGroup[nextGroupIdx] = \n charGroups[nextGroupIdx].Length;\n // There are more unprocessed characters left.\n else\n {\n // Swap processed character with the last unprocessed character\n // so that we don't pick it until we process all characters in\n // this group.\n if (lastCharIdx != nextCharIdx)\n {\n char temp = charGroups[nextGroupIdx][lastCharIdx];\n charGroups[nextGroupIdx][lastCharIdx] = \n charGroups[nextGroupIdx][nextCharIdx];\n charGroups[nextGroupIdx][nextCharIdx] = temp;\n }\n // Decrement the number of unprocessed characters in\n // this group.\n charsLeftInGroup[nextGroupIdx]--;\n }\n\n // If we processed the last group, start all over.\n if (lastLeftGroupsOrderIdx == 0)\n lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n // There are more unprocessed groups left.\n else\n {\n // Swap processed group with the last unprocessed group\n // so that we don't pick it until we process all groups.\n if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)\n {\n int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];\n leftGroupsOrder[lastLeftGroupsOrderIdx] = \n leftGroupsOrder[nextLeftGroupsOrderIdx];\n leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;\n }\n // Decrement the number of unprocessed groups.\n lastLeftGroupsOrderIdx--;\n }\n }\n\n // Convert password characters into a string and return the result.\n return new string(password);\n }\n}\n\n/// <summary>\n/// Illustrates the use of the RandomPassword class.\n/// </summary>\npublic class RandomPasswordTest\n{\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main(string[] args)\n {\n // Print 100 randomly generated passwords (8-to-10 char long).\n for (int i=0; i<100; i++)\n Console.WriteLine(RandomPassword.Generate(8, 10));\n }\n}\n//\n// END OF FILE\n///////////////////////////////////////////////////////////////////////////////\n"
},
{
"answer_id": 54997,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 7,
"selected": false,
"text": "public string CreatePassword(int length)\n{\n const string valid = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n StringBuilder res = new StringBuilder();\n Random rnd = new Random();\n while (0 < length--)\n {\n res.Append(valid[rnd.Next(valid.Length)]);\n }\n return res.ToString();\n}\n"
},
{
"answer_id": 55023,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "string[] words = { 'bur', 'ler', 'meh', 'ree' };\nstring word = \"\";\n\nRandom rnd = new Random();\nfor (i = 0; i < 3; i++)\n word += words[rnd.Next(words.length)]\n\nint numbCount = rnd.Next(4);\nfor (i = 0; i < numbCount; i++)\n word += (2 + rnd.Next(7)).ToString();\n\nreturn word;\n"
},
{
"answer_id": 55447,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 10,
"selected": true,
"text": "System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters"
},
{
"answer_id": 4757527,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 3,
"selected": false,
"text": "string password = Guid.NewGuid().ToString(\"N\").ToLower()\n .Replace(\"1\", \"\").Replace(\"o\", \"\").Replace(\"0\",\"\")\n .Substring(0,10);\n"
},
{
"answer_id": 10600220,
"author": "Hugo",
"author_id": 1396093,
"author_profile": "https://Stackoverflow.com/users/1396093",
"pm_score": 2,
"selected": false,
"text": "public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n {\n string allowedChars = \"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789\";\n string allowedNonAlphaNum = \"!@#$%^&*()_-+=[{]};:<>|./?\";\n Random rd = new Random();\n\n if (NonAlphaNumericChars > Length || Length <= 0 || NonAlphaNumericChars < 0)\n throw new ArgumentOutOfRangeException();\n\n char[] pass = new char[Length];\n int[] pos = new int[Length];\n int i = 0, j = 0, temp = 0;\n bool flag = false;\n\n //Random the position values of the pos array for the string Pass\n while (i < Length - 1)\n {\n j = 0;\n flag = false;\n temp = rd.Next(0, Length);\n for (j = 0; j < Length; j++)\n if (temp == pos[j])\n {\n flag = true;\n j = Length;\n }\n\n if (!flag)\n {\n pos[i] = temp;\n i++;\n }\n }\n\n //Random the AlphaNumericChars\n for (i = 0; i < Length - NonAlphaNumericChars; i++)\n pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];\n\n //Random the NonAlphaNumericChars\n for (i = Length - NonAlphaNumericChars; i < Length; i++)\n pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];\n\n //Set the sorted array values by the pos array for the rigth posistion\n char[] sorted = new char[Length];\n for (i = 0; i < Length; i++)\n sorted[i] = pass[pos[i]];\n\n string Pass = new String(sorted);\n\n return Pass;\n }\n"
},
{
"answer_id": 14287335,
"author": "Troy Alford",
"author_id": 1454806,
"author_profile": "https://Stackoverflow.com/users/1454806",
"pm_score": 3,
"selected": false,
"text": "^(?=\\b\\w*[a-z].*[a-z]\\w*\\b)(?=\\b\\w*[A-Z].*[A-Z]\\w*\\b)(?=\\b\\w*[0-9].*[0-9]\\w*\\b)[a-zA-Z0-9]{8,}$\n public static string GeneratePassword(int lowercase, int uppercase, int numerics) {\n string lowers = \"abcdefghijklmnopqrstuvwxyz\";\n string uppers = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string number = \"0123456789\";\n\n Random random = new Random();\n\n string generated = \"!\";\n for (int i = 1; i <= lowercase; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n lowers[random.Next(lowers.Length - 1)].ToString()\n );\n\n for (int i = 1; i <= uppercase; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n uppers[random.Next(uppers.Length - 1)].ToString()\n );\n\n for (int i = 1; i <= numerics; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n number[random.Next(number.Length - 1)].ToString()\n );\n\n return generated.Replace(\"!\", string.Empty);\n\n}\n String randomPassword = GeneratePassword(3, 3, 3);\n \"!\" lowercase + uppercase + numerics"
},
{
"answer_id": 19067818,
"author": "Joe",
"author_id": 2724942,
"author_profile": "https://Stackoverflow.com/users/2724942",
"pm_score": -1,
"selected": false,
"text": "int count = 0;\n private void button1_Click(object sender, EventArgs e)\n {\n // This clears the textBox, resets the count, and starts the timer\n count = 0;\n textBox1.Clear();\n timer1.Start();\n }\n\n private void timer1_Tick(object sender, EventArgs e)\n {\n // This generates the password, and types it in the textBox\n count += 1;\n string possible = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n string psw = \"\";\n Random rnd = new Random { };\n psw += possible[rnd.Next(possible.Length)];\n textBox1.Text += psw;\n if (count == (comboBox1.SelectedIndex + 1))\n {\n timer1.Stop();\n }\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n // This adds password lengths to the comboBox to choose from.\n comboBox1.Items.Add(\"1\");\n comboBox1.Items.Add(\"2\");\n comboBox1.Items.Add(\"3\");\n comboBox1.Items.Add(\"4\");\n comboBox1.Items.Add(\"5\");\n comboBox1.Items.Add(\"6\");\n comboBox1.Items.Add(\"7\");\n comboBox1.Items.Add(\"8\");\n comboBox1.Items.Add(\"9\");\n comboBox1.Items.Add(\"10\");\n comboBox1.Items.Add(\"11\");\n comboBox1.Items.Add(\"12\");\n }\n private void button2_click(object sender, EventArgs e)\n {\n // This encrypts the password\n tochar = textBox1.Text;\n textBox1.Clear();\n char[] carray = tochar.ToCharArray();\n for (int i = 0; i < carray.Length; i++)\n {\n int num = Convert.ToInt32(carray[i]) + 10;\n string cvrt = Convert.ToChar(num).ToString();\n textBox1.Text += cvrt;\n }\n }\n"
},
{
"answer_id": 19068116,
"author": "CodesInChaos",
"author_id": 445517,
"author_profile": "https://Stackoverflow.com/users/445517",
"pm_score": 6,
"selected": false,
"text": "RNGCryptoServiceProvider System.Random using System;\nusing System.Security.Cryptography;\n\npublic static string GetRandomAlphanumericString(int length)\n{\n const string alphanumericCharacters =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" +\n \"abcdefghijklmnopqrstuvwxyz\" +\n \"0123456789\";\n return GetRandomString(length, alphanumericCharacters);\n}\n\npublic static string GetRandomString(int length, IEnumerable<char> characterSet)\n{\n if (length < 0)\n throw new ArgumentException(\"length must not be negative\", \"length\");\n if (length > int.MaxValue / 8) // 250 million chars ought to be enough for anybody\n throw new ArgumentException(\"length is too big\", \"length\");\n if (characterSet == null)\n throw new ArgumentNullException(\"characterSet\");\n var characterArray = characterSet.Distinct().ToArray();\n if (characterArray.Length == 0)\n throw new ArgumentException(\"characterSet must not be empty\", \"characterSet\");\n\n var bytes = new byte[length * 8];\n new RNGCryptoServiceProvider().GetBytes(bytes);\n var result = new char[length];\n for (int i = 0; i < length; i++)\n {\n ulong value = BitConverter.ToUInt64(bytes, i * 8);\n result[i] = characterArray[value % (uint)characterArray.Length];\n }\n return new string(result);\n}\n"
},
{
"answer_id": 19613574,
"author": "user1058637",
"author_id": 1058637,
"author_profile": "https://Stackoverflow.com/users/1058637",
"pm_score": -1,
"selected": false,
"text": "public static string GenerateRandomCode(int length)\n{\n Random rdm = new Random();\n StringBuilder sb = new StringBuilder();\n\n for(int i = 0; i < length; i++)\n sb.Append(Convert.ToChar(rdm.Next(101,132)));\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 23973810,
"author": "Alex Siepman",
"author_id": 1333374,
"author_profile": "https://Stackoverflow.com/users/1333374",
"pm_score": 3,
"selected": false,
"text": "var generator = new PasswordGenerator(minimumLengthPassword: 8,\n maximumLengthPassword: 15,\n minimumUpperCaseChars: 2,\n minimumNumericChars: 3,\n minimumSpecialChars: 2);\nstring password = generator.Generate();\n"
},
{
"answer_id": 24711536,
"author": "anaximander",
"author_id": 1448943,
"author_profile": "https://Stackoverflow.com/users/1448943",
"pm_score": 5,
"selected": false,
"text": "public string GenerateToken(int length)\n{\n using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())\n {\n byte[] tokenBuffer = new byte[length];\n cryptRNG.GetBytes(tokenBuffer);\n return Convert.ToBase64String(tokenBuffer);\n }\n}\n RNGCryptoServiceProvider = length = Convert.ToBase64String() Encoding Encoding.UTF8.GetString(tokenBuffer)"
},
{
"answer_id": 29334830,
"author": "GRUNGER",
"author_id": 4727475,
"author_profile": "https://Stackoverflow.com/users/4727475",
"pm_score": -1,
"selected": false,
"text": " //Symb array\n private const string _SymbolsAll = \"~`!@#$%^&*()_+=-\\\\|[{]}'\\\";:/?.>,<\";\n\n //Random symb\n public string GetSymbol(int Length)\n {\n Random Rand = new Random(DateTime.Now.Millisecond);\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < Length; i++)\n result.Append(_SymbolsAll[Rand.Next(0, _SymbolsAll.Length)]);\n return result.ToString();\n }\n _SymbolsAll"
},
{
"answer_id": 30830874,
"author": "Peter",
"author_id": 328968,
"author_profile": "https://Stackoverflow.com/users/328968",
"pm_score": 2,
"selected": false,
"text": "using KeePassLib.Cryptography.PasswordGenerator;\nusing KeePassLib.Security;\n\n\npublic static string GeneratePassword(int passwordLength, bool lowerCase, bool upperCase, bool digits,\n bool punctuation, bool brackets, bool specialAscii, bool excludeLookAlike)\n {\n var ps = new ProtectedString();\n var profile = new PwProfile();\n profile.CharSet = new PwCharSet();\n profile.CharSet.Clear();\n\n if (lowerCase)\n profile.CharSet.AddCharSet('l');\n if(upperCase)\n profile.CharSet.AddCharSet('u');\n if(digits)\n profile.CharSet.AddCharSet('d');\n if (punctuation)\n profile.CharSet.AddCharSet('p');\n if (brackets)\n profile.CharSet.AddCharSet('b');\n if (specialAscii)\n profile.CharSet.AddCharSet('s');\n\n profile.ExcludeLookAlike = excludeLookAlike;\n profile.Length = (uint)passwordLength;\n profile.NoRepeatingCharacters = true;\n\n KeePassLib.Cryptography.PasswordGenerator.PwGenerator.Generate(out ps, profile, null, _pool);\n\n return ps.ReadString();\n }\n"
},
{
"answer_id": 34060765,
"author": "Skyler Campbell",
"author_id": 2465875,
"author_profile": "https://Stackoverflow.com/users/2465875",
"pm_score": -1,
"selected": false,
"text": " public string GeneratePassword(int len)\n {\n string res = \"\";\n Random rnd = new Random();\n while (res.Length < len) res += (new Func<Random, string>((r) => {\n char c = (char)((r.Next(123) * DateTime.Now.Millisecond % 123)); \n return (Char.IsLetterOrDigit(c)) ? c.ToString() : \"\"; \n }))(rnd);\n return res;\n }\n"
},
{
"answer_id": 35722429,
"author": "Ercan ILIK",
"author_id": 5166814,
"author_profile": "https://Stackoverflow.com/users/5166814",
"pm_score": -1,
"selected": false,
"text": "public string Sifre_Uret(int boy, int noalfa)\n{\n\n // 01.03.2016 \n // Genel amaçlı şifre üretme fonksiyonu\n\n\n //Fonskiyon 128 den büyük olmasına izin vermiyor.\n if (boy > 128 ) { boy = 128; }\n if (noalfa > 128) { noalfa = 128; }\n if (noalfa > boy) { noalfa = boy; }\n\n\n string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);\n\n //URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.\n //Microsoft Garanti etmiyor. Alfa Sayısallar Olabiliyorimiş . !@#$%^&*()_-+=[{]};:<>|./?.\n //https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx\n\n\n //URL ve Json ajax lar için filtreleme\n passch = passch.Replace(\":\", \"z\");\n passch = passch.Replace(\";\", \"W\");\n passch = passch.Replace(\"'\", \"t\");\n passch = passch.Replace(\"\\\"\", \"r\");\n passch = passch.Replace(\"/\", \"+\");\n passch = passch.Replace(\"\\\\\", \"e\");\n\n passch = passch.Replace(\"?\", \"9\");\n passch = passch.Replace(\"&\", \"8\");\n passch = passch.Replace(\"#\", \"D\");\n passch = passch.Replace(\"%\", \"u\");\n passch = passch.Replace(\"=\", \"4\");\n passch = passch.Replace(\"~\", \"1\");\n\n passch = passch.Replace(\"[\", \"2\");\n passch = passch.Replace(\"]\", \"3\");\n passch = passch.Replace(\"{\", \"g\");\n passch = passch.Replace(\"}\", \"J\");\n\n\n //passch = passch.Replace(\"(\", \"6\");\n //passch = passch.Replace(\")\", \"0\");\n //passch = passch.Replace(\"|\", \"p\");\n //passch = passch.Replace(\"@\", \"4\");\n //passch = passch.Replace(\"!\", \"u\");\n //passch = passch.Replace(\"$\", \"Z\");\n //passch = passch.Replace(\"*\", \"5\");\n //passch = passch.Replace(\"_\", \"a\");\n\n passch = passch.Replace(\",\", \"V\");\n passch = passch.Replace(\".\", \"N\");\n passch = passch.Replace(\"+\", \"w\");\n passch = passch.Replace(\"-\", \"7\");\n\n\n\n\n\n return passch;\n\n\n\n}\n"
},
{
"answer_id": 41449547,
"author": "Matt",
"author_id": 2157661,
"author_profile": "https://Stackoverflow.com/users/2157661",
"pm_score": -1,
"selected": false,
"text": "private string RandomPassword(int length, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n if (length < 8 || length > 128) throw new ArgumentOutOfRangeException(\"length\");\n if (!includeCharacters && !includeNumbers && !includeNonAlphaNumericCharacters) throw new ArgumentException(\"RandomPassword-Key arguments all false, no values would be returned\");\n\n string pw = \"\";\n do\n {\n pw += System.Web.Security.Membership.GeneratePassword(128, 25);\n pw = RemoveCharacters(pw, includeCharacters, includeNumbers, includeUppercase, includeNonAlphaNumericCharacters, includeLookAlikes);\n } while (pw.Length < length);\n\n return pw.Substring(0, length);\n}\n\nprivate string RemoveCharacters(string passwordString, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n if (!includeCharacters)\n {\n var remove = new string[] { \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\" };\n foreach (string r in remove)\n {\n passwordString = passwordString.Replace(r, string.Empty);\n passwordString = passwordString.Replace(r.ToUpper(), string.Empty);\n }\n }\n\n if (!includeNumbers)\n {\n var remove = new string[] { \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n if (!includeUppercase)\n passwordString = passwordString.ToLower();\n\n if (!includeNonAlphaNumericCharacters)\n {\n var remove = new string[] { \"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"(\", \")\", \"-\", \"_\", \"+\", \"=\", \"{\", \"}\", \"[\", \"]\", \"|\", \"\\\\\", \":\", \";\", \"<\", \">\", \"/\", \"?\", \".\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n if (!includeLookAlikes)\n {\n var remove = new string[] { \"(\", \")\", \"0\", \"O\", \"o\", \"1\", \"i\", \"I\", \"l\", \"|\", \"!\", \":\", \";\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n return passwordString;\n}\n System.Web.Security.Membership.GeneratePassword"
},
{
"answer_id": 46550870,
"author": "Sean",
"author_id": 6114538,
"author_profile": "https://Stackoverflow.com/users/6114538",
"pm_score": -1,
"selected": false,
"text": "string validChars = String.Join(\"\", Enumerable.Range(33, (126 - 33)).Where(i => !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i => { return (char)i; }));\nstring.Join(\"\", Enumerable.Range(1, 12).Select(i => { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))\n"
},
{
"answer_id": 48701757,
"author": "akshay tilekar",
"author_id": 8152379,
"author_profile": "https://Stackoverflow.com/users/8152379",
"pm_score": -1,
"selected": false,
"text": " Generate random password of specified length with \n - Special characters \n - Number\n - Lowecase\n - Uppercase\n\n public static string CreatePassword(int length = 12)\n {\n const string lower = \"abcdefghijklmnopqrstuvwxyz\";\n const string upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const string number = \"1234567890\";\n const string special = \"!@#$%^&*\";\n\n var middle = length / 2;\n StringBuilder res = new StringBuilder();\n Random rnd = new Random();\n while (0 < length--)\n {\n if (middle == length)\n {\n res.Append(number[rnd.Next(number.Length)]);\n }\n else if (middle - 1 == length)\n {\n res.Append(special[rnd.Next(special.Length)]);\n }\n else\n {\n if (length % 2 == 0)\n {\n res.Append(lower[rnd.Next(lower.Length)]);\n }\n else\n {\n res.Append(upper[rnd.Next(upper.Length)]);\n }\n }\n }\n return res.ToString();\n }\n"
},
{
"answer_id": 51023300,
"author": "Saeed Ahmad",
"author_id": 7351330,
"author_profile": "https://Stackoverflow.com/users/7351330",
"pm_score": 0,
"selected": false,
"text": "public static string GeneratePassword(int passLength) {\n var chars = \"abcdefghijklmnopqrstuvwxyz@#$&ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n var random = new Random();\n var result = new string(\n Enumerable.Repeat(chars, passLength)\n .Select(s => s[random.Next(s.Length)])\n .ToArray());\n return result;\n }\n"
},
{
"answer_id": 55130798,
"author": "kitsu.eb",
"author_id": 770443,
"author_profile": "https://Stackoverflow.com/users/770443",
"pm_score": 3,
"selected": false,
"text": "Membership.GeneratePassword Membership.GeneratePassword public static class PasswordGenerator\n{\n private readonly static Random _rand = new Random();\n\n public static string Generate(int length = 24)\n {\n const string lower = \"abcdefghijklmnopqrstuvwxyz\";\n const string upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const string number = \"1234567890\";\n const string special = \"!@#$%^&*_-=+\";\n\n // Get cryptographically random sequence of bytes\n var bytes = new byte[length];\n new RNGCryptoServiceProvider().GetBytes(bytes);\n\n // Build up a string using random bytes and character classes\n var res = new StringBuilder();\n foreach(byte b in bytes)\n {\n // Randomly select a character class for each byte\n switch (_rand.Next(4))\n {\n // In each case use mod to project byte b to the correct range\n case 0:\n res.Append(lower[b % lower.Count()]);\n break;\n case 1:\n res.Append(upper[b % upper.Count()]);\n break;\n case 2:\n res.Append(number[b % number.Count()]);\n break;\n case 3:\n res.Append(special[b % special.Count()]);\n break;\n }\n }\n return res.ToString();\n }\n}\n PasswordGenerator.Generate(12)\n\"pzY=64@-ChS$\"\n\"BG0OsyLbYnI_\"\n\"l9#5^2&adj_i\"\n\"#++Ws9d$%O%X\"\n\"IWhdIN-#&O^s\"\n Random Random 1 switch (_rand.Next(6))\n{\n // Prefer letters 2:1\n case 0:\n case 1:\n res.Append(lower[b % lower.Count()]);\n break;\n case 2:\n case 3:\n res.Append(upper[b % upper.Count()]);\n break;\n case 4:\n res.Append(number[b % number.Count()]);\n break;\n case 5:\n res.Append(special[b % special.Count()]);\n break;\n}\n"
},
{
"answer_id": 57331316,
"author": "Roohi Ali",
"author_id": 3706939,
"author_profile": "https://Stackoverflow.com/users/3706939",
"pm_score": -1,
"selected": false,
"text": "public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n {\n string allowedChars = \"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789\";\n string allowedNonAlphaNum = \"!@#$%^&*()_-+=[{]};:<>|./?\";\n string pass = \"\";\n Random rd = new Random(DateTime.Now.Millisecond);\n for (int i = 0; i < Length; i++)\n {\n if (rd.Next(1) > 0 && NonAlphaNumericChars > 0)\n {\n pass += allowedNonAlphaNum[rd.Next(allowedNonAlphaNum.Length)];\n NonAlphaNumericChars--;\n }\n else\n {\n pass += allowedChars[rd.Next(allowedChars.Length)];\n }\n }\n return pass;\n }\n"
},
{
"answer_id": 59933028,
"author": "Johan Maes",
"author_id": 9266796,
"author_profile": "https://Stackoverflow.com/users/9266796",
"pm_score": 0,
"selected": false,
"text": "var pwd = new Password().IncludeLowercase().IncludeUppercase().IncludeSpecial();\nvar password = pwd.Next();\n"
},
{
"answer_id": 60382377,
"author": "samgak",
"author_id": 696391,
"author_profile": "https://Stackoverflow.com/users/696391",
"pm_score": 0,
"selected": false,
"text": "static string GeneratePassword(int characterCount)\n{\n string password = String.Empty;\n while(password.Length < characterCount)\n password += Regex.Replace(System.Web.Security.Membership.GeneratePassword(128, 0), \"[^a-zA-Z0-9]\", string.Empty);\n return password.Substring(0, characterCount);\n}\n"
},
{
"answer_id": 66334368,
"author": "RD07 Dz",
"author_id": 13557184,
"author_profile": "https://Stackoverflow.com/users/13557184",
"pm_score": 0,
"selected": false,
"text": " public string GeneratePassword(int length)\n {\n using(RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider();)\n {\n byte[] tokenBuffer = new byte[length];\n cryptRNG.GetBytes(tokenBuffer);\n return Convert.ToBase64String(tokenBuffer).Remove(length);\n }\n \n }\n"
},
{
"answer_id": 67102548,
"author": "Vijay Kumavat",
"author_id": 12376492,
"author_profile": "https://Stackoverflow.com/users/12376492",
"pm_score": 0,
"selected": false,
"text": " private static Random random = new Random();\n public static void Main()\n {\n Console.WriteLine(\"Random password with length of 8 character.\");\n Console.WriteLine(\"===========================================\");\n Console.WriteLine(\"Capital latters : 2\");\n Console.WriteLine(\"Number latters : 2\");\n Console.WriteLine(\"Special latters : 2\");\n Console.WriteLine(\"Small latters : 2\");\n Console.WriteLine(\"===========================================\");\n Console.Write(\"The Random Password : \");\n Console.WriteLine(RandomStringCap(2) + RandomStringNum(2) + RandomStringSpe(2) + RandomStringSml(2));\n Console.WriteLine(\"===========================================\");\n }\n public static string RandomStringCap(int length)\n {\n const string chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringNum(int length)\n {\n const string chars = \"0123456789\";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringSml(int length)\n {\n const string chars = \"abcdefghijklmnopqrstuvwxyz\";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringSpe(int length)\n {\n const string chars = \"!@#$%^&*_-=+\";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n"
},
{
"answer_id": 73316960,
"author": "Shane",
"author_id": 5564257,
"author_profile": "https://Stackoverflow.com/users/5564257",
"pm_score": 0,
"selected": false,
"text": "RandomNumberGenerator Random RNGCryptoServiceProvider System.Text.Json.JsonSerializer.Serialize & \\u0026 public static class PasswordGenerator\n{\n const string lower = \"abcdefghijklmnopqrstuvwxyz\";\n const string upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const string number = \"1234567890\";\n const string special = \"!@#$%^&*()[]{},.:`~_-=+\"; // excludes problematic characters like ;'\"/\\\n const string specialJsonSafe = \"!@#$%^*()[]{},.:~_-=\"; // excludes problematic characters like ;'\"/\\ and &`+\n\n const int lowerLength = 26; // lower.Length\n const int upperLength = 26; // upper.Length;\n const int numberLength = 10; // number.Length;\n const int specialLength = 23; // special.Length;\n const int specialJsonSafeLength = 20; // specialJsonSafe.Length;\n\n public static string Generate(int length = 96, bool jsonSafeSpecialCharactersOnly = false)\n {\n Span<char> result = length < 1024 ? stackalloc char[length] : new char[length].AsSpan();\n\n for (int i = 0; i < length; ++i)\n {\n switch (RandomNumberGenerator.GetInt32(4))\n {\n case 0:\n result[i] = lower[RandomNumberGenerator.GetInt32(0, lowerLength)];\n break;\n case 1:\n result[i] = upper[RandomNumberGenerator.GetInt32(0, upperLength)];\n break;\n case 2:\n result[i] = number[RandomNumberGenerator.GetInt32(0, numberLength)];\n break;\n case 3:\n if (jsonSafeSpecialCharactersOnly)\n {\n result[i] = specialJsonSafe[RandomNumberGenerator.GetInt32(0, specialJsonSafeLength)];\n }\n else\n {\n result[i] = special[RandomNumberGenerator.GetInt32(0, specialLength)];\n }\n break;\n }\n }\n\n return result.ToString();\n }\n}\n"
},
{
"answer_id": 73913189,
"author": "clamchoda",
"author_id": 591285,
"author_profile": "https://Stackoverflow.com/users/591285",
"pm_score": 0,
"selected": false,
"text": "Random Random rand = new Random();\nint min = 8;\nint max = 16;\nint totalLen = rand.Next(min, max);\nint remainingGroups = 4;\n \nstring[] allowedLowerChars = \"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z\".Split(','); \nstring [] allowedUpperChars = \"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z\".Split(',');\nstring [] allowedNumbers = \"1,2,3,4,5,6,7,8,9,0\".Split(',');\nstring [] allowedSpecialChars = \"!,@,#,$,%,&,?\".Split(',');\n\n\nvar password = allowedLowerChars.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-remainingGroups--)).ToList();\npassword.AddRange(allowedUpperChars.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedNumbers.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedSpecialChars.OrderBy(c => rand.Next()).Take(totalLen-password.Count).ToList());\npassword = password.OrderBy(c => rand.Next()).ToList(); // randomize groups\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/54991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
55,010 |
<p>Supposing you have a form that collects and submits sensitive information and you want to ensure it is never accessed via insecure (non-HTTPS) means, how might you best go about enforcing that policy?</p>
|
[
{
"answer_id": 55024,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 3,
"selected": false,
"text": "RewriteRule .htaccess RewriteCond %{HTTPS} \"off\"\nRewriteRule /mypage.html https://example.com/mypage.html\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] |
55,013 |
<p>Is there ever a circumstance in which I would not want to use the <a href="http://msdn.microsoft.com/en-us/library/cb8x3kfz.aspx" rel="noreferrer"><code>AndAlso</code></a> operator rather than the <a href="http://msdn.microsoft.com/en-us/library/sdbcfyzh.aspx" rel="noreferrer"><code>And</code></a> operator? …or in which I would not want to use the <a href="http://msdn.microsoft.com/en-us/library/ea1sssb2.aspx" rel="noreferrer"><code>OrElse</code></a> operator rather than the <a href="http://msdn.microsoft.com/en-us/library/06s37a7f.aspx" rel="noreferrer"><code>Or</code></a> operator?</p>
|
[
{
"answer_id": 55025,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "AndAlso OrElse && ||"
},
{
"answer_id": 69841478,
"author": "Andrew",
"author_id": 6794075,
"author_profile": "https://Stackoverflow.com/users/6794075",
"pm_score": 0,
"selected": false,
"text": "AndAlso OrElse && || And Or & | And 0b010 Or 0b001"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
55,042 |
<p>I want to build a bot that asks someone a few simple questions and branches based on the answer. I realize parsing meaning from the human responses will be challenging, but how do you setup the program to deal with the "state" of the conversation?</p>
<p>It will be a one-to-one conversation between a human and the bot.</p>
|
[
{
"answer_id": 55053,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 6,
"selected": true,
"text": "import random, sys\n\nNONWORD = \"\\n\"\nSTARTKEY = NONWORD, NONWORD\nMAXGEN=1000\n\nclass MarkovChainer(object):\n def __init__(self):\n self.state = dict()\n\n def input(self, input):\n word1, word2 = STARTKEY\n for word3 in input.split():\n self.state.setdefault((word1, word2), list()).append(word3)\n word1, word2 = word2, word3 \n self.state.setdefault((word1, word2), list()).append(NONWORD)\n\n def output(self):\n output = list()\n word1, word2 = STARTKEY\n for i in range(MAXGEN):\n word3 = random.choice(self.state[(word1,word2)])\n if word3 == NONWORD: break\n output.append(word3)\n word1, word2 = word2, word3\n return \" \".join(output)\n\nif __name__ == \"__main__\":\n c = MarkovChainer()\n c.input(sys.stdin.read())\n print c.output()\n"
},
{
"answer_id": 23901502,
"author": "user3513316",
"author_id": 3513316,
"author_profile": "https://Stackoverflow.com/users/3513316",
"pm_score": 1,
"selected": false,
"text": "#lukebot-trainer.py\nimport pickle\nb=open('war&peace.txt')\ntext=[]\nfor line in b:\n for word in line.split():\n text.append (word)\nb.close()\ntextset=list(set(text))\nfollow={}\nfor l in range(len(textset)):\n working=[]\n check=textset[l]\n for w in range(len(text)-1):\n if check==text[w] and text[w][-1] not in '(),.?!':\n working.append(str(text[w+1]))\n follow[check]=working\na=open('lexicon-luke','wb')\npickle.dump(follow,a,2)\na.close()\n #lukebot.py\nimport pickle,random\na=open('lexicon-luke','rb')\nsuccessorlist=pickle.load(a)\na.close()\ndef nextword(a):\n if a in successorlist:\n return random.choice(successorlist[a])\n else:\n return 'the'\nspeech=''\nwhile speech!='quit':\n speech=raw_input('>')\n s=random.choice(speech.split())\n response=''\n while True:\n neword=nextword(s)\n response+=' '+neword\n s=neword\n if neword[-1] in ',?!.':\n break\n print response\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
55,054 |
<p>What’s the best way to capitalize the first letter of each word in a string in SQL Server.</p>
|
[
{
"answer_id": 55057,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) \nRETURNS VARCHAR(4000)\nAS\nBEGIN\n\nDECLARE @Index INT\nDECLARE @Char CHAR(1)\nDECLARE @PrevChar CHAR(1)\nDECLARE @OutputString VARCHAR(255)\n\nSET @OutputString = LOWER(@InputString)\nSET @Index = 1\n\nWHILE @Index <= LEN(@InputString)\nBEGIN\n SET @Char = SUBSTRING(@InputString, @Index, 1)\n SET @PrevChar = CASE WHEN @Index = 1 THEN ' '\n ELSE SUBSTRING(@InputString, @Index - 1, 1)\n END\n\n IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')\n BEGIN\n IF @PrevChar != '''' OR UPPER(@Char) != 'S'\n SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))\n END\n\n SET @Index = @Index + 1\nEND\n\nRETURN @OutputString\n\nEND\nGO\n"
},
{
"answer_id": 55153,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION [widget].[properCase](@string varchar(8000)) RETURNS varchar(8000) AS\nBEGIN \n SET @string = LOWER(@string)\n DECLARE @i INT\n SET @i = ASCII('a')\n WHILE @i <= ASCII('z')\n BEGIN\n SET @string = REPLACE( @string, ' ' + CHAR(@i), ' ' + CHAR(@i-32))\n SET @i = @i + 1\n END\n SET @string = CHAR(ASCII(LEFT(@string, 1))-32) + RIGHT(@string, LEN(@string)-1)\n RETURN @string\nEND\n"
},
{
"answer_id": 27742913,
"author": "Andrey Morozov",
"author_id": 483408,
"author_profile": "https://Stackoverflow.com/users/483408",
"pm_score": 2,
"selected": false,
"text": "create function [dbo].InitCap (@value varchar(max))\nreturns varchar(max) as\nbegin\n\n declare\n @separator char(1) = ' ',\n @result varchar(max) = '';\n\n with r as (\n select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j\n union all\n select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value]\n , left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x]\n , left(r.[value], 1)\n , [no] + 1 [no]\n from r where value > '')\n\n select @result = @result +\n case\n when ascii([char]) between 97 and 122 \n then stuff(x, 1, 1, char(ascii([char])-32))\n else x\n end + @separator\n from r where x is not null;\n\n set @result = rtrim(@result);\n\n return @result;\nend\n"
},
{
"answer_id": 31574024,
"author": "Amrik",
"author_id": 1783751,
"author_profile": "https://Stackoverflow.com/users/1783751",
"pm_score": 0,
"selected": false,
"text": "SELECT LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) ) FROM [tablename]\n"
},
{
"answer_id": 46344989,
"author": "Kristofer",
"author_id": 1398417,
"author_profile": "https://Stackoverflow.com/users/1398417",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX))\nRETURNS TABLE\nAS\nRETURN \nWITH a AS (\n SELECT (\n SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()'\n FROM string_split(@v, ' ')\n ORDER BY CHARINDEX(value,@v)\n FOR XML PATH (''), TYPE) ret)\n\nSELECT CAST(a.ret AS varchar(MAX)) ret from a\nGO\n string_split COMPATIBILITY_LEVEL"
},
{
"answer_id": 47754555,
"author": "Vignesh Sonaiya",
"author_id": 8294507,
"author_profile": "https://Stackoverflow.com/users/8294507",
"pm_score": 1,
"selected": false,
"text": "BEGIN\nDECLARE @string varchar(100) = 'asdsadsd asdad asd'\nDECLARE @ResultString varchar(200) = ''\nDECLARE @index int = 1\nDECLARE @flag bit = 0\nDECLARE @temp varchar(2) = ''\nWHILE (@Index <LEN(@string)+1)\n BEGIN\n SET @temp = SUBSTRING(@string, @Index-1, 1)\n --select @temp\n IF @temp = ' ' OR @index = 1\n BEGIN\n SET @ResultString = @ResultString + UPPER(SUBSTRING(@string, @Index, 1))\n END\n ELSE\n BEGIN\n \n SET @ResultString = @ResultString + LOWER(SUBSTRING(@string, @Index, 1)) \n END \n\n SET @Index = @Index+ 1--increase the index\n END\nSELECT @ResultString\nEND\n"
},
{
"answer_id": 52286176,
"author": "Rene",
"author_id": 1739704,
"author_profile": "https://Stackoverflow.com/users/1739704",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION Capitalyze(@input varchar(100) )\n returns varchar(100)\nas\nbegin\n \n declare @index int=0\n declare @char as varchar(1)=' '\n declare @prevCharIsSpace as bit=1\n declare @Result as varchar(100)=''\n\n set @input=UPPER(LEFT(@input,1))+LOWER(SUBSTRING(@input, 2, LEN(@input)))\n set @index=PATINDEX('% _%',@input)\n if @index=0\n set @index=len(@input)\n set @Result=substring(@input,0,@index+1)\n\n WHILE (@index < len(@input))\n BEGIN\n SET @index = @index + 1\n SET @char=substring(@input,@index,1)\n if (@prevCharIsSpace=1)\n begin\n set @char=UPPER(@char)\n if (@char=' ')\n set @char=''\n end\n\n if (@char=' ')\n set @prevCharIsSpace=1\n else\n set @prevCharIsSpace=0\n\n set @Result=@Result+@char\n --print @Result\n END\n --print @Result\n return @Result\nend\n"
},
{
"answer_id": 52621398,
"author": "Akhil Singh",
"author_id": 7528842,
"author_profile": "https://Stackoverflow.com/users/7528842",
"pm_score": 0,
"selected": false,
"text": "select UPPER(left(fname,1))+SUBSTRING(fname,2,LEN(fname)) as fname\nFROM [dbo].[akhil]\n"
},
{
"answer_id": 53025811,
"author": "Shashank Gupta",
"author_id": 10155755,
"author_profile": "https://Stackoverflow.com/users/10155755",
"pm_score": 2,
"selected": false,
"text": "SQL> select INITCAP(dname) from department;\n\nINITCAP(DNAME)\n--------------------------------------------------\nSales\nManagement\nProduction\nDevelopment\n"
},
{
"answer_id": 56481595,
"author": "Andrew Solomonik",
"author_id": 11610118,
"author_profile": "https://Stackoverflow.com/users/11610118",
"pm_score": -1,
"selected": false,
"text": "IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL\n DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter\nGO\n\nCREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (@string NVARCHAR(MAX), @delimiter NCHAR(1), @new_delimeter NCHAR(1))\nRETURNS NVARCHAR(MAX)\nAS \nBEGIN\n DECLARE @result NVARCHAR(MAX)\n SELECT @result = '';\n IF (LEN(@string) > 0)\n DECLARE @curr INT\n DECLARE @next INT\n BEGIN\n SELECT @curr = 1\n SELECT @next = CHARINDEX(@delimiter, @string)\n WHILE (LEN(@string) > 0)\n BEGIN\n SELECT @result = \n @result + \n CASE WHEN LEN(@result) > 0 THEN @new_delimeter ELSE '' END +\n UPPER(SUBSTRING(@string, @curr, 1)) + \n CASE \n WHEN @next <> 0 \n THEN LOWER(SUBSTRING(@string, @curr+1, @next-2))\n ELSE LOWER(SUBSTRING(@string, @curr+1, LEN(@string)-@curr))\n END\n IF (@next > 0)\n BEGIN\n SELECT @string = SUBSTRING(@string, @next+1, LEN(@string)-@next)\n SELECT @next = CHARINDEX(@delimiter, @string)\n END\n ELSE\n SELECT @string = ''\n END\n END\n RETURN @result\nEND\nGO\n"
},
{
"answer_id": 58296137,
"author": "Vitaly Borisov",
"author_id": 4119599,
"author_profile": "https://Stackoverflow.com/users/4119599",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION [dbo].[InitCap](@Text NVARCHAR(MAX))\nRETURNS NVARCHAR(MAX)\nAS\nBEGIN\n RETURN STUFF((\n SELECT ' ' + UPPER(LEFT(s.value,1)) + LOWER(SUBSTRING(s.value,2,LEN(s.value)))\n FROM OPENJSON('[\"' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Text,'\\','\\\\'),'\"','\\\"'),CHAR(9),'\\t'),CHAR(10),'\\n'),' ','\",\"') + '\"]') s\n ORDER BY s.[key]\n FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'');\nEND\n"
},
{
"answer_id": 61159787,
"author": "Glen",
"author_id": 1828277,
"author_profile": "https://Stackoverflow.com/users/1828277",
"pm_score": 2,
"selected": false,
"text": ";WITH StudentList(Name) AS (\n SELECT CONVERT(varchar(50), 'Carl-VAN')\nUNION SELECT 'Dean o''brian'\nUNION SELECT 'Andrew-le-Smith'\nUNION SELECT 'Eddy thompson'\nUNION SELECT 'BOBs-your-Uncle'\n), Student AS (\n SELECT CONVERT(varchar(50), UPPER(LEFT(Name, 1)) + LOWER(SUBSTRING(Name, 2, LEN(Name)))) Name, \n pos = PATINDEX('%[-'' ]%', Name)\n FROM StudentList\n UNION ALL\n SELECT CONVERT(varchar(50), LEFT(Name, pos) + UPPER(SUBSTRING(Name, pos + 1, 1)) + SUBSTRING(Name, pos + 2, LEN(Name))) Name, \n pos = CASE WHEN PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) = 0 THEN 0 ELSE pos + PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) END\n FROM Student\n WHERE pos > 0\n)\nSELECT Name\nFROM Student \nWHERE pos = 0\nORDER BY Name \n"
},
{
"answer_id": 64925176,
"author": "KodFun",
"author_id": 8783782,
"author_profile": "https://Stackoverflow.com/users/8783782",
"pm_score": 0,
"selected": false,
"text": "GO\nCREATE FUNCTION [dbo].[Capitalize](@text NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS\nBEGIN\n DECLARE @result NVARCHAR(MAX) = '';\n DECLARE @c NVARCHAR(1);\n DECLARE @i INT = 1;\n DECLARE @isPrevSpace BIT = 1;\n\n WHILE @i <= LEN(@text)\n BEGIN\n SET @c = SUBSTRING(@text, @i, 1);\n SET @result += IIF(@isPrevSpace = 1, UPPER(@c), LOWER(@c));\n SET @isPrevSpace = IIF(@c LIKE '[ -]', 1, 0);\n SET @i += 1;\n END\n RETURN @result;\nEND\nGO\n\nDECLARE @sentence NVARCHAR(100) = N'i-thINK-this soLUTION-works-LiKe-a charm';\nPRINT dbo.Capitalize(@sentence);\n-- I-Think-This Solution-Works-Like-A Charm\n"
},
{
"answer_id": 67810946,
"author": "Merin Nakarmi",
"author_id": 717955,
"author_profile": "https://Stackoverflow.com/users/717955",
"pm_score": 1,
"selected": false,
"text": "DECLARE @Name VARCHAR(500) = 'Roger';\n\nSELECT @Name AS Name, UPPER(LEFT(@Name, 1)) + SUBSTRING(@Name, 2, LEN(@Name)) AS CapitalizedName;\n"
},
{
"answer_id": 67998634,
"author": "Ashraf Ali",
"author_id": 16241030,
"author_profile": "https://Stackoverflow.com/users/16241030",
"pm_score": 1,
"selected": false,
"text": "select ID,Name\n,string_agg(concat(upper(substring(value,1,1)),lower(substring(value,2,len(value)-1))),' ') as ModifiedName \nfrom Table_Customer \ncross apply String_Split(replace(trim(Name),' ',' '),' ')\nwhere Name is not null\ngroup by ID,Name;\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170/"
] |
55,056 |
<p>I'm building a Django project that needs search functionality, and until there's a <code>django.contrib.search</code>, I have to choose a search app. So, which is the best? By "best" I mean...</p>
<ul>
<li>easy to install / set up</li>
<li>has a Django- or at least Python-friendly API</li>
<li>can perform reasonably complex searches</li>
</ul>
<p>Here are some apps I've heard of, please suggest others if you know of any:</p>
<ul>
<li><a href="http://code.google.com/p/djangosearch/" rel="noreferrer">djangosearch</a></li>
<li><a href="http://code.google.com/p/django-sphinx/" rel="noreferrer">django-sphinx</a></li>
</ul>
<p>I'd also like to avoid using a third-party search engine (like Google SiteSearch), because some of the data I'd like to index is for site members only and should not be public.</p>
|
[
{
"answer_id": 55924,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 4,
"selected": false,
"text": "django.contrib.search"
},
{
"answer_id": 56885,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 3,
"selected": false,
"text": "# set up the model\nclass Event(models.Model):\n title = models.CharField(max_length=255)\n date = models.DateField()\n is_outdoors = models.BooleanField()\n\n index = djangosearch.ModelIndex(text=['title'], \n additional=['date', 'is_outdoors'])\n\n# run a search\nresults = Event.index.search(\"django conference\")\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5616/"
] |
55,060 |
<p>I'm pretty sure the answer to this question is no, but in case there's some PHP guru</p>
<p>is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of <code>'@'</code></p>
<p>Much like empty and isset do. You can pass in a variable you just made up and it won't error.</p>
<pre><code>ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
</code></pre>
|
[
{
"answer_id": 55065,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "function safeLookup($array, $key)\n{\n if (isset($array, $key))\n return $array[$key];\n\n return 0;\n}\n defaultValue(safeLookup($foo, \"bar\"), \"baz);\n"
},
{
"answer_id": 55079,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "return $value ? $value : $default;\n"
},
{
"answer_id": 55090,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": -1,
"selected": false,
"text": "class Configuration {\n\n private var $configValues = array( 'cool' => 'Defaultcoolval' ,\n 'uncool' => 'Defuncoolval' );\n\n public setCool($val) {\n $this->configValues['cool'] = $val;\n }\n\n public getCool() {\n return $this->configValues['cool'];\n }\n\n}\n"
},
{
"answer_id": 55127,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "error_reporting(E_ALL);\nini_set('display_errors', 1);\n\nfunction defaultValue() {\n $args = func_get_args();\n\n foreach($args as $arg) {\n if (!is_array($arg)) {\n $arg = array($arg);\n }\n foreach($arg as $a) {\n if(!empty($a)) {\n return $a;\n }\n }\n }\n\n return false;\n}\n\n$var = 'bob';\n\necho defaultValue(compact('var'), 'alpha') . \"\\n\"; //returns 'bob'\necho defaultValue(compact('var2'), 'alpha') . \"\\n\"; //returns 'alpha'\necho defaultValue('alpha') . \"\\n\"; //return\necho defaultValue() . \"\\n\";\n"
},
{
"answer_id": 55128,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "return isset($input) ? $input : $default;\n"
},
{
"answer_id": 55133,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "$result = ($func_result = doLargeIntenseFunction()) ? $func_result : 'no result';\n isset() true false true false isset()"
},
{
"answer_id": 311954,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": " function myHappyFunction(&$var)\n { \n }\n"
},
{
"answer_id": 504472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "error_reporting ini_restore('error_reporting'); error_reporting $var = @foo($bar);\n\nfunction foo($test_var)\n{\n ini_restore('error_reporting');\n\n if(is_set($test_var) && strlen($test_var))\n {\n return $test_var;\n }\n else\n {\n return -1;\n }\n}\n $bar foo() is_set isset"
},
{
"answer_id": 931565,
"author": "BraedenP",
"author_id": 95764,
"author_profile": "https://Stackoverflow.com/users/95764",
"pm_score": 0,
"selected": false,
"text": "function empty($paramName = \"\"){\n if(isset($paramName){\n //Code here\n }\n else if(empty($paramName)){\n //Code here\n }\n}\n"
},
{
"answer_id": 1867434,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 2,
"selected": false,
"text": "/**\n * Shortcut for getting a value from a possibly unset variable.\n * Normal:\n * if (isset($_GET['foo']) && $_GET['foo'] == 'bar') {\n * Short:\n * if (value($_GET['foo']) == 'bar') {\n *\n * @param mixed $variable \n * @return mixed Returns null if not set\n */\nfunction value(&$variable) {\n if (isset($variable)) {\n return $variable;\n }\n}\n myHappyFunction($someBogusVar);\n myHappyFunction(value($someBogusVar));\n"
},
{
"answer_id": 10890296,
"author": "Omar",
"author_id": 931377,
"author_profile": "https://Stackoverflow.com/users/931377",
"pm_score": 0,
"selected": false,
"text": "myHappyFunction($someBogusVar=\"\"); <?php\nfunction test1($argument)\n{\n echo $argument;\n echo \"\\n\";\n}\n\nfunction test2($argument=\"\")\n{\n echo $argument;\n echo \"\\n\";\n}\n\ntest1();\ntest1(\"Hello\");\ntest1($argument);\n$argument = \"Hello world\";\ntest1($argument);\n\ntest2();\ntest2(\"Hello\");\ntest2($argument);\n$argument = \"Hello world\";\ntest2($argument);\n?>\n test1() test2() isset()"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] |
55,083 |
<p>Any ideas how to display a PDF file in a WPF Windows Application? </p>
<hr>
<p>I am using the following code to run the browser but the <code>Browser.Navigate</code> method does not do anything!</p>
<pre><code>WebBrowser browser = new WebBrowser();
browser.Navigate("http://www.google.com");
this.AddChild(browser); // this is the System.Windows.Window
</code></pre>
|
[
{
"answer_id": 55177,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": true,
"text": "private AxAcroPDFLib.AxAcroPDF axAcroPDF1;\nthis.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();\nthis.axAcroPDF1.Dock = System.Windows.Forms.DockStyle.Fill;\nthis.axAcroPDF1.Enabled = true;\nthis.axAcroPDF1.Name = \"axAcroPDF1\";\nthis.axAcroPDF1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject(\"axAcroPDF1.OcxState\")));\naxAcroPDF1.LoadFile(DownloadedFullFileName);\naxAcroPDF1.Visible = true;\n"
},
{
"answer_id": 581997,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "String fileName = \"FileName.pdf\";\nSystem.Diagnostics.Process process = new System.Diagnostics.Process(); \nprocess.StartInfo.FileName = fileName;\nprocess.Start();\nprocess.WaitForExit();\n"
},
{
"answer_id": 5759095,
"author": "odyth",
"author_id": 86524,
"author_profile": "https://Stackoverflow.com/users/86524",
"pm_score": 3,
"selected": false,
"text": "Frame frame = new Frame();\nWebBrowserbrowser = new WebBrowser();\nbrowser.Navigate(new Uri(filename));\nframe.Content = browser;\n WebBrowser browser = frame.Content as WebBrowser;\nbrowser.Dispose();\nframe.Content = null;\n"
},
{
"answer_id": 17381626,
"author": "VahidN",
"author_id": 298573,
"author_profile": "https://Stackoverflow.com/users/298573",
"pm_score": 3,
"selected": false,
"text": "MoonPdfPanel - A WPF-based PDF viewer control"
},
{
"answer_id": 19423956,
"author": "Frank Rem",
"author_id": 450467,
"author_profile": "https://Stackoverflow.com/users/450467",
"pm_score": 1,
"selected": false,
"text": "using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))\n{\n pdfDoc = new Document(file);\n\n ConvertToWpfOptions convertOptions = new ConvertToWpfOptions();\n RenderSettings renderSettings = new RenderSettings();\n ...\n\n FixedDocument wpfDoc = pdfDoc.ConvertToWpf(renderSettings, convertOptions, 0, 9, summary);\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
55,093 |
<p>I have a class to parse a matrix that keeps the result in an array member:</p>
<pre><code>class Parser
{
...
double matrix_[4][4];
};
</code></pre>
<p>The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:</p>
<pre><code>void api_func(const double matrix[4][4]);
</code></pre>
<p>The only way I have come up with for the caller to pass the array result to the function is by making the member public:</p>
<pre><code>void myfunc()
{
Parser parser;
...
api_func(parser.matrix_);
}
</code></pre>
<p>Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought <code>matrix_</code> would essentially be the same as a <code>double**</code> and I could cast (safely) between the two. As it turns out, I can't even find an <em>unsafe</em> way to cast between the things. Say I add an accessor to the <code>Parser</code> class:</p>
<pre><code>void* Parser::getMatrix()
{
return (void*)matrix_;
}
</code></pre>
<p>This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type:</p>
<pre><code> // A smorgasbord of syntax errors...
api_func((double[][])parser.getMatrix());
api_func((double[4][4])parser.getMatrix());
api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type
</code></pre>
<p>The error is:</p>
<blockquote>
<p>error C2440: 'type cast' : cannot convert from 'void *' to 'const double [4][4]'</p>
</blockquote>
<p>...with an intriguing addendum:</p>
<blockquote>
<p>There are no conversions to array types, although there are conversions to references or pointers to arrays</p>
</blockquote>
<p>I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here.</p>
<p>To be sure, at this point the matter is purely academic, as the <code>void*</code> casts are hardly cleaner than a single class member left public!</p>
|
[
{
"answer_id": 55118,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "union matrix {\n double dflat[16];\n double dmatr[4][4];\n};\n"
},
{
"answer_id": 55149,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "class Parser\n{\npublic:\n typedef double matrix[4][4];\n\n // ...\n\n const matrix& getMatrix() const\n {\n return matrix_;\n }\n\n // ...\n\nprivate:\n matrix matrix_;\n};\n typedef"
},
{
"answer_id": 55167,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "typedef double FourSquare[4][4];\n\nclass Parser\n{\n private:\n double matrix_[4][4];\n\n public:\n Parser()\n {\n for(int i=0; i<4; i++)\n for(int j=0; j<4; j++)\n matrix_[i][j] = i*j;\n }\n\n public:\n const FourSquare& GetMatrix()\n {\n return matrix_;\n }\n};\n\nvoid api_func( const double matrix[4][4] )\n{\n}\n\nint main( int argc, char** argv )\n{\n Parser parser;\n api_func( parser.GetMatrix() );\n return 0;\n}\n"
},
{
"answer_id": 55183,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 2,
"selected": false,
"text": "typedef double matrix_t[4][4];\n\nclass Parser\n{\n double matrix_[4][4];\npublic:\n void* get_matrix () { return static_cast<void*>(matrix_); }\n\n const matrix_t& get_matrix_ref () const { return matrix_; }\n};\n\nint main ()\n{\n Parser p;\n\n matrix_t& data1 = *reinterpret_cast<matrix_t*>(p.get_matrix());\n\n const matrix_t& data2 = p.get_matrix_ref();\n}\n"
},
{
"answer_id": 55341,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "const matrix& getMatrix() const\n Parser"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
55,099 |
<p>We have an intranet site backed by SVN, such that the site is a checkout out copy of the repository (working folder used only by IIS). Something on the site has been causing problems today, and I want to know how to find out what was checked out to that working folder in the last 48 hours.</p>
<p><strong>Update:</strong> If there's an option I need to turn on to enable this in the future, what is it?</p>
<p>Also, as a corollary question, if I have to use the file creation time, how can I do that quickly in a recursive manner for a large folder?</p>
<hr>
<p>If I have to check creation times, then <a href="https://stackoverflow.com/questions/56682/how-to-see-if-a-subfile-of-a-directory-has-changed">this question</a> will be helpful to the solution as well.</p>
|
[
{
"answer_id": 55309,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": true,
"text": "svn info svn blame svn stat svn diff"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
55,101 |
<p>I have a Linq query that I want to call from multiple places:</p>
<pre><code>var myData = from a in db.MyTable
where a.MyValue == "A"
select new {
a.Key,
a.MyValue
};
</code></pre>
<p>How can I create a method, put this code in it, and then call it?</p>
<pre><code>public ??? GetSomeData()
{
// my Linq query
}
</code></pre>
|
[
{
"answer_id": 55110,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 3,
"selected": false,
"text": "IQueryable public IQueryable GetSomeData()\n"
},
{
"answer_id": 55120,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "var IEnumerable<>"
},
{
"answer_id": 55254,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 4,
"selected": true,
"text": "< > < > var myData = from a in db.MyTable\n where a.MyValue == \"A\"\n select new MyType\n {\n Key = a.Key,\n Value = a.MyValue\n };\n"
},
{
"answer_id": 55278,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "public class MyType {Key{get;set;} Value{get;set}}\n\npublic IQueryable<T> GetSomeData<T>() where T : MyType, new() \n { return from a in db.MyTable\n where a.MyValue == \"A\" \n select new T {Key=a.Key,Value=a.MyValue};\n }\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
55,113 |
<p>Word 2007 saves its documents in .docx format which is really a zip file with a bunch of stuff in it including an xml file with the document.</p>
<p>I want to be able to take a .docx file and drop it into a folder in my asp.net web app and have the code open the .docx file and render the (xml part of the) document as a web page.</p>
<p>I've been searching the web for more information on this but so far haven't found much. My questions are:</p>
<ol>
<li>Would you (a) use XSLT to transform the XML to HTML, or (b) use xml manipulation libraries in .net (such as XDocument and XElement in 3.5) to convert to HTML or (c) other?</li>
<li>Do you know of any open source libraries/projects that have done this that I could use as a starting point? </li>
</ol>
<p>Thanks!</p>
|
[
{
"answer_id": 12257270,
"author": "raghava",
"author_id": 1645149,
"author_profile": "https://Stackoverflow.com/users/1645149",
"pm_score": 1,
"selected": false,
"text": ".docx function read_file_docx($filename){\n\n $striped_content = '';\n $content = '';\n\n if(!$filename || !file_exists($filename)) { echo \"sucess\";}else{ echo \"not sucess\";}\n\n $zip = zip_open($filename);\n\n if (!$zip || is_numeric($zip)) return false;\n\n while ($zip_entry = zip_read($zip)) {\n\n if (zip_entry_open($zip, $zip_entry) == FALSE) continue;\n\n if (zip_entry_name($zip_entry) != \"word/document.xml\") continue;\n\n $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));\n\n zip_entry_close($zip_entry);\n }// end while\n\n zip_close($zip);\n\n //echo $content;\n //echo \"<hr>\";\n //file_put_contents('1.xml', $content); \n\n $content = str_replace('</w:r></w:p></w:tc><w:tc>', \" \", $content);\n $content = str_replace('</w:r></w:p>', \"\\r\\n\", $content);\n //header(\"Content-Type: plain/text\");\n\n\n $striped_content = strip_tags($content);\n\n\n $striped_content = preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$striped_content);\n\n echo nl2br($striped_content); \n}\n"
},
{
"answer_id": 27985333,
"author": "messed-up",
"author_id": 4421126,
"author_profile": "https://Stackoverflow.com/users/4421126",
"pm_score": 0,
"selected": false,
"text": "using System.Runtime.InteropServices;\nusing Microsoft.Office.Interop.Word;\n public List<string> GetHelpDocuments()\n {\n\n List<string> lstHtmlDocuments = new List<string>();\n foreach (string _sourceFilePath in Directory.GetFiles(\"\"))\n {\n string[] validextentions = { \".doc\", \".docx\" };\n if (validextentions.Contains(System.IO.Path.GetExtension(_sourceFilePath)))\n {\n sourceFilePath = _sourceFilePath;\n destinationFilePath = _sourceFilePath.Replace(System.IO.Path.GetExtension(_sourceFilePath), \".html\");\n if (System.IO.File.Exists(sourceFilePath))\n {\n //checking if the HTML format of the file already exists. if it does then is it the latest one?\n if (System.IO.File.Exists(destinationFilePath))\n {\n if (System.IO.File.GetCreationTime(destinationFilePath) != System.IO.File.GetCreationTime(sourceFilePath))\n {\n System.IO.File.Delete(destinationFilePath);\n ConvertToHTML();\n }\n }\n else\n {\n ConvertToHTML();\n }\n\n lstHtmlDocuments.Add(destinationFilePath);\n }\n }\n\n\n }\n return lstHtmlDocuments;\n }\n private void ConvertToHtml()\n {\n IsError = false;\n if (System.IO.File.Exists(sourceFilePath))\n {\n Microsoft.Office.Interop.Word.Application docApp = null;\n string strExtension = System.IO.Path.GetExtension(sourceFilePath);\n try\n {\n docApp = new Microsoft.Office.Interop.Word.Application();\n docApp.Visible = true;\n\n docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;\n object fileFormat = WdSaveFormat.wdFormatHTML;\n docApp.Application.Visible = true;\n var doc = docApp.Documents.Open(sourceFilePath);\n doc.SaveAs2(destinationFilePath, fileFormat);\n }\n catch\n {\n IsError = true;\n }\n finally\n {\n try\n {\n docApp.Quit(SaveChanges: false);\n\n }\n catch { }\n finally\n {\n Process[] wProcess = Process.GetProcessesByName(\"WINWORD\");\n foreach (Process p in wProcess)\n {\n p.Kill();\n }\n }\n Marshal.ReleaseComObject(docApp);\n docApp = null;\n GC.Collect();\n }\n }\n }\n private void BindHelpContents()\n {\n List<string> lstHelpDocuments = new List<string>();\n HelpDocuments hDoc = new HelpDocuments(Server.MapPath(\"~/HelpDocx/docx/\"));\n lstHelpDocuments = hDoc.GetHelpDocuments();\n int index = 1;\n ddlHelpDocuments.Items.Insert(0, new ListItem { Value = \"0\", Text = \"---Select Document---\", Selected = true });\n\n foreach (string strHelpDocument in lstHelpDocuments)\n {\n ddlHelpDocuments.Items.Insert(index, new ListItem { Value = strHelpDocument, Text = strHelpDocument.Split('\\\\')[strHelpDocument.Split('\\\\').Length - 1].Replace(\".html\", \"\") });\n index++;\n }\n FetchDocuments();\n\n }\n protected void RenderHelpContents(object sender, EventArgs e)\n {\n try\n {\n if (ddlHelpDocuments.SelectedValue == \"0\") return;\n string strHtml = ddlHelpDocuments.SelectedValue;\n string newaspxpage = strHtml.Replace(Server.MapPath(\"~/\"), \"~/\");\n string pageVirtualPath = VirtualPathUtility.ToAbsolute(newaspxpage);// \n documentholder.Attributes[\"src\"] = pageVirtualPath;\n }\n catch\n {\n lblGError.Text = \"Selected document doesn't exist, please refresh the page and try again. If that doesn't help, please contact Support\";\n }\n }\n"
},
{
"answer_id": 30153764,
"author": "Michael Williamson",
"author_id": 49381,
"author_profile": "https://Stackoverflow.com/users/49381",
"pm_score": 2,
"selected": false,
"text": "Heading 1 <h1>"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
55,114 |
<p>Ok, so I'm an idiot. </p>
<p>So I was working on a regex that took way to long to craft. After perfecting it, I upgraded my work machine with a blazing fast hard drive and realized that I never saved the regex anywhere and simply used RegexBuddy's autosave to store it. Dumb dumb dumb. </p>
<p>I sent a copy of the regex to a coworker but now he can't find it (or the record of our communication). My best hope of finding the regex is to find it in RegexBuddy on the old hard drive. RegexBuddy automatically saves whatever you were working on each time you close it. I've done some preliminary searches to try to determine where it actually saves that working data but I'm having no success. </p>
<p>This question is the result of my dumb behavior but I thought it was a good chance to finally ask a question here. </p>
|
[
{
"answer_id": 55182,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "HKEY_CURRENT_USER\\Software\\JGsoft\\RegexBuddy3\\History\n C:\\Documents and Settings\\<username>\\Application Data\\JGsoft\\RegexBuddy 3\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116922/"
] |
55,130 |
<p>This is a segment of code from an app I've inherited, a user got a Yellow screen of death:</p>
<blockquote>
<p>Object reference not set to an instance of an object</p>
</blockquote>
<p>on the line: </p>
<pre><code>bool l_Success ...
</code></pre>
<p>Now I'm 95% sure the faulty argument is <code>ref l_Monitor</code> which is very weird considering the object is instantiated a few lines before. Anyone have a clue why it would happen? Note that I have seen the same issue pop up in other places in the code.</p>
<pre><code>IDMS.Monitor l_Monitor = new IDMS.Monitor();
l_Monitor.LogFile.Product_ID = "SE_WEB_APP";
if (m_PermType_RadioButtonList.SelectedIndex == -1) {
l_Monitor.LogFile.Log(
Nortel.IS.IDMS.LogFile.MessageTypes.ERROR,
"No permission type selected"
);
return;
}
bool l_Success = SE.UI.Utilities.GetPermissionList(
ref l_Monitor,
ref m_CPermissions_ListBox,
(int)this.ViewState["m_Account_Share_ID"],
(m_PermFolders_DropDownList.Enabled)
? m_PermFolders_DropDownList.SelectedItem.Value
: "-1",
(SE.Types.PermissionType)m_PermType_RadioButtonList.SelectedIndex,
(SE.Types.PermissionResource)m_PermResource_RadioButtonList.SelectedIndex);
</code></pre>
|
[
{
"answer_id": 84541,
"author": "Beriadan",
"author_id": 1983,
"author_profile": "https://Stackoverflow.com/users/1983",
"pm_score": 0,
"selected": false,
"text": "NullReferenceException l_Monitor"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
] |
55,159 |
<p>In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?</p>
<blockquote>
<p>duplicate of:<br>
<a href="https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row">Best way to get identity of inserted row?</a></p>
</blockquote>
|
[
{
"answer_id": 55172,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 6,
"selected": true,
"text": "command.CommandText = \"INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()\";\nint id = (int)command.ExecuteScalar();\n"
},
{
"answer_id": 55190,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[InsertProducts]\n @id INT = NULL OUT,\n @name VARCHAR(150) = NULL,\n @desc VARCHAR(250) = NULL\n\nAS\n\n INSERT INTO dbo.Products\n (Name,\n Description)\n VALUES\n (@name,\n @desc)\n\n SET @id = SCOPE_IDENTITY();\n"
},
{
"answer_id": 55299,
"author": "kamajo",
"author_id": 5415,
"author_profile": "https://Stackoverflow.com/users/5415",
"pm_score": 4,
"selected": false,
"text": "OUTPUT INSERTED.columnname insert DECLARE @MyTableVar table( ID int, \n Name varchar(50), \n ModifiedDate datetime); \nINSERT MyTable \n OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.ModifiedDate INTO @MyTableVar \nSELECT someName, GetDate() from SomeTable \n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096640/"
] |
55,180 |
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p>
<p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p>
<p>For example, you had this:</p>
<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
</code></pre>
<p>I want to print the associated values in the following sequence sorted by key:</p>
<pre><code>this is a
this is b
this is c
</code></pre>
|
[
{
"answer_id": 55188,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "keys = list(d.keys())\nkeys.sort()\nfor key in keys:\n print d[key]\n sorted()"
},
{
"answer_id": 55193,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": false,
"text": "for key in sorted(d):\n print d[key]\n"
},
{
"answer_id": 55194,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "for key, value in sorted(d.items()):\n print value\n"
},
{
"answer_id": 55197,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": ">>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}\n>>> for k,v in sorted(d.items()):\n... print v, k\n... \nthis is a a\nthis is b b\nthis is c c\n"
},
{
"answer_id": 55202,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}\nks = d.keys()\nks.sort()\nfor k in ks:\n print \"this is \" + k\n"
},
{
"answer_id": 56134,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 0,
"selected": false,
"text": "for key in sorted(d):\n print d[key]\n"
},
{
"answer_id": 59235,
"author": "Peter C",
"author_id": 1952,
"author_profile": "https://Stackoverflow.com/users/1952",
"pm_score": 2,
"selected": false,
"text": "import operator\n\nd = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}\n\nfor key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):\n print key, \" \", value\n"
},
{
"answer_id": 40301443,
"author": "Ukimiku",
"author_id": 6804704,
"author_profile": "https://Stackoverflow.com/users/6804704",
"pm_score": 0,
"selected": false,
"text": "from collections import OrderedDict\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
55,203 |
<p>I have an asp.net web page written in C#.<br>
Using some javascript I popup another .aspx page which has a few controls that are filled in and from which I create a small snippet of text.<br>
When the user clicks OK on that dialog box I want to insert that piece of text into a textbox on the page that initial "popped up" the dialog/popup page. </p>
<p>I'm guessing that this will involve javascript which is not a strong point of mine.</p>
<p>How do I do this?</p>
|
[
{
"answer_id": 55242,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 4,
"selected": true,
"text": "parent.opener.document.getElemenyById('ParentTextBox').value = \"New Text\";\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
55,206 |
<p>What is the operator precedence order in Visual Basic 6.0 (VB6)?</p>
<p>In particular, for the logical operators.</p>
|
[
{
"answer_id": 55215,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 5,
"selected": true,
"text": "^ - * / \\ Mod + - & = <> < > <= >= Like Is Not And Or Xor Eqv Imp"
},
{
"answer_id": 55260,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "If A < B And B < C Then\n < And"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
] |
55,210 |
<p>What would be the best strategy to generate anagrams.</p>
<blockquote>
<pre><code>An anagram is a type of word play, the result of rearranging the letters
of a word or phrase to produce a new word or phrase, using all the original
letters exactly once;
ex.
</code></pre>
<ul>
<li><strong>Eleven plus two</strong> is anagram of <strong><em>Twelve plus one</em></strong> </li>
<li><strong>A decimal point</strong> is anagram of <strong><em>I'm a dot in place</em></strong></li>
<li><strong>Astronomers</strong> is anagram of <strong><em>Moon starers</em></strong></li>
</ul>
</blockquote>
<p>At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary.</p>
<p>I came across this page, <a href="http://lojic.com/blog/2007/10/22/solving-anagrams-in-ruby/" rel="noreferrer">Solving anagrams in Ruby</a>. </p>
<p>But what are your ideas?</p>
|
[
{
"answer_id": 55255,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "lettermap[set(a,e,d,f)] = { \"deaf\", \"fade\" }\n astronomers => (a,e,m,n,o,o,r,r,s,s,t)\n"
},
{
"answer_id": 55339,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 0,
"selected": false,
"text": "function FindWords(solutionList, wordsSoFar, sortedQuery)\n // base case\n if sortedQuery is empty\n solutionList.Add(wordsSoFar)\n return\n\n // recursive case\n\n // InitialStrings(\"abc\") is {\"a\",\"ab\",\"abc\"}\n foreach initialStr in InitalStrings(sortedQuery)\n // Remaining letters after initialStr\n sortedQueryRec := sortedQuery.Substring(initialStr.Length)\n words := words matching initialStr in the dictionary\n // Note that sometimes words list will be empty\n foreach word in words\n // Append should return a new list, not change wordSoFar\n wordsSoFarRec := Append(wordSoFar, word) \n FindWords(solutionList, wordSoFarRec, sortedQueryRec)\n"
},
{
"answer_id": 1924561,
"author": "FogleBird",
"author_id": 90308,
"author_profile": "https://Stackoverflow.com/users/90308",
"pm_score": 6,
"selected": false,
"text": "words.txt MIN_WORD_SIZE = 4 # min size of a word in the output\n\nclass Node(object):\n def __init__(self, letter='', final=False, depth=0):\n self.letter = letter\n self.final = final\n self.depth = depth\n self.children = {}\n def add(self, letters):\n node = self\n for index, letter in enumerate(letters):\n if letter not in node.children:\n node.children[letter] = Node(letter, index==len(letters)-1, index+1)\n node = node.children[letter]\n def anagram(self, letters):\n tiles = {}\n for letter in letters:\n tiles[letter] = tiles.get(letter, 0) + 1\n min_length = len(letters)\n return self._anagram(tiles, [], self, min_length)\n def _anagram(self, tiles, path, root, min_length):\n if self.final and self.depth >= MIN_WORD_SIZE:\n word = ''.join(path)\n length = len(word.replace(' ', ''))\n if length >= min_length:\n yield word\n path.append(' ')\n for word in root._anagram(tiles, path, root, min_length):\n yield word\n path.pop()\n for letter, node in self.children.iteritems():\n count = tiles.get(letter, 0)\n if count == 0:\n continue\n tiles[letter] = count - 1\n path.append(letter)\n for word in node._anagram(tiles, path, root, min_length):\n yield word\n path.pop()\n tiles[letter] = count\n\ndef load_dictionary(path):\n result = Node()\n for line in open(path, 'r'):\n word = line.strip().lower()\n result.add(word)\n return result\n\ndef main():\n print 'Loading word list.'\n words = load_dictionary('words.txt')\n while True:\n letters = raw_input('Enter letters: ')\n letters = letters.lower()\n letters = letters.replace(' ', '')\n if not letters:\n break\n count = 0\n for word in words.anagram(letters):\n print word\n count += 1\n print '%d results.' % count\n\nif __name__ == '__main__':\n main()\n MIN_WORD_SIZE MIN_WORD_SIZE MIN_WORD_SIZE"
},
{
"answer_id": 14132957,
"author": "Parth",
"author_id": 1944006,
"author_profile": "https://Stackoverflow.com/users/1944006",
"pm_score": 2,
"selected": false,
"text": "// recursive function to find all the anagrams for charInventory characters\n// starting with the word at dictionaryIndex in dictionary keyList\nprivate Set<Set<String>> findAnagrams(int dictionaryIndex, char[] charInventory, List<String> keyList) {\n // terminating condition if no words are found\n if (dictionaryIndex >= keyList.size() || charInventory.length < minWordSize) {\n return null;\n }\n\n String searchWord = keyList.get(dictionaryIndex);\n char[] searchWordChars = searchWord.toCharArray();\n // this is where you find the anagrams for whole word\n if (AnagramSolverHelper.isEquivalent(searchWordChars, charInventory)) {\n Set<Set<String>> anagramsSet = new HashSet<Set<String>>();\n Set<String> anagramSet = new HashSet<String>();\n anagramSet.add(searchWord);\n anagramsSet.add(anagramSet);\n\n return anagramsSet;\n }\n\n // this is where you find the anagrams with multiple words\n if (AnagramSolverHelper.isSubset(searchWordChars, charInventory)) {\n // update charInventory by removing the characters of the search\n // word as it is subset of characters for the anagram search word\n char[] newCharInventory = AnagramSolverHelper.setDifference(charInventory, searchWordChars);\n if (newCharInventory.length >= minWordSize) {\n Set<Set<String>> anagramsSet = new HashSet<Set<String>>();\n for (int index = dictionaryIndex + 1; index < keyList.size(); index++) {\n Set<Set<String>> searchWordAnagramsKeysSet = findAnagrams(index, newCharInventory, keyList);\n if (searchWordAnagramsKeysSet != null) {\n Set<Set<String>> mergedSets = mergeWordToSets(searchWord, searchWordAnagramsKeysSet);\n anagramsSet.addAll(mergedSets);\n }\n }\n return anagramsSet.isEmpty() ? null : anagramsSet;\n }\n }\n\n // no anagrams found for current word\n return null;\n}\n"
},
{
"answer_id": 41226791,
"author": "ACV",
"author_id": 912829,
"author_profile": "https://Stackoverflow.com/users/912829",
"pm_score": 2,
"selected": false,
"text": "package com.vvirlan;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class Words {\n private int[] PRIMES = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,\n 79, 83, 89, 97, 101, 103, 107, 109, 113 };\n\n public static void main(String[] args) {\n Scanner s = new Scanner(System.in);\n String word = \"hello\";\n System.out.println(\"Please type a word:\");\n if (s.hasNext()) {\n word = s.next();\n }\n Words w = new Words();\n w.start(word);\n }\n\n private void start(String word) {\n measureTime();\n char[] letters = word.toUpperCase().toCharArray();\n long searchProduct = calculateProduct(letters);\n System.out.println(searchProduct);\n try {\n findByProduct(searchProduct);\n } catch (Exception e) {\n e.printStackTrace();\n }\n measureTime();\n System.out.println(matchingWords);\n System.out.println(\"Total time: \" + time);\n }\n\n private List<String> matchingWords = new ArrayList<>();\n\n private void findByProduct(long searchProduct) throws IOException {\n File f = new File(\"/usr/share/dict/words\");\n FileReader fr = new FileReader(f);\n BufferedReader br = new BufferedReader(fr);\n String line = null;\n while ((line = br.readLine()) != null) {\n char[] letters = line.toUpperCase().toCharArray();\n long p = calculateProduct(letters);\n if (p == -1) {\n continue;\n }\n if (p == searchProduct) {\n matchingWords.add(line);\n }\n }\n br.close();\n }\n\n private long calculateProduct(char[] letters) {\n long result = 1L;\n for (char c : letters) {\n if (c < 65) {\n return -1;\n }\n int pos = c - 65;\n result *= PRIMES[pos];\n }\n return result;\n }\n\n private long time = 0L;\n\n private void measureTime() {\n long t = new Date().getTime();\n if (time == 0L) {\n time = t;\n } else {\n time = t - time;\n }\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] |
55,218 |
<p>I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key.</p>
<p>I have done the following:</p>
<pre><code>strtolower(substr(crypt(time()), 0, 7));
</code></pre>
<p>But I have found that once in a while I end up with a duplicate key (rarely, but often enough).</p>
<p>I have also thought of doing:</p>
<pre><code>strtolower(substr(crypt(uniqid(rand(), true)), 0, 7));
</code></pre>
<p>But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible.</p>
<p>After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary.</p>
<p>One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique.</p>
<p>Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found <a href="http://userident.com" rel="noreferrer">http://userident.com</a> but I'm not sure if the keys will be completely unique.</p>
<p>This needs to run in the background without any user input.</p>
|
[
{
"answer_id": 55233,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "$this->password = '';\n\nfor($i=0; $i<10; $i++)\n{\n if($i%2 == 0)\n $this->password .= chr(rand(65,90));\n if($i%3 == 0)\n $this->password .= chr(rand(97,122));\n if($i%4 == 0)\n $this->password .= chr(rand(48,57));\n}\n"
},
{
"answer_id": 55247,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 1,
"selected": false,
"text": "uniqid()"
},
{
"answer_id": 1426722,
"author": "Vince",
"author_id": 173661,
"author_profile": "https://Stackoverflow.com/users/173661",
"pm_score": 0,
"selected": false,
"text": "$ukey = dechex(time()) . crypt( time() . md5(microtime() + mt_rand(0, 100000)) ); \n"
},
{
"answer_id": 2472907,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 0,
"selected": false,
"text": "function GetUniqueValue()\n{\n static $counter = 0; //initalized only 1st time function is called\n return strtr(microtime(), array('.' => '', ' ' => '')) . $counter++;\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
55,270 |
<p>I have some code that modifies a value that several controls in other update panels are bound to. When this event handler fires, I'd like it to force the other update panels to refresh as well, so they can rebind.</p>
<p>Is this possible?</p>
<p>Edit: </p>
<p>To clarify, I have an update panel in one user control, the other update panels are in other user controls, so they can't see each other unless I were to expose some custom properties and use findControl etc etc...</p>
<p>Edit Again:</p>
<p>Here is what I came up with:</p>
<pre><code>public void Update()
{
recursiveUpdate(this);
}
private void recursiveUpdate(Control control)
{
foreach (Control c in control.Controls)
{
if (c is UpdatePanel)
{
((UpdatePanel)c).Update();
}
if (c.HasControls())
{
recursiveUpdate(c);
}
}
}
</code></pre>
<p>I had 3 main user controls that were full of update panels, these controls were visible to the main page, so I added an Update method there that called Update on those three.</p>
<p>In my triggering control, I just cast this.Page into the currentpage and called Update.</p>
<p>Edit:</p>
<p>AARRGGGG!</p>
<p>While the update panels refresh, it does not call Page_Load within the subcontrols in them...What do I do now!</p>
|
[
{
"answer_id": 23698230,
"author": "ravenx30",
"author_id": 3515281,
"author_profile": "https://Stackoverflow.com/users/3515281",
"pm_score": 0,
"selected": false,
"text": "PresenterClass.AttachInterface(mIOrder);\nPresenterClass.DoSomeCalulation();\nPresenterClass.drawPanel(1);\nPresenterClass.AttachInterface(mIOtherOrder);\nPresenterClass.DoSomeCalulation();\nPresenterClass.drawPanel(2);\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
55,296 |
<p>I'm looking to implement httpOnly in my legacy ASP classic sites.
Anyone knows how to do it?</p>
|
[
{
"answer_id": 55389,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 5,
"selected": true,
"text": "Response.AddHeader \"Set-Cookie\", \"mycookie=yo; HttpOnly\"\n expires path secure"
},
{
"answer_id": 14818679,
"author": "Brian Clark",
"author_id": 1496402,
"author_profile": "https://Stackoverflow.com/users/1496402",
"pm_score": 4,
"selected": false,
"text": "<rewrite>\n <outboundRules>\n <rule name=\"Add HttpOnly\" preCondition=\"No HttpOnly\">\n <match serverVariable=\"RESPONSE_Set_Cookie\" pattern=\".*\" negate=\"false\" />\n <action type=\"Rewrite\" value=\"{R:0}; HttpOnly\" />\n <conditions>\n </conditions>\n </rule>\n <preConditions>\n <preCondition name=\"No HttpOnly\">\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\".\" />\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\"; HttpOnly\" negate=\"true\" />\n </preCondition>\n </preConditions>\n </outboundRules>\n</rewrite>\n"
},
{
"answer_id": 31680643,
"author": "Hernaldo Gonzalez",
"author_id": 1536197,
"author_profile": "https://Stackoverflow.com/users/1536197",
"pm_score": 0,
"selected": false,
"text": "Response.AddHeader \"Set-Cookie\", \"\"&CStr(Request.ServerVariables(\"HTTP_COOKIE\"))&\";path=/;HttpOnly\"&\"\"\n"
},
{
"answer_id": 62751004,
"author": "Yvan Zhu",
"author_id": 13054805,
"author_profile": "https://Stackoverflow.com/users/13054805",
"pm_score": -1,
"selected": false,
"text": " <rewrite>\n <outboundRules>\n <rule name=\"Add HttpOnly\" preCondition=\"No HttpOnly\">\n <match serverVariable=\"RESPONSE_Set_Cookie\" pattern=\".*\" negate=\"false\" />\n <action type=\"Rewrite\" value=\"{R:0}; HttpOnly\" />\n <conditions>\n </conditions>\n </rule>\n <preConditions>\n <preCondition name=\"No HttpOnly\">\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\".\" />\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\"; HttpOnly\" negate=\"true\" />\n </preCondition>\n </preConditions>\n </outboundRules>\n </rewrite>\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
55,297 |
<p>Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.</p>
<p>I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net.
The site itself remains ASP for the moment...</p>
<p>Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)?
What do I replace below with?:</p>
<pre><code>set objRS = oConn.execute(SQL)
while not objRS.eof
...
name = Cstr(objRS(1))
...
wend
</code></pre>
<p>and also mutliple recordsets can be replaced with?
I'm talking :</p>
<pre><code> set objRS = objRs.nextRecordset
</code></pre>
<p>Anybody went through this and can recommend?</p>
<p><strong><em>@AdditionalInfo - you asked for it :-)</em></strong></p>
<p>Let me start at the beginning.
<strong>Existing Situation is</strong>:
I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).</p>
<p>Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.</p>
<p>I <em>could</em> go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.</p>
<p>Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.</p>
<p>That brings me to the questions above!</p>
|
[
{
"answer_id": 55358,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 2,
"selected": false,
"text": "MyDataWebService ws = new MyDataWebService();\nforeach(DataItem item in myData)\n{\n ws.Insert(item);\n}\n MyDataWebService ws = new MyDataWebService();\nws.Insert(myData); // Let the web service process the whole set at once.\n"
},
{
"answer_id": 55378,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 1,
"selected": false,
"text": "[WebMethod]\npublic string HelloWorld()\n{\n return \"Hello World\";\n}\n Dim xhr\n\nSet xhr = server.CreateObject(\"MSXML2.XMLHTTP\")\n\nxhr.Open \"POST\", \"/MyService.asmx/HelloWorld\", false\nxhr.SetRequestHeader \"content-type\", \"application/x-www-form-urlencoded\"\nxhr.Send\n\nResponse.Write(xhr.ResponseText)\n <string>Hello World</string>\n"
},
{
"answer_id": 75703,
"author": "Skyhigh",
"author_id": 13387,
"author_profile": "https://Stackoverflow.com/users/13387",
"pm_score": 2,
"selected": true,
"text": "Class clsDatabase\n\n Private Sub Class_Initialize()\n If Session(\"Debug\") Then Response.Write \"Database Initialized<br />\"\n End Sub\n\n Private Sub Class_Terminate()\n If Session(\"Debug\") Then Response.Write \"Database Terminated<br />\"\n End Sub\n\n Public Function Run(SQL)\n Set RS = CreateObject(\"ADODB.Recordset\")\n RS.CursorLocation = adUseClient\n RS.Open SQLValidate(SQL), Application(\"Data\"), adOpenKeyset, adLockReadOnly, adCmdText\n Set Run = RS\n Set RS = nothing\n End Function\n\n Public Function SQLValidate(SQL)\n SQLValidate = SQL\n SQLValidate = Replace(SQLValidate, \"--\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \";\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"SP_\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"@@\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" DECLARE\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"EXEC\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" DROP\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" CREATE\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" GRANT\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" XP_\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"CHAR(124)\", \"\", 1, -1, 1)\n End Function\nEnd Class\n Set oData = new clsDatabase\nSet Recordset = oData.Run(\"SELECT field FROM table WHERE something = another\")\nSet oData = nothing\n"
},
{
"answer_id": 79876,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 1,
"selected": false,
"text": "\"C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\RegAsm.exe\" \"C:\\path\\to\\assembly.dll\" /tlb /codebase\n Dim obj, returnValue\nSet obj = Server.CreateObject(\"MyProject.MyClass\")\nreturnValue = obj.DoSomething(param1, param2)\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] |
55,313 |
<p>One thing I really miss about Java is the tool support. FindBugs, Checkstyle and PMD made for a holy trinity of code quality metrics and automatic bug checking. </p>
<p>Is there anything that will check for simple bugs and / or style violations of Ruby code? Bonus points if I can adapt it for frameworks such as Rails so that Rails idioms are adhered to.</p>
|
[
{
"answer_id": 55357,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "NamedLikeThis"
},
{
"answer_id": 16063567,
"author": "Bozhidar Batsov",
"author_id": 291550,
"author_profile": "https://Stackoverflow.com/users/291550",
"pm_score": 3,
"selected": false,
"text": "ripper"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266/"
] |
55,317 |
<p>When objects from a CallList intersect the near plane I get a flicker..., what can I do?</p>
<p>Im using OpenGL and SDL.</p>
<p>Yes it is double buffered.</p>
|
[
{
"answer_id": 55331,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 0,
"selected": false,
"text": " glPolygonOffset is useful for rendering hidden-line images,\n for applying decals to surfaces, and for rendering solids\n with highlighted edges.\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] |
55,342 |
<p>I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator.</p>
<p>I don't want to just lock the database and let the users quit gracefully.</p>
<p>How would I script this?</p>
|
[
{
"answer_id": 55359,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 7,
"selected": true,
"text": "ALTER SYSTEM ENABLE RESTRICTED SESSION;\n\nbegin \n for x in ( \n select Sid, Serial#, machine, program \n from v$session \n where \n machine <> 'MyDatabaseServerName' \n ) loop \n execute immediate 'Alter System Kill Session '''|| x.Sid \n || ',' || x.Serial# || ''' IMMEDIATE'; \n end loop; \nend;\n"
},
{
"answer_id": 59580,
"author": "Grrey",
"author_id": 6155,
"author_profile": "https://Stackoverflow.com/users/6155",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE TRIGGER rds_logon_trigger\nAFTER LOGON ON DATABASE\nBEGIN\n IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN\n RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');\n END IF;\n\n IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN\n RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');\n END IF;\n\nEND;\n"
},
{
"answer_id": 60807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "ALTER SYSTEM ENABLE RESTRICTED SESSION;\n"
},
{
"answer_id": 234184,
"author": "Gazmo",
"author_id": 31175,
"author_profile": "https://Stackoverflow.com/users/31175",
"pm_score": 2,
"selected": false,
"text": "ALTER SYSTEM QUIESCE RESTRICTED;\n"
},
{
"answer_id": 939765,
"author": "jon077",
"author_id": 22801,
"author_profile": "https://Stackoverflow.com/users/22801",
"pm_score": 1,
"selected": false,
"text": "select\nowner||'.'||object_name obj ,\noracle_username||' ('||s.status||')' oruser ,\nos_user_name osuser ,\nmachine computer ,\nl.process unix ,\ns.sid||','||s.serial# ss ,\nr.name rs ,\nto_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time\nfrom v$locked_object l ,\ndba_objects o ,\nv$session s ,\nv$transaction t ,\nv$rollname r\nwhere l.object_id = o.object_id\nand s.sid=l.session_id\nand s.taddr=t.addr\nand t.xidusn=r.usn\norder by osuser, ss, obj\n;\n Alter System Kill Session '<value from ss above>'\n;\n"
},
{
"answer_id": 3825265,
"author": "Gaius",
"author_id": 447514,
"author_profile": "https://Stackoverflow.com/users/447514",
"pm_score": 4,
"selected": false,
"text": "startup force;\n"
},
{
"answer_id": 6122593,
"author": "dovka",
"author_id": 555848,
"author_profile": "https://Stackoverflow.com/users/555848",
"pm_score": 1,
"selected": false,
"text": "select ses.USERNAME,\n substr(MACHINE,1,10) as MACHINE, \n substr(module,1,25) as module,\n status, \n 'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill\nfrom v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)\nwhere schemaname <> 'SYS'\n and not exists\n (select 1 \n from DBA_ROLE_PRIVS \n where GRANTED_ROLE='DBA' \n and schemaname=grantee)\n and machine!='yourlocalhostname' \norder by LAST_CALL_ET desc;\n"
},
{
"answer_id": 7806123,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 3,
"selected": false,
"text": "BEGIN\n FOR c IN (\n SELECT s.sid, s.serial#\n FROM v$session s\n WHERE (s.Osuser = 'MyUser' or s.MACHINE = 'MyNtDomain\\MyMachineName')\n AND s.USERNAME <> 'SYS'\n AND s.STATUS <> 'KILLED'\n )\n LOOP\n EXECUTE IMMEDIATE 'alter system kill session ''' || c.sid || ',' || c.serial# || '''';\n END LOOP;\nEND;\n"
},
{
"answer_id": 9117640,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "alter system kill session '130,620,@1';\n"
},
{
"answer_id": 36299914,
"author": "Ramki",
"author_id": 4136306,
"author_profile": "https://Stackoverflow.com/users/4136306",
"pm_score": 0,
"selected": false,
"text": "ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}'"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] |
55,360 |
<p>The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??</p>
<p>It's a simple asp:LinkButton with an OnClick event</p>
<pre><code><asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
</code></pre>
<p>The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.</p>
<p>I enable the control on the page load event.</p>
<p>Any ideas?</p>
<hr>
<p>I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"</p>
<p>Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.</p>
<p>Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.</p>
|
[
{
"answer_id": 55367,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "if (!confirm(...)) { return false; } _doPostBack(...);\n <a href=\"javascript:__doPostBack()\" onclick=\"return confirm()\" />\n"
},
{
"answer_id": 55379,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "function __doPostBack(eventTarget, eventArgument) {\n\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n\n theForm.__EVENTTARGET.value = eventTarget;\n\n theForm.__EVENTARGUMENT.value = eventArgument;\n\n theForm.submit();\n\n }\n\n}\n"
},
{
"answer_id": 55420,
"author": "moza",
"author_id": 3465,
"author_profile": "https://Stackoverflow.com/users/3465",
"pm_score": 1,
"selected": false,
"text": "if (!isPostBack)\n{\n //do something\n}\nelse if (Request.Form[\"__EVENTTARGET\"].ToLower().IndexOf(\"myevent\") >= 0)\n{\n //call appropriate function.\n}\n"
},
{
"answer_id": 1004304,
"author": "Todd",
"author_id": 54305,
"author_profile": "https://Stackoverflow.com/users/54305",
"pm_score": 2,
"selected": false,
"text": "<input type=\"button\" id=\"yourButton\" onclick=\"doSomethingThenPostBack();\" value=\"Post\" />\n <input type=\"submit\" id=\"yourButton\" ...\n"
},
{
"answer_id": 24784827,
"author": "SSZero",
"author_id": 400323,
"author_profile": "https://Stackoverflow.com/users/400323",
"pm_score": 0,
"selected": false,
"text": "__doPostBack() <asp:Button runat=\"server\" ID=\"btnMyPostback\" OnClick=\"btnMyPostback_Click\" CssClass=\"hide\" ToolTip=\"Click here to submit this transaction.\" />\n protected void btnMyPostback_Click(object sender, EventArgs e)\n {\n //do my postback stuff\n }\n $(\"#btnMyPostback\").trigger(\"click\");\n Page_Load Page_Load"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230/"
] |
55,365 |
<p>I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?</p>
|
[
{
"answer_id": 55493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "XKeymacs"
},
{
"answer_id": 85113,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "import readline\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
55,375 |
<p>I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java? I mean "extend" in both the sense of adding new values to an enum, but also in the OO sense of inheriting from an existing enum. </p>
<p>I assume it's not possible in Java, as it only got them fairly recently (Java 5?). C# seems more forgiving of people that want to do crazy things, though, so I thought it might be possible some way. Presumably it could be hacked up via reflection (not that you'd every actually use that method)?</p>
<p>I'm not necessarily interested in implementing any given method, it just provoked my curiosity when it occurred to me :-)</p>
|
[
{
"answer_id": 55390,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 2,
"selected": false,
"text": "Enum.GetNames() Enum.GetValues()"
},
{
"answer_id": 55486,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 6,
"selected": false,
"text": "public class Action {\n public string Name {get; private set;}\n public string Description {get; private set;}\n\n private Action(string name, string description) {\n Name = name;\n Description = description;\n }\n\n public static Action DoIt = new Action(\"Do it\", \"This does things\");\n public static Action StopIt = new Action(\"Stop It\", \"This stops things\");\n}\n public void ProcessAction(Action a) {\n Console.WriteLine(\"Performing action: \" + a.Name)\n if (a == Action.DoIt) {\n // ... and so on\n }\n}\n"
},
{
"answer_id": 55521,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 2,
"selected": false,
"text": "class Person {\n enum Bracket {\n Low(0, 12000),\n Middle(12000, 60000),\n Upper(60000, 100000);\n\n private final int low;\n private final int high;\n Brackets(int low, int high) {\n this.low = low;\n this.high = high;\n }\n\n public int getLow() {\n return low;\n }\n\n public int getHigh() {\n return high;\n }\n\n public boolean isWithin(int value) {\n return value >= low && value <= high;\n }\n\n public String toString() {\n return \"Bracket \" + low + \" to \" + high;\n }\n }\n\n private Bracket bracket;\n private String name;\n\n public Person(String name, Bracket bracket) {\n this.bracket = bracket;\n this.name = name;\n }\n\n public String toString() {\n return name + \" in \" + bracket;\n } \n}\n"
},
{
"answer_id": 56413,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "public interface Result {\n String name();\n String toString();\n}\npublic enum StandardResults implements Result {\n TRUE, FALSE\n}\n\n\npublic enum WTFResults implements Result {\n FILE_NOT_FOUND\n}\n"
},
{
"answer_id": 1688974,
"author": "Ken",
"author_id": 205066,
"author_profile": "https://Stackoverflow.com/users/205066",
"pm_score": 5,
"selected": false,
"text": "enum Animal { Mosquito, Dog, Cat };\nenum Mammal : Animal { Dog, Cat }; // (not valid C#)\n"
},
{
"answer_id": 3230740,
"author": "Magnum",
"author_id": 389712,
"author_profile": "https://Stackoverflow.com/users/389712",
"pm_score": 1,
"selected": false,
"text": "public enum AnchorStyles {\n None = 0,\n Top = 1,\n Bottom = 2,\n Left = 4,\n Right = 8,\n} my_ctrl.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;\n my_ctrl.Anchor = AnchorStyles.BottomRight;\n"
},
{
"answer_id": 18443046,
"author": "Aniket Thakur",
"author_id": 2396539,
"author_profile": "https://Stackoverflow.com/users/2396539",
"pm_score": 0,
"selected": false,
"text": " enum Person (JOHN SAM} \n enum Student extends Person {HARVEY ROSS}\n Person person = Student.ROSS; //not legal\n"
},
{
"answer_id": 27519356,
"author": "Sultan ",
"author_id": 4369010,
"author_profile": "https://Stackoverflow.com/users/4369010",
"pm_score": 0,
"selected": false,
"text": "public enum MyEnum { A = 1, B = 2, C = 4 }\n\npublic const MyEnum D = (MyEnum)(8);\npublic const MyEnum E = (MyEnum)(16);\n\nfunc1{\n MyEnum EnumValue = D;\n\n switch (EnumValue){\n case D: break;\n case E: break;\n case MyEnum.A: break;\n case MyEnum.B: break;\n }\n}\n"
},
{
"answer_id": 58630495,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 1,
"selected": false,
"text": "enum Animals { Dog, Cat }\nenum AnimalsExt { Dog = Animals.Dog, Cat= Animals.Cat, MyOther}\n// BUT CAST THEM when using:\nvar xyz = AnimalsExt.Cat;\nMethodThatNeedsAnimal( (Animals)xyz );\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5296/"
] |
55,386 |
<p>I'm using Windows and I'm trying to get ANT to work.</p>
<p>When I do an ant build from the command line, I get:
<code>C:\dev\Projects\springapp\${%ANT_HOME%}\lib not found.</code></p>
<p>I look into the <code>build.xml</code> file and I find:
<code>appserver.home=${user.home}/apache-tomcat-6.0.14</code> (which I just copied and pasted straight from a tutorial)</p>
<p>I changed it to:</p>
<p><code>appserver.home="C:\Program Files\Apache Software Foundation\Tomcat 6.0"</code></p>
<p>but now I get:</p>
<p><code>C:\dev\Projects\springapp\"C:Program FilesApache Software FoundationTomcat 6.0"\lib not found.</code></p>
<p>It seems like the white space in Program Files and Tomcat 6.0 are causing the build to fail. How do you deal with these in xml files without re-creating the directory with a path with no white space?</p>
|
[
{
"answer_id": 55426,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "appserver.home=\"C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 6.0\"\n"
},
{
"answer_id": 56911,
"author": "Rob Spieldenner",
"author_id": 5118,
"author_profile": "https://Stackoverflow.com/users/5118",
"pm_score": 2,
"selected": false,
"text": "<property name=\"property.1\" value=\"directory\" />\n <property name=\"property.1\" location=\"directory\" />\n"
},
{
"answer_id": 4327767,
"author": "caseyboardman",
"author_id": 807,
"author_profile": "https://Stackoverflow.com/users/807",
"pm_score": 1,
"selected": false,
"text": "<property environment=\"env\"/> ${env.USER_HOME} ${java.home}"
},
{
"answer_id": 6830626,
"author": "gliptak",
"author_id": 304690,
"author_profile": "https://Stackoverflow.com/users/304690",
"pm_score": 2,
"selected": false,
"text": "dir /x path"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
55,391 |
<p>I want to grab the value of a hidden input field in HTML.</p>
<pre><code><input type="hidden" name="fooId" value="12-3456789-1111111111" />
</code></pre>
<p>I want to write a regular expression in Python that will return the value of <code>fooId</code>, given that I know the line in the HTML follows the format</p>
<pre><code><input type="hidden" name="fooId" value="**[id is here]**" />
</code></pre>
<p>Can someone provide an example in Python to parse the HTML for the value?</p>
|
[
{
"answer_id": 55399,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "/<input type=\"hidden\" name=\"fooId\" value=\"([\\d-]+)\" \\/>/\n"
},
{
"answer_id": 55404,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 3,
"selected": false,
"text": "import re\nreg = re.compile('<input type=\"hidden\" name=\"([^\"]*)\" value=\"<id>\" />')\nvalue = reg.search(inputHTML).group(1)\nprint 'Value is', value\n"
},
{
"answer_id": 55424,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "from BeautifulSoup import BeautifulSoup\n\n#Or retrieve it from the web, etc. \nhtml_data = open('/yourwebsite/page.html','r').read()\n\n#Create the soup object from the HTML data\nsoup = BeautifulSoup(html_data)\nfooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag\nvalue = fooId.attrs[2][1] #The value of the third attribute of the desired tag \n #or index it directly via fooId['value']\n"
},
{
"answer_id": 56144,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 0,
"selected": false,
"text": "/<input\\s+type=\"hidden\"\\s+name=\"([A-Za-z0-9_]+)\"\\s+value=\"([A-Za-z0-9_\\-]*)\"\\s*/>/\n\n>>> import re\n>>> s = '<input type=\"hidden\" name=\"fooId\" value=\"12-3456789-1111111111\" />'\n>>> re.match('<input\\s+type=\"hidden\"\\s+name=\"([A-Za-z0-9_]+)\"\\s+value=\"([A-Za-z0-9_\\-]*)\"\\s*/>', s).groups()\n('fooId', '12-3456789-1111111111')\n"
},
{
"answer_id": 64983,
"author": "A Nony Mouse",
"author_id": 7182,
"author_profile": "https://Stackoverflow.com/users/7182",
"pm_score": 4,
"selected": false,
"text": "fooId['value'] from BeautifulSoup import BeautifulSoup\n#Or retrieve it from the web, etc.\nhtml_data = open('/yourwebsite/page.html','r').read()\n#Create the soup object from the HTML data\nsoup = BeautifulSoup(html_data)\nfooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag\nvalue = fooId['value'] #The value attribute\n"
},
{
"answer_id": 1421480,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 1,
"selected": false,
"text": "html = \"\"\"<html><body>\n<input type=\"hidden\" name=\"fooId\" value=\"**[id is here]**\" />\n<blah>\n<input name=\"fooId\" type=\"hidden\" value=\"**[id is here too]**\" />\n<input NAME=\"fooId\" type=\"hidden\" value=\"**[id is HERE too]**\" />\n<INPUT NAME=\"fooId\" type=\"hidden\" value=\"**[and id is even here TOO]**\" />\n<!--\n<input type=\"hidden\" name=\"fooId\" value=\"**[don't report this id]**\" />\n-->\n<foo>\n</body></html>\"\"\"\n\nfrom pyparsing import makeHTMLTags, withAttribute, htmlComment\n\n# use makeHTMLTags to create tag expression - makeHTMLTags returns expressions for\n# opening and closing tags, we're only interested in the opening tag\ninputTag = makeHTMLTags(\"input\")[0]\n\n# only want input tags with special attributes\ninputTag.setParseAction(withAttribute(type=\"hidden\", name=\"fooId\"))\n\n# don't report tags that are commented out\ninputTag.ignore(htmlComment)\n\n# use searchString to skip through the input \nfoundTags = inputTag.searchString(html)\n\n# dump out first result to show all returned tags and attributes\nprint foundTags[0].dump()\nprint\n\n# print out the value attribute for all matched tags\nfor inpTag in foundTags:\n print inpTag.value\n ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]\n- empty: True\n- name: fooId\n- startInput: ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]\n - empty: True\n - name: fooId\n - type: hidden\n - value: **[id is here]**\n- type: hidden\n- value: **[id is here]**\n\n**[id is here]**\n**[id is here too]**\n**[id is HERE too]**\n**[and id is even here TOO]**\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5675/"
] |
55,403 |
<p>I am interested to know whether anyone has written an application that takes advantage of a <a href="http://en.wikipedia.org/wiki/GPGPU" rel="nofollow noreferrer">GPGPU</a> by using, for example, <a href="http://www.nvidia.com/object/cuda_get.html" rel="nofollow noreferrer">nVidia CUDA</a>. If so, what issues did you find and what performance gains did you achieve compared with a standard CPU?</p>
|
[
{
"answer_id": 853110,
"author": "Edison Gustavo Muenz",
"author_id": 61915,
"author_profile": "https://Stackoverflow.com/users/61915",
"pm_score": 0,
"selected": false,
"text": "if (false){}"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3305/"
] |
55,411 |
<p>Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account. </p>
<p>I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.</p>
<p>I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck.</p>
<p>Can anyone shed some light on this?</p>
<p>**Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.</p>
|
[
{
"answer_id": 60353,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 5,
"selected": true,
"text": "<identity impersonate=\"true\" />\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678/"
] |
55,434 |
<p>This question is the other side of the question asking, "<a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">How do I calculate relative time?</a>".</p>
<p>Given some human input for a relative time, how can you parse it? By default you would offset from <code>DateTime.Now()</code>, but could optionally offset from another <code>DateTime</code>.</p>
<p>(Prefer answers in C#)</p>
<p>Example input:</p>
<ul>
<li>"in 20 minutes"</li>
<li>"5 hours ago"</li>
<li>"3h 2m"</li>
<li>"next week"</li>
</ul>
<p><strong>Edit:</strong> Let's suppose we can define some limits on the input. This sort of code would be a useful thing to have out on the web.</p>
|
[
{
"answer_id": 55469,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": false,
"text": "* Aug 25 5pm\n* 5pm August 25\n* next saturday\n...\n* tomorrow\n* next thursday at 4pm\n* at 4pm\n* eod\n* in 5 minutes\n* 5 minutes from now\n* 5 hours before now\n* 2 days from tomorrow\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
55,440 |
<p>I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.</p>
<pre><code>template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}
</code></pre>
<p>Now, how do I make sure that <code>ImplementationClass</code> can be derived from a set of classes only, similar to java's generics</p>
<pre><code><? extends BaseClass>
</code></pre>
<p>syntax?</p>
|
[
{
"answer_id": 55446,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 4,
"selected": true,
"text": "#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\nstruct base {};\n\ntemplate <typename ImplementationClass, class Enable = void>\nclass WrapperClass;\n\ntemplate <typename ImplementationClass>\nclass WrapperClass<ImplementationClass,\n typename boost::enable_if<\n boost::is_base_of<base,ImplementationClass> >::type>\n{};\n\nstruct derived : base {};\nstruct not_derived {};\n\nint main() {\n WrapperClass<derived> x;\n\n // Compile error here:\n WrapperClass<not_derived> y;\n}\n #include <boost/static_assert.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\nstruct base {};\n\ntemplate <typename ImplementationClass>\nclass WrapperClass\n{\n BOOST_STATIC_ASSERT((\n boost::is_base_of<base, ImplementationClass>::value));\n};\n"
},
{
"answer_id": 56551,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "template<class T, class B> struct Derived_from {\n static void constraints(T* p) { B* pb = p; }\n Derived_from() { void(*p)(T*) = constraints; }\n};\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108465/"
] |
55,449 |
<p>I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'.</p>
<p>I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in. Does P4 have the equivalent of Subversion's 'ignore file' feature? </p>
|
[
{
"answer_id": 55509,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 7,
"selected": true,
"text": "P4IGNORE"
},
{
"answer_id": 56498,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": false,
"text": ".p4ignore"
},
{
"answer_id": 3021154,
"author": "Mike Burrows",
"author_id": 171757,
"author_profile": "https://Stackoverflow.com/users/171757",
"pm_score": 3,
"selected": false,
"text": "write user * * -//.../*.suo\nwrite user * * -//.../*.obj\nwrite user * * -//.../*.ccscc\n"
},
{
"answer_id": 3883647,
"author": "Warren P",
"author_id": 84704,
"author_profile": "https://Stackoverflow.com/users/84704",
"pm_score": 2,
"selected": false,
"text": ".p4ignore"
},
{
"answer_id": 4973027,
"author": "kevin cline",
"author_id": 229810,
"author_profile": "https://Stackoverflow.com/users/229810",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n# reconcile P4 offline work, assuming P4CLIENT is set\nif [ -z \"$P4CLIENT\" ] ; then echo \"P4CLIENT is not set\"; exit 1; fi\nunset PWD # confuses P4 on Windows/CYGWIN\n\n# delete filew that are no longer present\np4 diff -sd ... | p4 -x - delete\n\n# checkout files that have been changed. \n# I don't run this step. Instead I just checkout everything, \n# then revert unchanged files before committing.\np4 diff -se ... | pr -x - edit\n\n# Add new files, ignoring subversion info, EMACS backups, log files\n# Filter output to see only added files and real errors\nfind . -type f \\\n | grep -v -E '(\\.svn)|(/build.*/)|(/\\.settings)|~|#|(\\.log)' \\\n | p4 -x - add \\\n | grep -v -E '(currently opened for add)|(existing file)|(already opened for edit)'\n"
},
{
"answer_id": 9538265,
"author": "Chance",
"author_id": 382186,
"author_profile": "https://Stackoverflow.com/users/382186",
"pm_score": 3,
"selected": false,
"text": "p4 help stream Ignored: Optional; a list of file or directory names to be ignored in\n client views. For example:\n\n /tmp # ignores files named 'tmp'\n /tmp/... # ignores dirs named 'tmp'\n .tmp # ignores file names ending in '.tmp'\n\n Lines in the Ignored field may appear in any order. Ignored\n names are inherited by child stream client views.\n p4 stream //stream_depot/stream_name"
},
{
"answer_id": 13126496,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 6,
"selected": false,
"text": ".gitignore P4IGNORE bin .gitignore p4ignore.txt P4IGNORE"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
55,482 |
<p>I'm able to successfully uninstall a third-party application via the command line and via a custom Inno Setup installer. </p>
<p>Command line Execution:</p>
<pre><code>MSIEXEC.exe /x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn
</code></pre>
<p>Inno Setup Command:</p>
<pre><code>[Run]
Filename: msiexec.exe; Flags: runhidden waituntilterminated;
Parameters: "/x {{14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
StatusMsg: "Uninstalling Service...";
</code></pre>
<p>I am also able to uninstall the application programmatically when executing the following C# code in debug mode.</p>
<p>C# Code:</p>
<pre><code>string fileName = "MSIEXEC.exe";
string arguments = "/x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
ProcessStartInfo psi = new ProcessStartInfo(fileName, arguments)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
Process process = Process.Start(psi);
string errorMsg = process.StandardOutput.ReadToEnd();
process.WaitForExit();
</code></pre>
<p>The same C# code, however, produces the following failure output when run as a compiled, deployed Windows Service: </p>
<pre><code>"This action is only valid for products that are currently installed."
</code></pre>
<p>Additional Comments:</p>
<ul>
<li>The Windows Service which is issuing
the uninstall command is running on
the same machine as the code being
tested in Debug Mode. The Windows
Service is running/logged on as the
Local system account. </li>
<li>I have consulted my application logs
and I have validated that the
executed command arguments are thhe
same in both debug and release mode.</li>
<li>I have consulted the Event Viewer
but it doesn't offer any clues.</li>
</ul>
<p>Thoughts? Any help would be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 55496,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "c:\\windows\\temp"
},
{
"answer_id": 55571,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 2,
"selected": false,
"text": "MSIINV.EXE"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
] |
55,502 |
<p>I have an object in a multi-threaded environment that maintains a collection of information, e.g.:</p>
<pre><code>public IList<string> Data
{
get
{
return data;
}
}
</code></pre>
<p>I currently have <code>return data;</code> wrapped by a <code>ReaderWriterLockSlim</code> to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible? </p>
|
[
{
"answer_id": 55661,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 4,
"selected": false,
"text": "IEnumerable<string>"
},
{
"answer_id": 59545,
"author": "Daniel Fortunov",
"author_id": 5975,
"author_profile": "https://Stackoverflow.com/users/5975",
"pm_score": 4,
"selected": false,
"text": "ReadOnlyCollection ReadOnlyCollection"
},
{
"answer_id": 110479,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "public IList<string> Data {\nget {\n return new List<T>(data);\n}}\n"
},
{
"answer_id": 110515,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "List<string> _Data;\npublic IEnumerable<string> Data\n{\n get\n {\n foreach(string item in _Data)\n {\n return yield item;\n }\n }\n}\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5296/"
] |
55,503 |
<p>I have a main asp.net app, which is written in asp.net 1.1. Runnning underneath the application are several 2.0 apps. To completely logout a user can I just logout of the 1.1 app with FormsAuthentication.SignOut or is it more complicated than that?</p>
|
[
{
"answer_id": 55575,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": true,
"text": "<authentication mode=\"Forms\">\n <forms name=\".cookiename\"\n loginUrl=\"~/Login.aspx\" \n timeout=\"30\" \n path=\"/\" />\n</authentication>\n <machineKey validationKey=\"F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902\"\n encryptionKey=\"F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC\"\n validation=\"SHA1\" />\n protected void Login(string userName, string password)\n{\n System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);\n cookie.Domain = \"domain1.com\";\n cookie.Expires = DateTime.Now.AddDays(30);\n Response.AppendCookie(cookie);\n}\n protected void Logout(string userName)\n{\n System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);\n cookie.Domain = \"domain1.com\";\n cookie.Expires = DateTime.Now.AddDays(-1);\n Response.AppendCookie(cookie);\n}\n"
},
{
"answer_id": 2280558,
"author": "Praveen",
"author_id": 269222,
"author_profile": "https://Stackoverflow.com/users/269222",
"pm_score": 0,
"selected": false,
"text": "HttpCookie cookie = Request.Cookies.Get(otherSiteCookieName);\ncookie.Expires = DateTime.Now.AddDays(-1);\nHttpContext.Current.Response.Cookies.Add(cookie);\n"
},
{
"answer_id": 3150917,
"author": "Daniel Steigerwald",
"author_id": 233902,
"author_profile": "https://Stackoverflow.com/users/233902",
"pm_score": 0,
"selected": false,
"text": "<authentication mode=\"Forms\">\n <forms domain=\".tv.loc\" loginUrl=\"~/signin\" timeout=\"2880\" name=\"auth\" />\n</authentication>\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4888/"
] |
55,506 |
<p>As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:</p>
<pre><code>if @version <> @expects
begin
declare @error varchar(100);
set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
raiserror(@error, 10, 1);
end
else
begin
...sql statements here...
end
</code></pre>
<p>Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:</p>
<pre>
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
</pre>
<p>Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?</p>
|
[
{
"answer_id": 55546,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 6,
"selected": true,
"text": "if @version <> @expects\n begin\n ...snip...\n end\nelse\n begin\n exec('CREATE PROC MyProc AS SELECT ''Victory!''');\n end\n"
},
{
"answer_id": 441970,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "IF NOT EXISTS(SELECT * FROM sys.procedures WHERE name = 'pr_MyStoredProc')\nBEGIN\n\n CREATE PROCEDURE pr_MyStoredProc AS .....\n SET NOCOUNT ON\nEND\n\nALTER PROC pr_MyStoredProc\nAS\nSELECT * FROM tb_MyTable\n"
},
{
"answer_id": 9383336,
"author": "DWalker59",
"author_id": 1224123,
"author_profile": "https://Stackoverflow.com/users/1224123",
"pm_score": 2,
"selected": false,
"text": "Exists Create Alter"
},
{
"answer_id": 36646576,
"author": "Proggear",
"author_id": 5247175,
"author_profile": "https://Stackoverflow.com/users/5247175",
"pm_score": 3,
"selected": false,
"text": "IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')\n SET NOEXEC ON\nGO\nCREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')\nRETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Granite.SQL.CLR.Functions].CLR_CharList_Split\nGO\nSET NOEXEC OFF\n"
},
{
"answer_id": 49648591,
"author": "Dave Thompson",
"author_id": 1049108,
"author_profile": "https://Stackoverflow.com/users/1049108",
"pm_score": 1,
"selected": false,
"text": "IF EXISTS(SELECT * FROM sysobjects WHERE Name = 'PROC_NAME' AND xtype='P') \nBEGIN\n DROP PROCEDURE PROC_NAME\nEND\nGO\nCREATE PROCEDURE PROC_NAME\n @value int\nAS\nBEGIN\n UPDATE SomeTable\n SET SomeColumn = 1\n WHERE Value = @value\nEND\nGO\n"
},
{
"answer_id": 57115083,
"author": "Display name",
"author_id": 4501035,
"author_profile": "https://Stackoverflow.com/users/4501035",
"pm_score": 2,
"selected": false,
"text": "IF NOT EXISTS(SELECT * FROM sysobjects WHERE Name = 'YOUR_STORED_PROC_NAME' AND xtype='P')\nEXECUTE('CREATE PROC [dbo].[YOUR_STORED_PROC_NAME] as BEGIN select 0 END')\nGO\nALTER PROC [dbo].[YOUR_STORED_PROC_NAME]\n....\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] |
55,510 |
<p>I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.</p>
<pre><code>int globalgarbage;
unsigned int anumber = 42;
</code></pre>
<p>But what about static ones defined within a function?</p>
<pre><code>void doSomething()
{
static bool globalish = true;
// ...
}
</code></pre>
<p>When is the space for <code>globalish</code> allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when <code>doSomething()</code> is first called?</p>
|
[
{
"answer_id": 55548,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 8,
"selected": true,
"text": "include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass test\n{\npublic:\n test(const char *name)\n : _name(name)\n {\n cout << _name << \" created\" << endl;\n }\n\n ~test()\n {\n cout << _name << \" destroyed\" << endl;\n }\n\n string _name;\n};\n\ntest t(\"global variable\");\n\nvoid f()\n{\n static test t(\"static variable\");\n\n test t2(\"Local variable\");\n\n cout << \"Function executed\" << endl;\n}\n\n\nint main()\n{\n test t(\"local to main\");\n\n cout << \"Program start\" << endl;\n\n f();\n\n cout << \"Program end\" << endl;\n return 0;\n}\n global variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\n"
},
{
"answer_id": 55592,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 3,
"selected": false,
"text": "foo foo"
},
{
"answer_id": 55877,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "int foo = init(); // bad if init() throws something\n\nint main() {\n try {\n ...\n }\n catch(...){\n ...\n }\n}\n int& foo() {\n static int myfoo = init();\n return myfoo;\n}\n"
},
{
"answer_id": 58804,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": " int foo(int i)\n {\n static int s = foo(2*i); // recursive call - undefined\n return i+1;\n }\n"
},
{
"answer_id": 20355603,
"author": "Thang Le",
"author_id": 2103515,
"author_profile": "https://Stackoverflow.com/users/2103515",
"pm_score": 3,
"selected": false,
"text": "#include <iostream> \n#include <string>\n\nusing namespace std;\n\nclass test\n{\npublic:\n test(const char *name)\n : _name(name)\n {\n cout << _name << \" created\" << endl;\n }\n\n ~test()\n {\n cout << _name << \" destroyed\" << endl;\n }\n\n string _name;\n static test t; // static member\n };\ntest test::t(\"static in class\");\n\ntest t(\"global variable\");\n\nvoid f()\n{\n static test t(\"static variable\");\n static int num = 10 ; // POD type, init before enter main function\n \n test t2(\"Local variable\");\n cout << \"Function executed\" << endl;\n}\n\nint main()\n{\n test t(\"local to main\");\n cout << \"Program start\" << endl;\n f();\n cout << \"Program end\" << endl;\n return 0;\n }\n static in class created\nglobal variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\nstatic in class destroyed\n"
},
{
"answer_id": 70837256,
"author": "Sherif Beshr",
"author_id": 15441343,
"author_profile": "https://Stackoverflow.com/users/15441343",
"pm_score": -1,
"selected": false,
"text": " int func(int x)\n {\n static int static_x = 4;\n static_x = x;\n printf (\"Address = 0x%x\",&static_x ); // prints 0x40a010\n return static_x;\n }\n int main()\n {\n int x = 8;\n uint32_t *ptr = (uint32_t *)(0x40a010); // static_x location\n printf (\"Initial = %d\\n\",*ptr);\n func(x);\n \n return 0;\n }\n"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
55,517 |
<p>We are getting very slow compile times, which can take upwards of 20+ minutes on dual core 2GHz, 2G Ram machines.</p>
<p>A lot of this is due to the size of our solution which has grown to 70+ projects, as well as VSS which is a bottle neck in itself when you have a lot of files. (swapping out VSS is not an option unfortunately, so I don't want this to descend into a VSS bash)</p>
<p>We are looking at merging projects. We are also looking at having multiple solutions to achieve greater separation of concerns and quicker compile times for each element of the application. This I can see will become a DLL hell as we try to keep things in synch.</p>
<p>I am interested to know how other teams have dealt with this scaling issue, what do you do when your code base reaches a critical mass that you are wasting half the day watching the status bar deliver compile messages.</p>
<p><strong>UPDATE</strong>
I neglected to mention this is a C# solution. Thanks for all the C++ suggestions, but it's been a few years since I've had to worry about headers.</p>
<p><strong>EDIT:</strong></p>
<p>Nice suggestions that have helped so far (not saying there aren't other nice suggestions below, just what has helped)</p>
<ul>
<li>New 3GHz laptop - the power of lost utilization works wonders when whinging to management
<li>Disable Anti Virus during compile
<li>'Disconnecting' from VSS (actually the network) during compile - I may get us to remove VS-VSS integration altogether and stick to using the VSS UI
</ul>
<p>Still not rip-snorting through a compile, but every bit helps.</p>
<p>Orion did mention in a comment that generics may have a play also. From my tests there does appear to be a minimal performance hit, but not high enough to sure - compile times can be inconsistent due to disc activity. Due to time limitations, my tests didn't include as many Generics, or as much code, as would appear in live system, so that may accumulate. I wouldn't avoid using generics where they are supposed to be used, just for compile time performance</p>
<p><strong>WORKAROUND</strong></p>
<p>We are testing the practice of building new areas of the application in new solutions, importing in the latest dlls as required, them integrating them into the larger solution when we are happy with them.</p>
<p>We may also do them same to existing code by creating temporary solutions that just encapsulate the areas we need to work on, and throwing them away after reintegrating the code. We need to weigh up the time it will take to reintegrate this code against the time we gain by not having Rip Van Winkle like experiences with rapid recompiling during development.</p>
|
[
{
"answer_id": 55542,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 1,
"selected": false,
"text": "<compilation defaultLanguage=\"c#\" debug=\"true\" batch=\"true\" > \n"
},
{
"answer_id": 55625,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 1,
"selected": false,
"text": "#include \"file1.cpp\"\n#include \"file2.cpp\"\n....\n#include \"fileN.cpp\"\n"
},
{
"answer_id": 3558097,
"author": "Pavel Radzivilovsky",
"author_id": 73656,
"author_profile": "https://Stackoverflow.com/users/73656",
"pm_score": 3,
"selected": false,
"text": "/Bt /showIncludes"
},
{
"answer_id": 6626597,
"author": "Gone Coding",
"author_id": 201078,
"author_profile": "https://Stackoverflow.com/users/201078",
"pm_score": 6,
"selected": false,
"text": "Project references DLL references"
},
{
"answer_id": 6934256,
"author": "Luke Li",
"author_id": 877575,
"author_profile": "https://Stackoverflow.com/users/877575",
"pm_score": 0,
"selected": false,
"text": "obj bin Clean solution"
}
] |
2008/09/10
|
[
"https://Stackoverflow.com/questions/55517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
55,532 |
<p>This came up from <a href="https://stackoverflow.com/questions/55093/how-to-deal-with-arrays-declared-on-the-stack-in-c#55183">this answer to a previous question of mine</a>.
Is it guaranteed for the compiler to treat <code>array[4][4]</code> the same as <code>array[16]</code>?</p>
<p>For instance, would either of the below calls to <code>api_func()</code> be safe?</p>
<pre><code>void api_func(const double matrix[4][4]);
// ...
{
typedef double Matrix[4][4];
double* array1 = new double[16];
double array2[16];
// ...
api_func(reinterpret_cast<Matrix&>(array1));
api_func(reinterpret_cast<Matrix&>(array2));
}
</code></pre>
|
[
{
"answer_id": 55660,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "sizeof n n double[4][4] double[16] sizeof(double[4]) = 4*sizeof(double)\n sizeof(double[4][4]) = 4*sizeof(double[4])\n sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
55,556 |
<p>I need to generate some passwords, I want to avoid characters that can be confused for each other. Is there a definitive list of characters I should avoid? my current list is</p>
<p>il10o8B3Evu![]{}</p>
<p>Are there any other pairs of characters that are easy to confuse? for special characters I was going to limit myself to those under the number keys, though I know that this differs depending on your keyboards nationality!</p>
<p>As a rider question, I would like my passwords to be 'wordlike'do you have a favoured algorithm for that?</p>
<p>Thanks :)</p>
|
[
{
"answer_id": 55634,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 7,
"selected": true,
"text": "!#%+23456789:=?@ABCDEFGHJKLMNPRS\nTUVWXYZabcdefghijkmnopqrstuvwxyz\n !\"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHJKLMNO\nPRSTUVWXYZ[\\]^_abcdefghijkmnopqrstuvwxyz{|}~\n"
},
{
"answer_id": 57452,
"author": "James B",
"author_id": 2951,
"author_profile": "https://Stackoverflow.com/users/2951",
"pm_score": 2,
"selected": false,
"text": "function generatePassword($syllables = 2, $use_prefix = true)\n{\n\n // Define function unless it is already exists\n if (!function_exists('arr'))\n {\n // This function returns random array element\n function arr(&$arr)\n {\n return $arr[rand(0, sizeof($arr)-1)];\n }\n }\n\n // Random prefixes\n $prefix = array('aero', 'anti', 'auto', 'bi', 'bio',\n 'cine', 'deca', 'demo', 'dyna', 'eco',\n 'ergo', 'geo', 'gyno', 'hypo', 'kilo',\n 'mega', 'tera', 'mini', 'nano', 'duo',\n 'an', 'arch', 'auto', 'be', 'co',\n 'counter', 'de', 'dis', 'ex', 'fore',\n 'in', 'infra', 'inter', 'mal', \n 'mis', 'neo', 'non', 'out', 'pan',\n 'post', 'pre', 'pseudo', 'semi',\n 'super', 'trans', 'twi', 'vice');\n\n // Random suffixes\n $suffix = array('dom', 'ity', 'ment', 'sion', 'ness',\n 'ence', 'er', 'ist', 'tion', 'or',\n 'ance', 'ive', 'en', 'ic', 'al',\n 'able', 'y', 'ous', 'ful', 'less',\n 'ise', 'ize', 'ate', 'ify', 'fy', 'ly'); \n\n // Vowel sounds \n $vowels = array('a', 'o', 'e', 'i', 'y', 'u', 'ou', 'oo', 'ae', 'ea', 'ie'); \n\n // Consonants \n $consonants = array('w', 'r', 't', 'p', 's', 'd', 'f', 'g', 'h', 'j', \n 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'qu');\n\n $password = $use_prefix?arr($prefix):'';\n $password_suffix = arr($suffix);\n\n for($i=0; $i<$syllables; $i++)\n {\n // selecting random consonant\n $doubles = array('n', 'm', 't', 's');\n $c = arr($consonants);\n if (in_array($c, $doubles)&&($i!=0)) { // maybe double it\n if (rand(0, 2) == 1) // 33% probability\n $c .= $c;\n }\n $password .= $c;\n //\n\n // selecting random vowel\n $password .= arr($vowels);\n\n if ($i == $syllables - 1) // if suffix begin with vovel\n if (in_array($password_suffix[0], $vowels)) // add one more consonant \n $password .= arr($consonants);\n\n }\n\n // selecting random suffix\n $password .= $password_suffix;\n\n return $password;\n}\n"
},
{
"answer_id": 64836,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 2,
"selected": false,
"text": "Es4tU$sA6\nwH@cY8Go2\n"
},
{
"answer_id": 9651123,
"author": "Anonym",
"author_id": 1261653,
"author_profile": "https://Stackoverflow.com/users/1261653",
"pm_score": 1,
"selected": false,
"text": "function random_readable_pwd($length=12){\n // special characters\n $sym=\"!\\\"§$%&/()={[]}\\,.-_:;@>|\";\n\n // read words from text file to array\n $filename=\"special.txt\";\n if (!file_exists($filename)) { die('File \"'.$filename.'\" is not exists!'); }\n $lines = file($filename);\n foreach ($lines as $line_num => $line) {\n $line=substr($line, 0, -2);\n $words[].=$line;\n }\n\n // Add words while password is smaller than the given length\n $pwd = '';\n $ran_date=date(\"s\");\n while (strlen($pwd) < $length){\n $r = mt_rand(0, count($words)-1);\n // randomly upercare word but not all in one time\n if ($ran_date % 3 == 0) $words[$r]=ucwords($words[$r]);\n $pwd .= $words[$r];\n //randomly add symbol\n if ($ran_date % 2 == 0) $pwd .= $sym{mt_rand(0,strlen($sym))};\n $ran_date++;\n }\n\n // append a number at the end if length > 2 and\n // reduce the password size to $length\n $num = mt_rand(1, 99);\n if ($length > 2){\n $pwd = substr($pwd,0,$length-strlen($num)).$num;\n } else { \n $pwd = substr($pwd, 0, $length);\n }\n\n return $pwd;\n\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552/"
] |
55,572 |
<p>I've only recently started working with asp.net and c#. Is there a standard practice set of web.config settings for a live final website? There seem to be a ton of options available and I'm looking to streamline performance, close possible security holes and other unnecessary options. </p>
|
[
{
"answer_id": 55595,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433/"
] |
55,574 |
<p>As it stands now, I'm a Java and C# developer. The more and more I look at Ruby on Rails, the more I really want to learn it. </p>
<p>What have you found to be the best route to learn RoR? Would it be easier to develop on Windows, or should I just run a virtual machine with Linux? </p>
<p>Is there an IDE that can match the robustness of Visual Studio? Any programs to develop that give a good overhead of what to do? Any good books? </p>
<p>Seriously, any tips/tricks/rants would be awesome.</p>
|
[
{
"answer_id": 1268056,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "* Agile development with Rails (book)\n* Railscasts - very useful, always learn something new.\n* And of course the RoR API\n"
},
{
"answer_id": 3225899,
"author": "Marc Bollinger",
"author_id": 12866,
"author_profile": "https://Stackoverflow.com/users/12866",
"pm_score": 2,
"selected": false,
"text": ":things"
},
{
"answer_id": 3439432,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "attr_accessor :attr1, :attr2, :attr3"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] |
55,577 |
<p>I want to test the web pages I create in all the modern versions of Internet Explorer (6, 7 and 8 beta) but I work mainly on a Mac and often don't have direct access to a PC.</p>
|
[
{
"answer_id": 55578,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": true,
"text": "/Applications/Q.app/Contents/MacOS/qemu-img convert -O raw -f vpc \"input.vhd\" temp.bin\nVBoxManage convertdd temp.bin \"output.vdi\"\nrm temp.bin\nmv \"output.vdi\" ~/Library/VirtualBox/VDI/\nVBoxManage modifyvdi \"output.vdi\" compact\n /Applications/Q.app/Contents/MacOS/qemu-img convert -O vmdk -f vpc \"input.vhd\" \"output.vmdk\"\nmv \"output.vmdk\" ~/Documents/Virtual\\ Machines.localized/\n"
},
{
"answer_id": 9440667,
"author": "chadoh",
"author_id": 249801,
"author_profile": "https://Stackoverflow.com/users/249801",
"pm_score": 1,
"selected": false,
"text": "curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"7\" bash\n curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"8\" bash\n curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"9\" bash\n curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | bash\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
] |
55,594 |
<p>When developing (works fine live) the pages for our website don't pick up the correct CSS until the user has authenticated (logged on).</p>
<p>So the Logon and Logoff forms look bad, but once inside the site, the CSS works again.</p>
<p>I'm guessing it's some kind of authentication issue? Haven't really looked into it too much because it's only when working on dev so not a huge issue, but would be nice to know how to fix it.</p>
|
[
{
"answer_id": 417692,
"author": "Jason",
"author_id": 38398,
"author_profile": "https://Stackoverflow.com/users/38398",
"pm_score": 4,
"selected": false,
"text": "<configuration>\n <system.web>\n // system.web configuration settings.\n </system.web>\n <location path=\"App_Themes/Default/YourFile.css\">\n <system.web>\n <authorization>\n <allow users=\"*\"/>\n </authorization>\n </system.web>\n </location>\n</configuration>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] |
55,607 |
<p>What is the best way to use multiple EVAL fields in a GridView ItemTemplate?</p>
<p>Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.</p>
|
[
{
"answer_id": 55629,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 3,
"selected": false,
"text": "<%# Eval(\"Name1\", \"{0} - \")%> <%#Eval(\"Name2\")%>\n <%#Eval(\"Name1\") & \" - \" & Eval(\"Name2\")%>\n <%# \"First Name - \" & Eval(\"Name1\") & \", Last Name - \" & Eval(\"Name2\")%> \n"
},
{
"answer_id": 55681,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 7,
"selected": true,
"text": "<%# String.Format(\"{0} - {1}\", Eval(\"Name1\"), Eval(\"Name2\")) %>\n"
},
{
"answer_id": 36522821,
"author": "Durgesh Pandey",
"author_id": 5030579,
"author_profile": "https://Stackoverflow.com/users/5030579",
"pm_score": 2,
"selected": false,
"text": "<asp:Label ID=\"lblName\" runat=\"server\" Text='<%#Eval(\"FirstName\").ToString() +\", \"+ Eval(\"LastName\").ToString() %>'></asp:Label>\n <%#Eval(\"FirstName\").ToString() +\", \"+ Eval(\"LastName\").ToString() %>\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] |
55,611 |
<p>To make a JavaScript class with a public method I'd do something like:</p>
<pre><code>function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
</code></pre>
<p>That way users of my class can:</p>
<pre><code>var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
</code></pre>
<p>How do I create a private method that can be called by the <code>buy_food</code> and <code>use_restroom</code> methods but not externally by users of the class?</p>
<p>In other words, I want my method implementation to be able to do:</p>
<pre><code>Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
</code></pre>
<p>But this shouldn't work:</p>
<pre><code>var r = new Restaurant();
r.private_stuff();
</code></pre>
<p>How do I define <code>private_stuff</code> as a private method so both of these hold true?</p>
<p>I've read <a href="http://javascript.crockford.com/private.html" rel="noreferrer">Doug Crockford's writeup</a> a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.</p>
|
[
{
"answer_id": 55637,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 10,
"selected": true,
"text": "function Restaurant() {\n var myPrivateVar;\n\n var private_stuff = function() { // Only visible inside Restaurant()\n myPrivateVar = \"I can set this here!\";\n }\n\n this.use_restroom = function() { // use_restroom is visible to all\n private_stuff();\n }\n\n this.buy_food = function() { // buy_food is visible to all\n private_stuff();\n }\n}\n"
},
{
"answer_id": 55638,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": false,
"text": "function Restaurant() {\n}\n\nRestaurant.prototype = (function() {\n var private_stuff = function() {\n // Private code here\n };\n\n return {\n\n constructor:Restaurant,\n\n use_restroom:function() {\n private_stuff();\n }\n\n };\n})();\n\nvar r = new Restaurant();\n\n// This will work:\nr.use_restroom();\n\n// This will cause an error:\nr.private_stuff();\n"
},
{
"answer_id": 55696,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "var MYLIB = function() { \n var aPrivateProperty = true;\n var aPrivateMethod = function() {\n // some code here...\n };\n return {\n aPublicMethod : function() {\n aPrivateMethod(); // okay\n // some code here...\n },\n aPublicProperty : true\n }; \n}();\n\nMYLIB.aPrivateMethod() // not okay\nMYLIB.aPublicMethod() // okay\n"
},
{
"answer_id": 148219,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 2,
"selected": false,
"text": "function MyObject(arg1, arg2, ...) {\n //constructor code using constructor arguments...\n //create/access public variables as \n // this.var1 = foo;\n\n //private variables\n\n var v1;\n var v2;\n\n //private functions\n function privateOne() {\n }\n\n function privateTwon() {\n }\n\n //public functions\n\n MyObject.prototype.publicOne = function () {\n };\n\n MyObject.prototype.publicTwo = function () {\n };\n}\n"
},
{
"answer_id": 1361654,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "var Car = function() {\n}\n\nCar.prototype = (function() {\n var hotWire = function() {\n // Private code *with* access to public properties through 'this'\n alert( this.drive() ); // Alerts 'Vroom!'\n }\n\n return {\n steal: function() {\n hotWire.call( this ); // Call a private method\n },\n drive: function() {\n return 'Vroom!';\n }\n };\n})();\n\nvar getAwayVechile = new Car();\n\nhotWire(); // Not allowed\ngetAwayVechile.hotWire(); // Not allowed\ngetAwayVechile.steal(); // Alerts 'Vroom!'\n"
},
{
"answer_id": 5703989,
"author": "David",
"author_id": 713524,
"author_profile": "https://Stackoverflow.com/users/713524",
"pm_score": 2,
"selected": false,
"text": "var TestClass = function( ) {\n\n var privateProperty = 42;\n\n function privateMethod( ) {\n alert( \"privateMethod, \" + privateProperty );\n }\n\n this.public = {\n constructor: TestClass,\n\n publicProperty: 88,\n publicMethod: function( ) {\n alert( \"publicMethod\" );\n privateMethod( );\n }\n };\n};\nTestClass.prototype = new TestClass( ).public;\n\n\nvar myTestClass = new TestClass( );\n\nalert( myTestClass.publicProperty );\nmyTestClass.publicMethod( );\n\nalert( myTestClass.privateMethod || \"no privateMethod\" );\n"
},
{
"answer_id": 9288441,
"author": "Sarath",
"author_id": 353241,
"author_profile": "https://Stackoverflow.com/users/353241",
"pm_score": 4,
"selected": false,
"text": "function Employee(id, name) { //Constructor\n //Public member variables\n this.id = id;\n this.name = name;\n //Private member variables\n var fName;\n var lName;\n var that = this;\n //By convention, we create a private variable 'that'. This is used to \n //make the object available to the private methods. \n\n //Private function\n function setFName(pfname) {\n fName = pfname;\n alert('setFName called');\n }\n //Privileged function\n this.setLName = function (plName, pfname) {\n lName = plName; //Has access to private variables\n setFName(pfname); //Has access to private function\n alert('setLName called ' + this.id); //Has access to member variables\n }\n //Another privileged member has access to both member variables and private variables\n //Note access of this.dataOfBirth created by public member setDateOfBirth\n this.toString = function () {\n return 'toString called ' + this.id + ' ' + this.name + ' ' + fName + ' ' + lName + ' ' + this.dataOfBirth; \n }\n}\n//Public function has access to member variable and can create on too but does not have access to private variable\nEmployee.prototype.setDateOfBirth = function (dob) {\n alert('setDateOfBirth called ' + this.id);\n this.dataOfBirth = dob; //Creates new public member note this is accessed by toString\n //alert(fName); //Does not have access to private member\n}\n$(document).ready()\n{\n var employee = new Employee(5, 'Shyam'); //Create a new object and initialize it with constructor\n employee.setLName('Bhaskar', 'Ram'); //Call privileged function\n employee.setDateOfBirth('1/1/2000'); //Call public function\n employee.id = 9; //Set up member value\n //employee.setFName('Ram'); //can not call Private Privileged method\n alert(employee.toString()); //See the changed object\n\n}\n"
},
{
"answer_id": 13327997,
"author": "mark",
"author_id": 1753943,
"author_profile": "https://Stackoverflow.com/users/1753943",
"pm_score": 0,
"selected": false,
"text": "Function Foo( ) {\n this.bar = 0; \n var foobar=function( ) {\n alert(this.bar);\n }\n} \n Function Foo( ) {\n this.bar = 0;\n that = this; \n var foobar=function( ) {\n alert(that.bar);\n }\n}\n"
},
{
"answer_id": 15721313,
"author": "Andreas Dyballa",
"author_id": 1636136,
"author_profile": "https://Stackoverflow.com/users/1636136",
"pm_score": 0,
"selected": false,
"text": "ctx.test = GD.Fabric.open('test', GD.Test.prototype, ctx, _); // is a private object\n GD.Fabric.openPrivacy = function(func, clss, ctx, _) {\n return function() {\n ctx._ = _;\n var res = clss[func].apply(ctx, arguments);\n ctx._ = null;\n return res;\n };\n};\n"
},
{
"answer_id": 16605660,
"author": "Flex Elektro Deimling",
"author_id": 530335,
"author_profile": "https://Stackoverflow.com/users/530335",
"pm_score": 0,
"selected": false,
"text": "var Restaurant = (function(){\n var private_buy_food = function(that){\n that.data.soldFood = true;\n }\n var private_take_a_shit = function(){\n this.data.isdirty = true; \n }\n // New Closure\n function restaurant()\n {\n this.data = {\n isdirty : false,\n soldFood: false,\n };\n }\n\n restaurant.prototype.buy_food = function()\n {\n private_buy_food(this);\n }\n restaurant.prototype.use_restroom = function()\n {\n private_take_a_shit.call(this);\n }\n return restaurant;\n})()\n\n// TEST:\n\nvar McDonalds = new Restaurant();\nMcDonalds.buy_food();\nMcDonalds.use_restroom();\nconsole.log(McDonalds);\nconsole.log(McDonalds.__proto__);\n"
},
{
"answer_id": 18222581,
"author": "iimos",
"author_id": 502860,
"author_profile": "https://Stackoverflow.com/users/502860",
"pm_score": 4,
"selected": false,
"text": "function () {\n\n}\n function () {\n var name,\n secretSkills = {\n pizza: function () { return new Pizza() },\n sushi: function () { return new Sushi() }\n }\n\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return name in secretSkills ? secretSkills[name]() : null\n }\n}\n var Restaurant = (function () {\n // Restaurant definition\n return Restaurant\n})()\n var Restaurant = (function () {\n var name,\n secretSkills = {\n pizza: function () { return new Pizza() },\n sushi: function () { return new Sushi() }\n }\n\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return name in secretSkills ? secretSkills[name]() : null\n }\n return Restaurant\n})()\n // Abstract class\nfunction AbstractRestaurant(skills) {\n var name\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return skills && name in skills ? skills[name]() : null\n }\n return Restaurant\n}\n\n// Concrete classes\nSushiRestaurant = AbstractRestaurant({ \n sushi: function() { return new Sushi() } \n})\n\nPizzaRestaurant = AbstractRestaurant({ \n pizza: function() { return new Pizza() } \n})\n\nvar r1 = new SushiRestaurant('Yo! Sushi'),\n r2 = new PizzaRestaurant('Dominos Pizza')\n\nr1.getFood('sushi')\nr2.getFood('pizza')\n"
},
{
"answer_id": 18239876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": ";( function class_Restaurant( namespace )\n{\n 'use strict';\n\n if( namespace[ \"Restaurant\" ] ) return // protect against double inclusions\n\n namespace.Restaurant = Restaurant\n var Static = TidBits.OoJs.setupClass( namespace, \"Restaurant\" )\n\n\n // constructor\n //\n function Restaurant()\n {\n this.toilets = 3\n\n this.Private( private_stuff )\n\n return this.Public( buy_food, use_restroom )\n }\n\n function private_stuff(){ console.log( \"There are\", this.toilets, \"toilets available\") }\n\n function buy_food (){ return \"food\" }\n function use_restroom (){ this.private_stuff() }\n\n})( window )\n\n\nvar chinese = new Restaurant\n\nconsole.log( chinese.buy_food() ); // output: food\nconsole.log( chinese.use_restroom() ); // output: There are 3 toilets available\nconsole.log( chinese.toilets ); // output: undefined\nconsole.log( chinese.private_stuff() ); // output: undefined\n\n// and throws: TypeError: Object #<Restaurant> has no method 'private_stuff'\n"
},
{
"answer_id": 19695554,
"author": "Evan Leis",
"author_id": 981337,
"author_profile": "https://Stackoverflow.com/users/981337",
"pm_score": 2,
"selected": false,
"text": "var Restaurant = (function() {\n\n var _id = 0;\n var privateVars = [];\n\n function Restaurant(name) {\n this.id = ++_id;\n this.name = name;\n privateVars[this.id] = {\n cooked: []\n };\n }\n\n Restaurant.prototype.cook = function (food) {\n privateVars[this.id].cooked.push(food);\n }\n\n return Restaurant;\n\n})();\n privateVars[this.id].cooked"
},
{
"answer_id": 20500648,
"author": "snowkid",
"author_id": 3087829,
"author_profile": "https://Stackoverflow.com/users/3087829",
"pm_score": 0,
"selected": false,
"text": "Class({ \n Namespace:ABC, \n Name:\"ClassL2\", \n Bases:[ABC.ClassTop], \n Private:{ \n m_var:2 \n }, \n Protected:{ \n proval:2, \n fight:Property(function(){ \n this.m_var--; \n console.log(\"ClassL2::fight (m_var)\" +this.m_var); \n },[Property.Type.Virtual]) \n }, \n Public:{ \n Fight:function(){ \n console.log(\"ClassL2::Fight (m_var)\"+this.m_var); \n this.fight(); \n } \n } \n}); \n"
},
{
"answer_id": 21167136,
"author": "Trem",
"author_id": 732236,
"author_profile": "https://Stackoverflow.com/users/732236",
"pm_score": 0,
"selected": false,
"text": "var MyObject = (function () {\n\n // Create the object\n function MyObject() {}\n\n // Add methods to the prototype\n MyObject.prototype = {\n\n // This is our public method\n public: function () {\n console.log('PUBLIC method has been called');\n },\n\n // This is our private method, using (_)\n _private: function () {\n console.log('PRIVATE method has been called');\n }\n }\n\n return protect(MyObject);\n\n})();\n\n// Create an instance of the object\nvar mo = new MyObject();\n\n// Call its methods\nmo.public(); // Pass\nmo._private(); // Fail\n"
},
{
"answer_id": 25172901,
"author": "Yves M.",
"author_id": 1480391,
"author_profile": "https://Stackoverflow.com/users/1480391",
"pm_score": 8,
"selected": false,
"text": "var MyObject = (function () {\n \n // Constructor\n function MyObject(foo) {\n this._foo = foo;\n }\n\n function privateFun(prefix) {\n return prefix + this._foo;\n }\n \n MyObject.prototype.publicFun = function () {\n return privateFun.call(this, \">>\");\n }\n \n return MyObject;\n\n}());\n var myObject = new MyObject(\"bar\");\nmyObject.publicFun(); // Returns \">>bar\"\nmyObject.privateFun(\">>\"); // ReferenceError: private is not defined\n this function MyObject(foo) {\n this._foo = foo;\n}\n \nfunction privateFun(prefix) {\n return prefix + this._foo;\n}\n\nMyObject.prototype.publicFun = function () {\n return privateFun.call(this, \">>\");\n}\n \nmodule.exports= MyObject;\n var MyObject = require(\"./MyObject\");\n \nvar myObject = new MyObject(\"bar\");\nmyObject.publicFun(); // Returns \">>bar\"\nmyObject.privateFun(\">>\"); // ReferenceError: private is not defined\n class MyObject {\n\n // Private field\n #foo;\n \n constructor(foo) {\n this.#foo = foo;\n }\n\n #privateFun(prefix) {\n return prefix + this.#foo;\n }\n \n publicFun() {\n return this.#privateFun(\">>\");\n }\n\n}\n # :: export default class MyObject {\n constructor (foo) {\n this._foo = foo;\n }\n\n publicFun () {\n return this::privateFun(\">>\");\n }\n}\n\nfunction privateFun (prefix) {\n return prefix + this._foo;\n}\n"
},
{
"answer_id": 25366378,
"author": "Fozi",
"author_id": 168683,
"author_profile": "https://Stackoverflow.com/users/168683",
"pm_score": 2,
"selected": false,
"text": "function Foo(x) {\n var y = 5;\n var bar = function() {\n return y * x;\n };\n\n this.public = function(z) {\n return bar() + x * z;\n };\n}\n eval(\"Foo = \" + Foo.toString().replace(\n /{/, \"{ this.eval = function(code) { return eval(code); }; \"\n));\n replace() new Foo() eval f = new Foo(99);\nf.eval(\"x\");\nf.eval(\"y\");\nf.eval(\"x = 8\");\n __private _protected"
},
{
"answer_id": 27396880,
"author": "low_rents",
"author_id": 3391783,
"author_profile": "https://Stackoverflow.com/users/3391783",
"pm_score": 2,
"selected": false,
"text": "var Person = (function () {\n\n //Immediately returns an anonymous function which builds our modules \n return function (name, location) {\n\n alert(\"createPerson called with \" + name);\n\n var localPrivateVar = name;\n\n var localPublicVar = \"A public variable\";\n\n var localPublicFunction = function () {\n alert(\"PUBLIC Func called, private var is :\" + localPrivateVar)\n };\n\n var localPrivateFunction = function () {\n alert(\"PRIVATE Func called \")\n };\n\n var setName = function (name) {\n\n localPrivateVar = name;\n\n }\n\n return {\n\n publicVar: localPublicVar,\n\n location: location,\n\n publicFunction: localPublicFunction,\n\n setName: setName\n\n }\n\n }\n})();\n\n\n//Request a Person instance - should print \"createPerson called with ben\"\nvar x = Person(\"ben\", \"germany\");\n\n//Request a Person instance - should print \"createPerson called with candide\"\nvar y = Person(\"candide\", \"belgium\");\n\n//Prints \"ben\"\nx.publicFunction();\n\n//Prints \"candide\"\ny.publicFunction();\n\n//Now call a public function which sets the value of a private variable in the x instance\nx.setName(\"Ben 2\");\n\n//Shouldn't have changed this : prints \"candide\"\ny.publicFunction();\n\n//Should have changed this : prints \"Ben 2\"\nx.publicFunction();\n"
},
{
"answer_id": 28190815,
"author": "Maxim Balaganskiy",
"author_id": 944182,
"author_profile": "https://Stackoverflow.com/users/944182",
"pm_score": 0,
"selected": false,
"text": "var obj = function(){\n var pr = \"private\";\n var prt = Object.getPrototypeOf(this);\n if(!prt.hasOwnProperty(\"showPrivate\")){\n prt.showPrivate = function(){\n console.log(pr);\n }\n } \n}\n\nvar i = new obj();\ni.showPrivate();\nconsole.log(i.hasOwnProperty(\"pr\"));\n"
},
{
"answer_id": 28279952,
"author": "James",
"author_id": 1185191,
"author_profile": "https://Stackoverflow.com/users/1185191",
"pm_score": 2,
"selected": false,
"text": "var MyClass = (function () {\n var secret = {}; // You can only getPriv() if you know this\n function MyClass() {\n var that = this, priv = {\n foo: 0 // ... and other private values\n };\n that.getPriv = function (proof) {\n return (proof === secret) && priv;\n };\n }\n MyClass.prototype.inc = function () {\n var priv = this.getPriv(secret);\n priv.foo += 1;\n return priv.foo;\n };\n return MyClass;\n}());\nvar x = new MyClass();\nx.inc(); // 1\nx.inc(); // 2\n priv getPriv() false secret"
},
{
"answer_id": 31042160,
"author": "Abdennour TOUMI",
"author_id": 747579,
"author_profile": "https://Stackoverflow.com/users/747579",
"pm_score": 2,
"selected": false,
"text": "window (function(w,nameSpacePrivate){\n w.Person=function(name){\n this.name=name; \n return this;\n };\n\n w.Person.prototype.profilePublic=function(){\n return nameSpacePrivate.profile.call(this);\n }; \n\n nameSpacePrivate.profile=function(){\n return 'My name is '+this.name;\n };\n\n})(window,{});\n var abdennour=new Person('Abdennour');\n abdennour.profilePublic();\n"
},
{
"answer_id": 37141668,
"author": "thegunmaster",
"author_id": 3080469,
"author_profile": "https://Stackoverflow.com/users/3080469",
"pm_score": 0,
"selected": false,
"text": "function calledPrivate(){\n var stack = new Error().stack.toString().split(\"\\n\");\n function getClass(line){\n var i = line.indexOf(\" \");\n var i2 = line.indexOf(\".\");\n return line.substring(i,i2);\n }\n return getClass(stack[2])==getClass(stack[3]);\n}\n\nclass Obj{\n privateMethode(){\n if(calledPrivate()){\n console.log(\"your code goes here\");\n }\n }\n publicMethode(){\n this.privateMethode();\n }\n}\n\nvar obj = new Obj();\nobj.publicMethode(); //logs \"your code goes here\"\nobj.privateMethode(); //does nothing\n"
},
{
"answer_id": 44423507,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 3,
"selected": false,
"text": "var myClass = (function() {\n // Private class properties go here\n\n var blueprint = function() {\n // Private instance properties go here\n ...\n };\n\n blueprint.prototype = { \n // Public class properties go here\n ...\n };\n\n return {\n // Public class properties go here\n create : function() { return new blueprint(); }\n ...\n };\n})();\n var Restaurant = function() {\n var totalfoodcount = 0; // Private class property\n var totalrestroomcount = 0; // Private class property\n \n var Restaurant = function(name){\n var foodcount = 0; // Private instance property\n var restroomcount = 0; // Private instance property\n \n this.name = name\n \n this.incrementFoodCount = function() {\n foodcount++;\n totalfoodcount++;\n this.printStatus();\n };\n this.incrementRestroomCount = function() {\n restroomcount++;\n totalrestroomcount++;\n this.printStatus();\n };\n this.getRestroomCount = function() {\n return restroomcount;\n },\n this.getFoodCount = function() {\n return foodcount;\n }\n };\n \n Restaurant.prototype = {\n name : '',\n buy_food : function(){\n this.incrementFoodCount();\n },\n use_restroom : function(){\n this.incrementRestroomCount();\n },\n getTotalRestroomCount : function() {\n return totalrestroomcount;\n },\n getTotalFoodCount : function() {\n return totalfoodcount;\n },\n printStatus : function() {\n document.body.innerHTML\n += '<h3>Buying food at '+this.name+'</h3>'\n + '<ul>' \n + '<li>Restroom count at ' + this.name + ' : '+ this.getRestroomCount() + '</li>'\n + '<li>Food count at ' + this.name + ' : ' + this.getFoodCount() + '</li>'\n + '<li>Total restroom count : '+ this.getTotalRestroomCount() + '</li>'\n + '<li>Total food count : '+ this.getTotalFoodCount() + '</li>'\n + '</ul>';\n }\n };\n\n return { // Singleton public properties\n create : function(name) {\n return new Restaurant(name);\n },\n printStatus : function() {\n document.body.innerHTML\n += '<hr />'\n + '<h3>Overview</h3>'\n + '<ul>' \n + '<li>Total restroom count : '+ Restaurant.prototype.getTotalRestroomCount() + '</li>'\n + '<li>Total food count : '+ Restaurant.prototype.getTotalFoodCount() + '</li>'\n + '</ul>'\n + '<hr />';\n }\n };\n}();\n\nvar Wendys = Restaurant.create(\"Wendy's\");\nvar McDonalds = Restaurant.create(\"McDonald's\");\nvar KFC = Restaurant.create(\"KFC\");\nvar BurgerKing = Restaurant.create(\"Burger King\");\n\nRestaurant.printStatus();\n\nWendys.buy_food();\nWendys.use_restroom();\nKFC.use_restroom();\nKFC.use_restroom();\nWendys.use_restroom();\nMcDonalds.buy_food();\nBurgerKing.buy_food();\n\nRestaurant.printStatus();\n\nBurgerKing.buy_food();\nWendys.use_restroom();\nMcDonalds.buy_food();\nKFC.buy_food();\nWendys.buy_food();\nBurgerKing.buy_food();\nMcDonalds.buy_food();\n\nRestaurant.printStatus();"
},
{
"answer_id": 48833952,
"author": "rich remer",
"author_id": 1078314,
"author_profile": "https://Stackoverflow.com/users/1078314",
"pm_score": 1,
"selected": false,
"text": "WeakMap const data = new WeakMap();\n\nfunction Foo(value) {\n data.set(this, {value});\n}\n\n// public method accessing private value\nFoo.prototype.accessValue = function() {\n return data.get(this).value;\n}\n\n// private 'method' accessing private value\nfunction accessValue(foo) {\n return data.get(foo).value;\n}\n\nexport {Foo};\n"
},
{
"answer_id": 51470058,
"author": "prograhammer",
"author_id": 1110941,
"author_profile": "https://Stackoverflow.com/users/1110941",
"pm_score": 3,
"selected": false,
"text": "private define([\n 'tooltip'\n ],\n function(\n tooltip\n ){\n\n function MyTooltip() {\n // Later, if needed, we can remove the underscore on some\n // of these (make public) and allow clients of our class\n // to set them.\n this._selector = \"#my-tooltip\"\n this._template = 'Hello from inside my tooltip!';\n this._initTooltip();\n }\n\n MyTooltip.prototype = {\n constructor: MyTooltip,\n\n _initTooltip: function () {\n new tooltip.tooltip(this._selector, {\n content: this._template,\n closeOnClick: true,\n closeButton: true\n });\n }\n }\n\n return {\n init: function init() {\n new MyTooltip(); // <-- Our constructor adds our tooltip to the DOM so not much we need to do after instantiation.\n }\n\n // You could instead return a new instantiation, \n // if later you do more with this class.\n /* \n create: function create() {\n return new MyTooltip();\n }\n */\n }\n });\n"
},
{
"answer_id": 59474509,
"author": "D-Marc",
"author_id": 3822526,
"author_profile": "https://Stackoverflow.com/users/3822526",
"pm_score": 4,
"selected": false,
"text": "# class ClassWithPrivateMethod {\n #privateMethod() {\n return 'hello world';\n }\n\n getPrivateMessage() {\n return #privateMethod();\n }\n}\n"
},
{
"answer_id": 63722178,
"author": "Daniel Shlomo",
"author_id": 1510406,
"author_profile": "https://Stackoverflow.com/users/1510406",
"pm_score": 0,
"selected": false,
"text": "function Class(cb) {\n const self = {};\n\n const constructor = (fn) => {\n func = fn; \n };\n\n const addPrivate = (fnName, obj) => {\n self[fnName] = obj;\n }\n\n const addPublic = (fnName, obj) => {\n this[fnName] = obj;\n self[fnName] = obj;\n func.prototype[fnName] = obj;\n }\n \n cb(constructor, addPrivate, addPublic, self);\n return func;\n}\n\nconst test = new Class((constructor, private, public, self) => {\n constructor(function (test) {\n console.log(test)\n });\n public('test', 'yay');\n private('qwe', 'nay');\n private('no', () => {\n return 'hello'\n })\n public('asd', () => {\n return 'this is public'\n })\n public('hello', () => {\n return self.qwe + self.no() + self.asd()\n })\n})\nconst asd = new test('qweqwe');\nconsole.log(asd.hello());"
},
{
"answer_id": 64504570,
"author": "t_dom93",
"author_id": 6774916,
"author_profile": "https://Stackoverflow.com/users/6774916",
"pm_score": 4,
"selected": false,
"text": "# class Restaurant {\n\n // private method\n #private_stuff() {\n console.log(\"private stuff\");\n }\n\n // public method\n buy_food() {\n this.#private_stuff();\n }\n\n};\n\nconst restaurant = new Restaurant();\nrestaurant.buy_food(); // \"private stuff\";\nrestaurant.private_stuff(); // Uncaught TypeError: restaurant.private_stuff is not a function\n"
},
{
"answer_id": 65552423,
"author": "Redu",
"author_id": 4543207,
"author_profile": "https://Stackoverflow.com/users/4543207",
"pm_score": 0,
"selected": false,
"text": "Object.create() Restaurant function restaurantFactory(name,menu){\n\n function Restaurant(name){\n this.name = name;\n }\n\n function prototypeFactory(menu){\n // This is a private function\n function calculateBill(item){\n return menu[item] || 0;\n }\n // This is the prototype to be\n return { constructor: Restaurant\n , askBill : function(...items){\n var cost = items.reduce((total,item) => total + calculateBill(item) ,0)\n return \"Thank you for dining at \" + this.name + \". Total is: \" + cost + \"\\n\"\n }\n , callWaiter : function(){\n return \"I have just called the waiter at \" + this.name + \"\\n\";\n }\n }\n }\n\n Restaurant.prototype = prototypeFactory(menu);\n\n return new Restaurant(name,menu);\n}\n\nvar menu = { water: 1\n , coke : 2\n , beer : 3\n , beef : 15\n , rice : 2\n },\n name = \"Silver Scooop\",\n rest = restaurantFactory(name,menu);\n\nconsole.log(rest.callWaiter());\nconsole.log(rest.askBill(\"beer\", \"beef\")); menu name Object.create() var rest = Object.create(prototypeFactory(menu)) rest rest.name = name"
},
{
"answer_id": 67235368,
"author": "yorg",
"author_id": 3225970,
"author_profile": "https://Stackoverflow.com/users/3225970",
"pm_score": 0,
"selected": false,
"text": "const PublicClass=function(priv,pub,ro){\n let _priv=new PrivateClass(priv,pub,ro);\n ['publicMethod'].forEach(k=>this[k]=(...args)=>_priv[k](...args));\n ['publicVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n ['readOnlyVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));\n};\n\nclass PrivateClass{\n constructor(priv,pub,ro){\n this.privateVar=priv;\n this.publicVar=pub;\n this.readOnlyVar=ro;\n }\n publicMethod(arg1,arg2){\n return this.privateMethod(arg1,arg2);\n }\n privateMethod(arg1,arg2){\n return arg1+''+arg2;\n }\n}\n// in node;\nmodule.exports=PublicClass;\n// in browser;\nconst PublicClass=(function(){\n // code here\n return PublicClass;\n})();\n var PublicClass=function(priv,pub,ro){\n var scope=this;\n var _priv=new PrivateClass(priv,pub,ro);\n ['publicMethod'].forEach(function(k){\n scope[k]=function(){return _priv[k].apply(_priv,arguments)};\n });\n ['publicVar'].forEach(function(k){\n Object.defineProperty(scope,k,{get:function(){return _priv[k]},set:function(v){_priv[k]=v}});\n });\n ['readOnlyVar'].forEach(function(k){\n Object.defineProperty(scope,k,{get:function(){return _priv[k]}});\n });\n};\n\nvar PrivateClass=function(priv,pub,ro){\n this.privateVar=priv;\n this.publicVar=pub;\n this.readOnlyVar=ro;\n};\nPrivateClass.prototype.publicMethod=function(arg1,arg2){\n return this.privateMethod(arg1,arg2);\n};\nPrivateClass.prototype.privateMethod=function(arg1,arg2){\n return arg1+''+arg2;\n};\n const AbstractPublicClass=function(instanciate,inherit){\n let _priv=instanciate();\n inherit.methods?.forEach(k=>this[k]=(...args)=>_priv[k](...args));\n inherit.vars?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n inherit.readonly?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));\n};\n\nAbstractPublicClass.static=function(_pub,_priv,inherit){\n inherit.methods?.forEach(k=>_pub[k]=(...args)=>_priv[k](...args));\n inherit.vars?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n inherit.readonly?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k]}));\n};\n // PrivateClass ...\nPrivateClass.staticVar='zog';\nPrivateClass.staticMethod=function(){return 'hello '+this.staticVar;};\n\n\nconst PublicClass=function(priv,pub,ro){\n AbstractPublicClass.apply(this,[()=>new PrivateClass(priv,pub,ro),{\n methods:['publicMethod'],\n vars:['publicVar'],\n readonly:['readOnlyVar']\n }]);\n};\nAbstractPublicClass.static(PublicClass,PrivateClass,{\n methods:['staticMethod'],\n vars:['staticVar']\n});\n"
},
{
"answer_id": 68978023,
"author": "denik1981",
"author_id": 13578650,
"author_profile": "https://Stackoverflow.com/users/13578650",
"pm_score": 1,
"selected": false,
"text": "((self) => ({\n pubProp: self.pubProp,\n // More public properties to export HERE\n // ...\n pubMethod: self.pubMethod.bind(self)\n // More public mehods to export HERE\n // Be sure bind each of them to self!!!\n // ... \n }))(self);\n 'use strict';\n\nclass MyClass {\n constructor(pubProp) {\n let self = this;\n self.pubProp = pubProp;\n self.privProp = \"I'm a private property!\";\n return ((self) => ({\n pubProp: self.pubProp,\n // More public properties to export HERE\n // ...\n pubMethod: self.pubMethod.bind(self)\n // More public mehods to export HERE\n // Be sure to bind each of them to self!!!\n // ... \n }))(self);\n }\n\n pubMethod() {\n console.log(\"I'm a public method!\");\n console.log(this.pubProp);\n\n return this.privMethod();\n }\n\n privMethod() {\n console.log(\"I'm a private method!\");\n return this.privProp\n }\n}\n\nconst myObj = new MyClass(\"I'm a public property!\");\nconsole.log(\"***DUMPING MY NEW INSTANCE***\");\nconsole.dir(myObj);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PUBLIC PROPERTIES***\");\nconsole.log(myObj.pubProp);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PRIVATE PROPERTIES***\");\nconsole.log(myObj.privProp);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PUBLIC METHODS***\");\nconsole.log(\"1. pubMethod access pubProp \");\nconsole.log(\"2. pubMethod calls privMethod\");\nconsole.log(\"3. privMethod access privProp\");\nconsole.log(\"\")\nconsole.log(myObj.pubMethod());\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PRIVATE METHODS***\");\nconsole.log(myObj.privMethod());"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284/"
] |
55,612 |
<p>This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this?</p>
|
[
{
"answer_id": 55624,
"author": "Robby Slaughter",
"author_id": 1854,
"author_profile": "https://Stackoverflow.com/users/1854",
"pm_score": 8,
"selected": true,
"text": ":first-letter :first-line :first-word"
},
{
"answer_id": 55627,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<div id=\"content\">\n <p><strong>First Word</strong> rest of paragraph.</p>\n</div>\n #content p strong\n{\n font-size: 14pt;\n}\n"
},
{
"answer_id": 57051,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 5,
"selected": false,
"text": "<span class=\"first-word\">"
},
{
"answer_id": 3139488,
"author": "Jon Hadley",
"author_id": 161525,
"author_profile": "https://Stackoverflow.com/users/161525",
"pm_score": 5,
"selected": false,
"text": "$('#links a').each(function(){\n var me = $(this);\n me.html( me.text().replace(/(^\\w+)/,'<strong>$1</strong>') );\n });\n $('#links a').each(function(){\n var me = $(this)\n , t = me.text().split(' ');\n me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );\n });\n"
},
{
"answer_id": 8243675,
"author": "Motekye Guakein",
"author_id": 1062088,
"author_profile": "https://Stackoverflow.com/users/1062088",
"pm_score": 3,
"selected": false,
"text": "display:block;\nWidth:40-100px; /* just enough for one word, depends on font size */\nOverflow:visible; /* so longer words don't get clipped.*/\nfloat:left; /* so it will flow with the paragraph. */\nposition:relative; /* for typeset adjustments. */\n"
},
{
"answer_id": 14968908,
"author": "user1171848",
"author_id": 1171848,
"author_profile": "https://Stackoverflow.com/users/1171848",
"pm_score": 2,
"selected": false,
"text": "<span> $(function() {\n $('#content p').each(function() {\n var text = this.innerHTML;\n var firstSpaceIndex = text.indexOf(\" \");\n if (firstSpaceIndex > 0) {\n var substrBefore = text.substring(0,firstSpaceIndex);\n var substrAfter = text.substring(firstSpaceIndex, text.length)\n var newText = '<span class=\"firstWord\">' + substrBefore + '</span>' + substrAfter;\n this.innerHTML = newText;\n } else {\n this.innerHTML = '<span class=\"firstWord\">' + text + '</span>';\n }\n });\n});\n .firstWord"
},
{
"answer_id": 29242398,
"author": "Simon Hayter",
"author_id": 1892635,
"author_profile": "https://Stackoverflow.com/users/1892635",
"pm_score": 4,
"selected": false,
"text": ":first-word :last-word :first-child :first-of-type :only-child :last-child :last-of-type :only-of-type :nth-child :nth-of-type :nth-last-child :nth-last-of-type ::first-letter ::first-line ::first-word ::last-letter ::last-line ::last-word ::nth-letter ::nth-line ::nth-word ::nth-last-letter ::nth-last-line ::nth-last-word"
},
{
"answer_id": 40359849,
"author": "Ashique",
"author_id": 7047794,
"author_profile": "https://Stackoverflow.com/users/7047794",
"pm_score": -1,
"selected": false,
"text": "<p><span>Hello</span>My Name Is Dot</p"
},
{
"answer_id": 64837372,
"author": "Noelia García",
"author_id": 14639208,
"author_profile": "https://Stackoverflow.com/users/14639208",
"pm_score": 1,
"selected": false,
"text": "TEXT A <b>text b</b>\n\n<h1>text b</h1>\n\n<style>\n h1 { /* the css style */}\n h1:before {content:\"text A (p.e.first word) with different style\"; \n display:\"inline\";/* the different css style */}\n</style>\n"
},
{
"answer_id": 69404852,
"author": "M K",
"author_id": 16383579,
"author_profile": "https://Stackoverflow.com/users/16383579",
"pm_score": 0,
"selected": false,
"text": "p::first-letter {\n font-weight: bold;\n color: red;\n}\n"
},
{
"answer_id": 71456785,
"author": "Schäfer",
"author_id": 9484755,
"author_profile": "https://Stackoverflow.com/users/9484755",
"pm_score": 0,
"selected": false,
"text": "let text = document.querySelector('.menu_text');\nconst words = menu_text.innerHTML.toString().split(' ');\ntext.innerText = words[0];\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204/"
] |
55,633 |
<p>WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a <a href="http://getfirebug.com/wiki/index.php/Console_API" rel="noreferrer">console documentation for Firebug</a>, but where can I find the console documentation for Safari/WebKit?</p>
|
[
{
"answer_id": 55653,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": true,
"text": "console.log() console.error() console.warn() console.info() console.count() console.debug() console.profileEnd() console.trace() console.dir() console.dirxml() console.assert() console.time() console.profile() console.timeEnd() console.group() console.groupEnd()"
},
{
"answer_id": 4698391,
"author": "Kerrick",
"author_id": 126329,
"author_profile": "https://Stackoverflow.com/users/126329",
"pm_score": 4,
"selected": false,
"text": "console.__proto__"
},
{
"answer_id": 6022331,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": false,
"text": "console.dir(console)\n"
},
{
"answer_id": 11050357,
"author": "arri",
"author_id": 194536,
"author_profile": "https://Stackoverflow.com/users/194536",
"pm_score": 0,
"selected": false,
"text": "> for(o in console) console.dir(o)\n _commandLineAPI\n log\n warn\n …\n > console.dir(_commandLineAPI)\n CommandLineAPI\n $0: \"—\"\n $1: \"—\"\n $2: \"—\"\n $3: \"—\"\n $4: \"—\"\n $$: bound: function () {\n $x: bound: function (xpath, context) {\n clear: bound: function () {\n copy: bound: function (object) {\n dir: bound: function () {\n dirxml: bound: function () {\n inspect: bound: function (object) {\n keys: bound: function (object) {\n monitorEvents: bound: function (object, types) {\n profile: bound: function () {\n profileEnd: bound: function () {\n unmonitorEvents: bound: function (object, types) {\n values: bound: function (object) {\n __proto__: CommandLineAPI\n"
},
{
"answer_id": 48357615,
"author": "Laimonas",
"author_id": 1790707,
"author_profile": "https://Stackoverflow.com/users/1790707",
"pm_score": 0,
"selected": false,
"text": "<article id=\"contents\" tabindex=\"0\" role=\"main\" class=\"isShowingTOC\">\n <a id=\"top\" name=\"top\"></a>\n <a id=\"INDEX\" href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/index.html\" style=\"display:none;\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_9";return this.s_oc?this.s_oc(e):true\"></a>\n \n <a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW1\" title=\"The Console\"></a><h1 id=\"pageTitle\">The Console</h1><p>The console offers a way to inspect and debug your webpages. Think of it as the Terminal of your web content. The console has access to the DOM and JavaScript of the open page. Use the console as a tool to modify your web content via interactive commands and as a teaching aid to expand your knowledge of JavaScript. Because an object’s methods and properties autocomplete as you type, you can see all available functions that are valid in Safari.</p><p>For example, open the console and type <code>$$(‘p’)[1]</code>. (<code>$$</code> is shorthand for <code>document.querySelectorAll</code>—see more shorthand commands in <span class=\"content_text\"><a href=\"#//apple_ref/doc/uid/TP40007874-CH6-SW7\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_10";return this.s_oc?this.s_oc(e):true\">Table 5-1</a></span>.) Because this paragraph is the second instance of the <code>p</code> element on this page (<code>[1]</code> in a 0-based index), the node represents this paragraph. As you hover over the node, its position on the page is visibly highlighted. You can expand the node to see its contents, and even press Command-C to copy it to your clipboard.</p><section><a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW5\" title=\"Command-Line API\"></a><h2 class=\"jump\">Command-Line API</h2><p>You can inspect HTML nodes and JavaScript objects in more detail by using the console commands listed in <span class=\"content_text\">Table 5-1</span>. Type the command-line APIs interactively within the console.</p><p>If your scripts share the same function name as a Command-Line API function, the function in your scripts takes precedence.</p><a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW7\" title=\"Table 5-1Commands available in the Web Inspector console\"></a><div class=\"tableholder\"><table class=\"graybox\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\"><caption class=\"tablecaption\"><strong class=\"caption_number\">Table 5-1</strong> Commands available in the Web Inspector console</caption><tbody><tr><th scope=\"col\" class=\"TableHeading_TableRow_TableCell\"><p>Command</p></th><th scope=\"col\" class=\"TableHeading_TableRow_TableCell\"><p>Description</p></th></tr><tr><td scope=\"row\"><p><code>$(</code><em>selector</em><code>)</code></p></td><td><p>Shorthand for <code>document.querySelector</code>.</p></td></tr><tr><td scope=\"row\"><p><code>$$(</code><em>selector</em><code>)</code></p></td><td><p>Shorthand for <code>document.querySelectorAll</code>.</p></td></tr><tr><td scope=\"row\"><p><code>$x(</code><em>xpath</em><code>)</code></p></td><td><p>Returns an array of elements that match the given <span class=\"content_text\"><a href=\"http://web.archive.org/web/20170322101551/http://www.w3.org/TR/xpath/\" class=\"urlLink\" rel=\"external\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/http://www.w3.org/TR/xpath/_1";return this.s_oc?this.s_oc(e):true\">XPath</a></span> expression.</p></td></tr><tr><td scope=\"row\"><p><code>$0</code></p></td><td><p>Represents the currently selected node in the content browser.</p></td></tr><tr><td scope=\"row\"><p><code>$</code><em>1..4</em></p></td><td><p>Represents the last, second to last, third to last, and fourth to last selected node in the content browser, respectively. </p></td></tr><tr><td scope=\"row\"><p><code>$_</code></p></td><td><p>Returns the value of the last evaluated expression.</p></td></tr><tr><td scope=\"row\"><p><code>dir(</code><em>object</em><code>)</code></p></td><td><p>Prints all the properties of the object.</p></td></tr><tr><td scope=\"row\"><p><code>dirxml(</code><em>object</em><code>)</code></p></td><td><p>Prints all the properties of the object. If the object is a node, prints the node and all child nodes.</p></td></tr><tr><td scope=\"row\"><p><code>keys(</code><em>object</em><code>)</code></p></td><td><p>Prints an array of the names of the object’s own properties.</p></td></tr><tr><td scope=\"row\"><p><code>values(</code><em>object</em><code>)</code></p></td><td><p>Prints an array of the values of the object’s own properties.</p></td></tr><tr><td scope=\"row\"><p><code>profile(</code><em>[title]</em><code>)</code></p></td><td><p>Starts the JavaScript profiler. The optional argument <code>title</code> contains the string to be printed in the header of the profile report. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Instruments/Instruments.html#//apple_ref/doc/uid/TP40007874-CH4-SW7\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_11";return this.s_oc?this.s_oc(e):true\">JavaScript and Events Recording</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>profileEnd()</code></p></td><td><p>Stops the JavaScript profiler and prints its report. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Instruments/Instruments.html#//apple_ref/doc/uid/TP40007874-CH4-SW7\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_12";return this.s_oc?this.s_oc(e):true\">JavaScript and Events Recording</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>getEventListeners(</code><em>object</em><code>)</code></p></td><td><p>Prints an object containing the object’s attached event listeners.</p></td></tr><tr><td scope=\"row\"><p><code>monitorEvents(</code><em>object[, types]</em><code>)</code></p></td><td><p>Starts logging all events dispatched to the given object. The optional argument <code>types</code> defines specific events or event types to log, such as “click”.</p></td></tr><tr><td scope=\"row\"><p><code>unmonitorEvents(</code><em>object[, types]</em><code>)</code></p></td><td><p>Stops logging for all events dispatched to the given object. The optional argument <code>types</code> defines specific events or event types to stop logging, such as “click”.</p></td></tr><tr><td scope=\"row\"><p><code>inspect(</code><em>object</em><code>)</code></p></td><td><p>Inspects the given object; this is the same as clicking the Inspect button.</p></td></tr><tr><td scope=\"row\"><p><code>copy(</code><em>object</em><code>)</code></p></td><td><p>Copies the given object to the clipboard.</p></td></tr><tr><td scope=\"row\"><p><code>clear()</code></p></td><td><p>Clears the console.</p></td></tr></tbody></table></div><p>The functions listed in <span class=\"content_text\">Table 5-1</span> are regular JavaScript functions that are part of the Web Inspector environment. That means you can use them as you would any JavaScript function. For example, you can assign a chain of Console API commands to a variable to create a useful shorthand. <span class=\"content_text\">Listing 5-1</span> shows how you can quickly see all event types attached to the selected node.</p><a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW6\" title=\"Listing 5-1Find the events attached to this element\"></a><p class=\"codesample clear\"><strong class=\"caption_number\">Listing 5-1</strong> Find the events attached to this element</p><div class=\"codesample clear\"><table><tbody><tr><td scope=\"row\"><pre>var evs = function () {<span></span></pre></td></tr><tr><td scope=\"row\"><pre> return keys(getEventListeners($0));<span></span></pre></td></tr><tr><td scope=\"row\"><pre>};<span></span></pre></td></tr></tbody></table></div><p>After defining this function, inspect the magnifying glass in the top-right corner of this webpage, and type <code>evs()</code> in the console. An array containing the string “click” is returned, because there is a click event listener attached to that element.</p><p>Of course, these functions shouldn’t be included in your website’s JavaScript files because they are not available in the browser environment. Only use these functions in the Web Inspector console. Console functions you can include in your scripts are described in <span class=\"content_text\"><a href=\"#//apple_ref/doc/uid/TP40007874-CH6-SW3\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_13";return this.s_oc?this.s_oc(e):true\">Console API</a></span>.</p></section><section><a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW3\" title=\"Console API\"></a><h2 class=\"jump\">Console API</h2><p>You can output messages to the console, add markers to the timeline, and control the debugger directly from your scripts by using the commands listed in <span class=\"content_text\">Table 5-2</span>.</p><div class=\"importantbox clear\"><aside><a name=\"//apple_ref/doc/uid/TP40007874-CH6-DontLinkElementID_5\" title=\"Important\"></a><p><strong>Important:</strong> These functions exist to aid development and should not be included in any of your production JavaScript.</p><p></p></aside></div><a name=\"//apple_ref/doc/uid/TP40007874-CH6-SW8\" title=\"Table 5-2JavaScript functions available in the Console API\"></a><div class=\"tableholder\"><table class=\"graybox\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\"><caption class=\"tablecaption\"><strong class=\"caption_number\">Table 5-2</strong> JavaScript functions available in the Console API</caption><tbody><tr><th scope=\"col\" class=\"TableHeading_TableRow_TableCell\"><p>Function</p></th><th scope=\"col\" class=\"TableHeading_TableRow_TableCell\"><p>Description</p></th></tr><tr><td scope=\"row\"><p><code>console.assert(expression, object)</code></p></td><td><p>Asserts whether the given expression is true. If the assertion fails, prints the error and increments the number of errors in the activity viewer. If the assertion succeeds, prints nothing.</p></td></tr><tr><td scope=\"row\"><p><code>console.clear()</code></p></td><td><p>Clears the console.</p></td></tr><tr><td scope=\"row\"><p><code>console.count([title])</code></p></td><td><p>Prints the number of times this line has been called.</p></td></tr><tr><td scope=\"row\"><p><code>console.debug(object)</code></p></td><td><p>Alias of <code>console.log()</code>.</p></td></tr><tr><td scope=\"row\"><p><code>console.dir(object)</code></p></td><td><p>Prints the properties and values of the object.</p></td></tr><tr><td scope=\"row\"><p><code>console.dirxml(node)</code></p></td><td><p>Prints the DOM tree of an HTML or XML node.</p></td></tr><tr><td scope=\"row\"><p><code>console.error(object)</code></p></td><td><p>Prints a message to the console with the error icon. Increments the number of errors shown in the activity viewer.</p></td></tr><tr><td scope=\"row\"><p><code>console.group([title])</code></p></td><td><p>Prints subsequent logs under a disclosure of the given title.</p></td></tr><tr><td scope=\"row\"><p><code>console.groupEnd()</code></p></td><td><p>Ends the previously declared console grouping.</p></td></tr><tr><td scope=\"row\"><p><code>console.info(object)</code></p></td><td><p>Alias of <code>console.log()</code>.</p></td></tr><tr><td scope=\"row\"><p><code>console.log(object)</code></p></td><td><p>Prints the object to the console with the log icon. Increments the number of logs shown in the activity viewer.</p></td></tr><tr><td scope=\"row\"><p><code>console.markTimeline(</code><em>label</em><code>)</code></p></td><td><p>Marks the Timeline with a green vertical dashed line that indicates when this line of code was called. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Instruments/Instruments.html#//apple_ref/doc/uid/TP40007874-CH4-SW2\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_14";return this.s_oc?this.s_oc(e):true\">Recording Timelines</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>console.profile(</code><em>[title]</em><code>)</code></p></td><td><p>Starts the JavaScript profiler. The optional argument <code>title</code> contains the string to be printed in the header of the profile report. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Instruments/Instruments.html#//apple_ref/doc/uid/TP40007874-CH4-SW7\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_15";return this.s_oc?this.s_oc(e):true\">JavaScript and Events Recording</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>console.profileEnd(</code><em>[title]</em><code>)</code></p></td><td><p>Stops the JavaScript profiler and prints its report. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Instruments/Instruments.html#//apple_ref/doc/uid/TP40007874-CH4-SW7\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_16";return this.s_oc?this.s_oc(e):true\">JavaScript and Events Recording</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>console.time(</code><em>name</em><code>)</code></p></td><td><p>Starts a timer associated with the given name. Useful for timing the duration of segments of code.</p></td></tr><tr><td scope=\"row\"><p><code>console.timeEnd(</code><em>name</em><code>)</code></p></td><td><p>Stops the timer associated with the given name and prints the elapsed time to the console.</p></td></tr><tr><td scope=\"row\"><p><code>console.trace()</code></p></td><td><p>Prints a stack trace at the moment the function is called. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Debugger/Debugger.html#//apple_ref/doc/uid/TP40007874-CH5-SW6\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_17";return this.s_oc?this.s_oc(e):true\">Figure 4-2</a></span>.</p></td></tr><tr><td scope=\"row\"><p><code>console.warn(</code><em>object</em><code>)</code></p></td><td><p>Prints a message to the console with the warning icon. Increments the number of warnings shown in the activity viewer.</p></td></tr><tr><td scope=\"row\"><p><code>debugger</code></p></td><td><p>Stops JavaScript execution at the current line. This is the equivalent of setting a breakpoint programmatically. See <span class=\"content_text\"><a href=\"/web/20170322101551/https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Debugger/Debugger.html#//apple_ref/doc/uid/TP40007874-CH5-SW2\" data-renderer-version=\"1\" onclick=\"s_objectID="http://web.archive.org/web/20170322101551/https://developer.apple.com/library/content/documentati_18";return this.s_oc?this.s_oc(e):true\">Breakpoints</a></span>.</p></td></tr></tbody></table></div></section>\n \n <div class=\"copyright\"><br><hr><div align=\"center\"><p class=\"content_text\" lang=\"en\" dir=\"ltr\"> Updated: 2016-09-13</p></div></div>\n\n <div id=\"pediaWindow\">\n <div id=\"pediaHeader\"></div>\n <div id=\"pediaBody\"></div>\n </div>\n </article>"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
55,641 |
<p>What is the best practice of Unicode processing in C++?</p>
|
[
{
"answer_id": 55650,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 7,
"selected": true,
"text": "is_alpha string"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5694/"
] |
55,677 |
<p>What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?</p>
<p>No legacy browser compatibility required, Safari, Opera and Firefox will do.</p>
|
[
{
"answer_id": 55723,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": -1,
"selected": false,
"text": " function onMouseClick(e) {\n var x = e.clientX;\n var y = e.clientY;\n }\n var canvas = dojo.byId(canvasId);\n dojo.connect(canvas,\"click\",onMouseClick);\n"
},
{
"answer_id": 4430498,
"author": "N4ppeL",
"author_id": 540725,
"author_profile": "https://Stackoverflow.com/users/540725",
"pm_score": 6,
"selected": false,
"text": "clientX clientY var x;\nvar y;\nif (e.pageX || e.pageY) { \n x = e.pageX;\n y = e.pageY;\n}\nelse { \n x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; \n y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; \n} \nx -= gCanvasElement.offsetLeft;\ny -= gCanvasElement.offsetTop;\n"
},
{
"answer_id": 5417934,
"author": "Aldekein",
"author_id": 162118,
"author_profile": "https://Stackoverflow.com/users/162118",
"pm_score": 4,
"selected": false,
"text": "clientX clientY function getCursorPosition(canvas, event) {\nvar x, y;\n\ncanoffset = $(canvas).offset();\nx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);\ny = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;\n\nreturn [x,y];\n}\n $(canvas).offset()"
},
{
"answer_id": 5932203,
"author": "Ryan Artecona",
"author_id": 671915,
"author_profile": "https://Stackoverflow.com/users/671915",
"pm_score": 8,
"selected": false,
"text": "canvas.offsetLeft/Top div position: relative offsetParent function relMouseCoords(event){\n var totalOffsetX = 0;\n var totalOffsetY = 0;\n var canvasX = 0;\n var canvasY = 0;\n var currentElement = this;\n\n do{\n totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;\n totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;\n }\n while(currentElement = currentElement.offsetParent)\n\n canvasX = event.pageX - totalOffsetX;\n canvasY = event.pageY - totalOffsetY;\n\n return {x:canvasX, y:canvasY}\n}\nHTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;\n coords = canvas.relMouseCoords(event);\ncanvasX = coords.x;\ncanvasY = coords.y;\n"
},
{
"answer_id": 9961416,
"author": "Cryptovirus",
"author_id": 1305768,
"author_profile": "https://Stackoverflow.com/users/1305768",
"pm_score": 4,
"selected": false,
"text": " HTMLCanvasElement.prototype.relMouseCoords = function (event) {\n var totalOffsetX = 0;\n var totalOffsetY = 0;\n var canvasX = 0;\n var canvasY = 0;\n var currentElement = this;\n\n do {\n totalOffsetX += currentElement.offsetLeft;\n totalOffsetY += currentElement.offsetTop;\n }\n while (currentElement = currentElement.offsetParent)\n\n canvasX = event.pageX - totalOffsetX;\n canvasY = event.pageY - totalOffsetY;\n\n // Fix for variable canvas width\n canvasX = Math.round( canvasX * (this.width / this.offsetWidth) );\n canvasY = Math.round( canvasY * (this.height / this.offsetHeight) );\n\n return {x:canvasX, y:canvasY}\n}\n"
},
{
"answer_id": 12114213,
"author": "mafafu",
"author_id": 1296226,
"author_profile": "https://Stackoverflow.com/users/1296226",
"pm_score": 5,
"selected": false,
"text": "function getRelativeCoords(event) {\n return { x: event.offsetX, y: event.offsetY };\n}\n function getRelativeCoords(event) {\n return { x: event.offsetX || event.layerX, y: event.offsetY || event.layerY };\n}\n"
},
{
"answer_id": 17178241,
"author": "Simon Hi",
"author_id": 2458202,
"author_profile": "https://Stackoverflow.com/users/2458202",
"pm_score": 0,
"selected": false,
"text": "function myGetPxStyle(e,p)\n{\n var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:\"\";\n return parseFloat(r);\n}\n\nfunction myGetClick=function(ev)\n{\n // {x:ev.layerX,y:ev.layerY} doesn't work when zooming with mac chrome 27\n // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21\n // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad\n // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)\n // html.offsetX and html.offsetY don't work with mac firefox 21\n\n var offsetX=0,offsetY=0,e=this,x,y;\n var htmls=document.getElementsByTagName(\"html\"),html=(htmls?htmls[0]:0);\n\n do\n {\n offsetX+=e.offsetLeft-e.scrollLeft;\n offsetY+=e.offsetTop-e.scrollTop;\n } while (e=e.offsetParent);\n\n if (html)\n {\n offsetX+=myGetPxStyle(html,\"marginLeft\");\n offsetY+=myGetPxStyle(html,\"marginTop\");\n }\n\n x=ev.pageX-offsetX-document.body.scrollLeft;\n y=ev.pageY-offsetY-document.body.scrollTop;\n return {x:x,y:y};\n}\n"
},
{
"answer_id": 17401918,
"author": "FraZer",
"author_id": 2515750,
"author_profile": "https://Stackoverflow.com/users/2515750",
"pm_score": 3,
"selected": false,
"text": " <canvas id=\"myCanvas\" width=\"578\" height=\"200\"></canvas>\n<script>\n function writeMessage(canvas, message) {\n var context = canvas.getContext('2d');\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.font = '18pt Calibri';\n context.fillStyle = 'black';\n context.fillText(message, 10, 25);\n }\n function getMousePos(canvas, evt) {\n var rect = canvas.getBoundingClientRect();\n return {\n x: evt.clientX - rect.left,\n y: evt.clientY - rect.top\n };\n }\n var canvas = document.getElementById('myCanvas');\n var context = canvas.getContext('2d');\n\n canvas.addEventListener('mousemove', function(evt) {\n var mousePos = getMousePos(canvas, evt);\n var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;\n writeMessage(canvas, message);\n }, false);\n"
},
{
"answer_id": 17418121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<style type=\"text/css\">\n\n #canvas{background-color: #000;}\n\n</style>\n\n<script type=\"text/javascript\">\n\n document.addEventListener(\"DOMContentLoaded\", init, false);\n\n function init()\n {\n var canvas = document.getElementById(\"canvas\");\n canvas.addEventListener(\"mousedown\", getPosition, false);\n }\n\n function getPosition(event)\n {\n var x = new Number();\n var y = new Number();\n var canvas = document.getElementById(\"canvas\");\n\n if (event.x != undefined && event.y != undefined)\n {\n x = event.x;\n y = event.y;\n }\n else // Firefox method to get the position\n {\n x = event.clientX + document.body.scrollLeft +\n document.documentElement.scrollLeft;\n y = event.clientY + document.body.scrollTop +\n document.documentElement.scrollTop;\n }\n\n x -= canvas.offsetLeft;\n y -= canvas.offsetTop;\n\n alert(\"x: \" + x + \" y: \" + y);\n }\n\n</script>\n"
},
{
"answer_id": 18053642,
"author": "patriques",
"author_id": 931738,
"author_profile": "https://Stackoverflow.com/users/931738",
"pm_score": 9,
"selected": true,
"text": "function getCursorPosition(canvas, event) {\n const rect = canvas.getBoundingClientRect()\n const x = event.clientX - rect.left\n const y = event.clientY - rect.top\n console.log(\"x: \" + x + \" y: \" + y)\n}\n\nconst canvas = document.querySelector('canvas')\ncanvas.addEventListener('mousedown', function(e) {\n getCursorPosition(canvas, e)\n})\n"
},
{
"answer_id": 19740807,
"author": "user2310569",
"author_id": 2310569,
"author_profile": "https://Stackoverflow.com/users/2310569",
"pm_score": 1,
"selected": false,
"text": "var canvas = yourCanvasElement;\nvar mouseX = (event.clientX - (canvas.offsetLeft - canvas.scrollLeft)) - 2;\nvar mouseY = (event.clientY - (canvas.offsetTop - canvas.scrollTop)) - 2;\n"
},
{
"answer_id": 20310070,
"author": "Daniel Patru",
"author_id": 268040,
"author_profile": "https://Stackoverflow.com/users/268040",
"pm_score": 1,
"selected": false,
"text": " function mousePositionOnCanvas(e) {\n var el=e.target, c=el;\n var scaleX = c.width/c.offsetWidth || 1;\n var scaleY = c.height/c.offsetHeight || 1;\n\n if (!isNaN(e.offsetX)) \n return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };\n\n var x=e.pageX, y=e.pageY;\n do {\n x -= el.offsetLeft;\n y -= el.offsetTop;\n el = el.offsetParent;\n } while (el);\n return { x: x*scaleX, y: y*scaleY };\n }\n"
},
{
"answer_id": 20930829,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 0,
"selected": false,
"text": "function findPos(obj) {\n var curleft = 0, curtop = 0;\n if (obj.offsetParent) {\n do {\n curleft += obj.offsetLeft;\n curtop += obj.offsetTop;\n } while (obj = obj.offsetParent);\n return { x: curleft, y: curtop };\n }\n return undefined;\n}\n $('#canvas').mousemove(function(e) {\n var pos = findPos(this);\n var x = e.pageX - pos.x;\n var y = e.pageY - pos.y;\n var coordinateDisplay = \"x=\" + x + \", y=\" + y;\n writeCoordinateDisplay(coordinateDisplay);\n});\n findPos offsetLeft offsetTop offsetParent div canvas body e.pageX e.pageY e.layerX e.layerY"
},
{
"answer_id": 27204937,
"author": "Tomáš Zato",
"author_id": 607407,
"author_profile": "https://Stackoverflow.com/users/607407",
"pm_score": 3,
"selected": false,
"text": "HTMLElement.getBoundingClientRect scrollTop /* Returns pixel coordinates according to the pixel that's under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n var x,y;\n //This is the current screen rectangle of canvas\n var rect = this.getBoundingClientRect();\n var top = rect.top;\n var bottom = rect.bottom;\n var left = rect.left;\n var right = rect.right;\n //Recalculate mouse offsets to relative offsets\n x = event.clientX - left;\n y = event.clientY - top;\n //Also recalculate offsets of canvas is stretched\n var width = right - left;\n //I use this to reduce number of calculations for images that have normal size \n if(this.width!=width) {\n var height = bottom - top;\n //changes coordinates by ratio\n x = x*(this.width/width);\n y = y*(this.height/height);\n } \n //Return as an array\n return [x,y];\n}\n /* Returns pixel coordinates according to the pixel that's under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n var x,y;\n //This is the current screen rectangle of canvas\n var rect = this.getBoundingClientRect();\n var top = rect.top;\n var bottom = rect.bottom;\n var left = rect.left;\n var right = rect.right;\n //Subtract border size\n // Get computed style\n var styling=getComputedStyle(this,null);\n // Turn the border widths in integers\n var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);\n var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);\n var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);\n var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);\n //Subtract border from rectangle\n left+=leftBorder;\n right-=rightBorder;\n top+=topBorder;\n bottom-=bottomBorder;\n //Proceed as usual\n ...\n}\n prototype (canvas, event) this canvas"
},
{
"answer_id": 34781170,
"author": "Sarsaparilla",
"author_id": 226844,
"author_profile": "https://Stackoverflow.com/users/226844",
"pm_score": 2,
"selected": false,
"text": "$(canvas).click(function(jqEvent) {\n var coords = {\n x: jqEvent.pageX - $(canvas).offset().left,\n y: jqEvent.pageY - $(canvas).offset().top\n };\n});\n var logicalCoords = {\n x: coords.x * (canvas.width / $(canvas).width()),\n y: coords.y * (canvas.height / $(canvas).height())\n}\n"
},
{
"answer_id": 37790303,
"author": "Aniket Betkikar",
"author_id": 5275732,
"author_profile": "https://Stackoverflow.com/users/5275732",
"pm_score": 0,
"selected": false,
"text": "var x = event.offsetX == undefined ? event.layerX : event.offsetX;\nvar y = event.offsetY == undefined ? event.layerY : event.offsetY;\n\nmouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;\nmouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;\n"
},
{
"answer_id": 54356770,
"author": "bb216b3acfd8f72cbc8f899d4d6963",
"author_id": 5513988,
"author_profile": "https://Stackoverflow.com/users/5513988",
"pm_score": 0,
"selected": false,
"text": "function click(event) {\n const bound = event.target.getBoundingClientRect();\n\n const xMult = bound.width / can.width;\n const yMult = bound.height / can.height;\n\n return {\n x: Math.floor(event.offsetX / xMult),\n y: Math.floor(event.offsetY / yMult),\n };\n}\n"
},
{
"answer_id": 56205486,
"author": "gman",
"author_id": 128511,
"author_profile": "https://Stackoverflow.com/users/128511",
"pm_score": 4,
"selected": false,
"text": "offsetX offsetY canvas.addEventListner('mousemove', (e) => {\n const x = e.offsetX;\n const y = e.offsetY;\n});\n offsetX offsetY offsetX offsetY clientX clientY canvas.getBoundingClientRect canvas. getBoundingClientRect() clientX top clientY canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n});\n canvas.addEventListener('touchmove', (e) => {\n const rect = canvas. getBoundingClientRect();\n const x = e.touches[0].clientX - rect.left;\n const y = e.touches[0].clientY - rect.top;\n});\n canvas.getBoundingClientRect clientX clientY canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n const elementRelativeX = e.clientX - rect.left;\n const elementRelativeY = e.clientY - rect.top;\n const canvasRelativeX = elementRelativeX * canvas.width / rect.width;\n const canvasRelativeY = elementRelativeY * canvas.height / rect.height;\n});\n offsetX offsetY canvas.addEventListener('mousemove', (e) => {\n const elementRelativeX = e.offsetX;\n const elementRelativeY = e.offsetY;\n const canvasRelativeX = elementRelativeX * canvas.width / canvas.clientWidth;\n const canvasRelativeY = elementRelativeY * canvas.height / canvas.clientHeight;\n});\n event.offsetX event.offsetY [...document.querySelectorAll('canvas')].forEach((canvas) => {\n const ctx = canvas.getContext('2d');\n ctx.canvas.width = ctx.canvas.clientWidth;\n ctx.canvas.height = ctx.canvas.clientHeight;\n let count = 0;\n\n function draw(e, radius = 1) {\n const pos = {\n x: e.offsetX * canvas.width / canvas.clientWidth,\n y: e.offsetY * canvas.height / canvas.clientHeight,\n };\n document.querySelector('#debug').textContent = count;\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n ctx.fill();\n }\n\n function preventDefault(e) {\n e.preventDefault();\n }\n\n if (window.PointerEvent) {\n canvas.addEventListener('pointermove', (e) => {\n draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n });\n canvas.addEventListener('touchstart', preventDefault, {passive: false});\n canvas.addEventListener('touchmove', preventDefault, {passive: false});\n } else {\n canvas.addEventListener('mousemove', draw);\n canvas.addEventListener('mousedown', preventDefault);\n }\n});\n\nfunction hsl(h, s, l) {\n return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n} .scene {\n width: 200px;\n height: 200px;\n perspective: 600px;\n}\n\n.cube {\n width: 100%;\n height: 100%;\n position: relative;\n transform-style: preserve-3d;\n animation-duration: 16s;\n animation-name: rotate;\n animation-iteration-count: infinite;\n animation-timing-function: linear;\n}\n\n@keyframes rotate {\n from { transform: translateZ(-100px) rotateX( 0deg) rotateY( 0deg); }\n to { transform: translateZ(-100px) rotateX(360deg) rotateY(720deg); }\n}\n\n.cube__face {\n position: absolute;\n width: 200px;\n height: 200px;\n display: block;\n}\n\n.cube__face--front { background: rgba(255, 0, 0, 0.2); transform: rotateY( 0deg) translateZ(100px); }\n.cube__face--right { background: rgba(0, 255, 0, 0.2); transform: rotateY( 90deg) translateZ(100px); }\n.cube__face--back { background: rgba(0, 0, 255, 0.2); transform: rotateY(180deg) translateZ(100px); }\n.cube__face--left { background: rgba(255, 255, 0, 0.2); transform: rotateY(-90deg) translateZ(100px); }\n.cube__face--top { background: rgba(0, 255, 255, 0.2); transform: rotateX( 90deg) translateZ(100px); }\n.cube__face--bottom { background: rgba(255, 0, 255, 0.2); transform: rotateX(-90deg) translateZ(100px); } <div class=\"scene\">\n <div class=\"cube\">\n <canvas class=\"cube__face cube__face--front\"></canvas>\n <canvas class=\"cube__face cube__face--back\"></canvas>\n <canvas class=\"cube__face cube__face--right\"></canvas>\n <canvas class=\"cube__face cube__face--left\"></canvas>\n <canvas class=\"cube__face cube__face--top\"></canvas>\n <canvas class=\"cube__face cube__face--bottom\"></canvas>\n </div>\n</div>\n<pre id=\"debug\"></pre> canvas.getBoundingClientRect event.clientX event.clientY const canvas = document.querySelector('canvas');\nconst ctx = canvas.getContext('2d');\nctx.canvas.width = ctx.canvas.clientWidth;\nctx.canvas.height = ctx.canvas.clientHeight;\nlet count = 0;\n\nfunction draw(e, radius = 1) {\n const rect = canvas.getBoundingClientRect();\n const pos = {\n x: (e.clientX - rect.left) * canvas.width / canvas.clientWidth,\n y: (e.clientY - rect.top) * canvas.height / canvas.clientHeight,\n };\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n ctx.fill();\n}\n\nfunction preventDefault(e) {\n e.preventDefault();\n}\n\nif (window.PointerEvent) {\n canvas.addEventListener('pointermove', (e) => {\n draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n });\n canvas.addEventListener('touchstart', preventDefault, {passive: false});\n canvas.addEventListener('touchmove', preventDefault, {passive: false});\n} else {\n canvas.addEventListener('mousemove', draw);\n canvas.addEventListener('mousedown', preventDefault);\n}\n\nfunction hsl(h, s, l) {\n return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n} canvas { background: #FED; } <canvas width=\"400\" height=\"100\" style=\"width: 300px; height: 200px\"></canvas>\n<div>canvas deliberately has differnt CSS size vs drawingbuffer size</div>"
},
{
"answer_id": 56363476,
"author": "Divyanshu Rawat",
"author_id": 5763627,
"author_profile": "https://Stackoverflow.com/users/5763627",
"pm_score": 1,
"selected": false,
"text": " private captureEvents(canvasEl: HTMLCanvasElement) {\n\n this.drawingSubscription = fromEvent(canvasEl, 'mousedown')\n .pipe(\n switchMap((e: any) => {\n\n return fromEvent(canvasEl, 'mousemove')\n .pipe(\n takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {\n const prevPos = {\n x: null,\n y: null\n };\n })),\n\n takeUntil(fromEvent(canvasEl, 'mouseleave')),\n pairwise()\n )\n })\n )\n .subscribe((res: [MouseEvent, MouseEvent]) => {\n const rect = this.cx.canvas.getBoundingClientRect();\n const prevPos = {\n x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n };\n const currentPos = {\n x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n };\n\n this.coordinatesArray[this.file.current_slide - 1].push(prevPos);\n this.drawOnCanvas(prevPos, currentPos);\n });\n }\n const prevPos = {\n x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\nconst currentPos = {\n x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
55,692 |
<p>My background is primarily as a Java Developer, but lately I have been doing some work in .NET. So I have been trying to do some simple projects at home to get better at working with .NET. I have been able to transfer much of my Java experience into working with .NET (specifically C#), but the only thing that has really perplexed me is namespaces.</p>
<p>I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in .NET it does not and all the files reside in a single folder and the namespace is simply declared in each class.</p>
<p>I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in .NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate.</p>
<p>Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project?</p>
<p>Edit: As Blair pointed out this is pretty much the same question asked <a href="https://stackoverflow.com/questions/4664/should-the-folders-in-a-solution-match-the-namespace">here</a>.</p>
|
[
{
"answer_id": 55708,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 1,
"selected": false,
"text": "mycompany_getcurrentdate MYCGetCurrentDate java.lang.primitivewrapper.numeric.Integer"
},
{
"answer_id": 58265,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "DataPager System.Web.UI.WebControls"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3340/"
] |
55,709 |
<p>I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.</p>
<p>Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.</p>
<p>My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage?</p>
<p>I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.</p>
<p>Any thoughts would be appreciated. Thanks.</p>
|
[
{
"answer_id": 55788,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 7,
"selected": true,
"text": "ServletOutputStream out = response.getOutputStream();\nInputStream in = [ code to get source input stream ];\nString mimeType = [ code to get mimetype of data to be served ];\nbyte[] bytes = new byte[FILEBUFFERSIZE];\nint bytesRead;\n\nresponse.setContentType(mimeType);\n\nwhile ((bytesRead = in.read(bytes)) != -1) {\n out.write(bytes, 0, bytesRead);\n}\n\n// do the following in a finally block:\nin.close();\nout.close();\n"
},
{
"answer_id": 23252476,
"author": "blast_hardcheese",
"author_id": 743614,
"author_profile": "https://Stackoverflow.com/users/743614",
"pm_score": 4,
"selected": false,
"text": "import java.io.InputStream;\nimport java.io.OutputStream;\nimport org.apache.commons.io.IOUtils;\n\nInputStream in = null;\nOutputStream out = null;\n\ntry {\n in = object.getObjectContent();\n out = response.getOutputStream();\n IOUtils.copy(in, out);\n} finally {\n IOUtils.closeQuietly(in);\n IOUtils.closeQuietly(out);\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974/"
] |
55,713 |
<p>In effect, if I have a <code>class c</code> and instances of <code>$c1</code> and <code>$c2</code>
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that <code>$c1 == $c2?</code></p>
<p>Does anyone know an easy way to do this?</p>
|
[
{
"answer_id": 55731,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 1,
"selected": false,
"text": "class cat {\n private $name;\n public function __contruct($catname) {\n $this->name = $catname;\n }\n\n public function __toString() {\n return \"My name is \" . $this->name . \"\\n\";\n }\n}\n\n$max = new cat('max');\n$toby = new cat('toby');\nprint $max; // echoes 'My name is max'\nprint $toby; // echoes 'My name is toby'\n\nif($max == $toby) {\n echo 'Woohoo!\\n';\n} else {\n echo 'Doh!\\n';\n}\n"
},
{
"answer_id": 55811,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 0,
"selected": false,
"text": "class Validate {\n public function validateName($c1, $c2) {\n if($c1->FirstName == \"foo\" && $c2->LastName == \"foo\") {\n return true;\n } else if (// someother condition) {\n return // someval;\n } else {\n return false;\n }\n }\n\n public function validatePhoneNumber($c1, $c2) {\n // some code\n }\n}\n"
},
{
"answer_id": 56012,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "$class1 = new Class1();\n$class2 = new Class2();\n$class3 = new Class3();\n$class4 = new Class4();\n$class5 = new Class5();\n\necho ClassChecker::samePublicMethods($class1,$class2); //should be true\necho ClassChecker::samePublicMethods($class1,$class3); //should be false - different values\necho ClassChecker::samePublicMethods($class1,$class4); //should be false -- class3 contains extra public methods\necho ClassChecker::samePublicMethods($class1,$class5); //should be true -- class5 contains extra private methods\n\nclass ClassChecker {\n\n public static function samePublicMethods($class1, $class2) {\n\n $class1methods = array();\n\n $r = new ReflectionClass($class1);\n $methods = $r->getMethods();\n\n foreach($methods as $m) {\n if ($m->isPublic()) {\n @$result = call_user_method($m->getName(), $class1);\n $class1methods[$m->getName()] = $result;\n }\n }\n\n $r = new ReflectionClass($class2);\n $methods = $r->getMethods();\n\n foreach($methods as $m) {\n\n //only comparing public methods\n if ($m->isPublic()) {\n\n //public method doesn't match method in class1 so return false\n if(!isset($class1methods[$m->getName()])) {\n return false;\n }\n\n //public method of same name doesn't return same value so return false\n @$result = call_user_method($m->getName(), $class2);\n if ($class1methods[$m->getName()] !== $result) {\n return false;\n }\n }\n }\n\n return true;\n }\n}\n\n\nclass Class1 {\n\n private $b = 'bbb';\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n\n}\n\nclass Class2 {\n\n private $a = 'aaa';\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n}\n\nclass Class3 {\n\n private $c = 'ccc';\n\n public function one() {\n return 222;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n\n}\n\nclass Class4 {\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n public function three() {\n return true;\n }\n\n}\n\nclass Class5 {\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n private function three() {\n return true;\n }\n\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
55,720 |
<p>Here's my first question at SO.</p>
<p>I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. </p>
<p>The problem is the applications is <strong>very slow</strong>.</p>
<p>How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code.</p>
<p>I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. </p>
<p>Thoughts?</p>
|
[
{
"answer_id": 56754,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 0,
"selected": false,
"text": "$object->setMarker(\"name\");"
},
{
"answer_id": 15717173,
"author": "Fedir RYKHTIK",
"author_id": 634275,
"author_profile": "https://Stackoverflow.com/users/634275",
"pm_score": 2,
"selected": false,
"text": "$ php apd-test.php\n\n$ pprofp -l pprof.SOME_PID\n\nTrace for /Users/martin/develop/php/apd-test/apd-test.php\nTotal Elapsed Time = 0.12\nTotal System Time = 0.01\nTotal User Time = 0.07\n\n\n Real User System secs/ cumm\n%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name\n--------------------------------------------------------------------------------------\n71.3 0.06 0.06 0.05 0.05 0.01 0.01 10000 0.0000 0.0000 0 in_array\n27.3 0.02 0.09 0.02 0.07 0.00 0.01 10000 0.0000 0.0000 0 my_test_function\n 1.5 0.03 0.03 0.00 0.00 0.00 0.00 1 0.0000 0.0000 0 apd_set_pprof_trace\n 0.0 0.00 0.12 0.00 0.07 0.00 0.01 1 0.0000 0.0000 0 main\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983/"
] |
55,729 |
<p>How often should you use git-gc? </p>
<p>The <a href="http://www.kernel.org/pub/software/scm/git/docs/git-gc.html" rel="noreferrer">manual page</a> simply says:</p>
<blockquote>
<p>Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance.</p>
</blockquote>
<p>Are there some commands to get some object counts to find out whether it's time to gc?</p>
|
[
{
"answer_id": 18541285,
"author": "cregox",
"author_id": 274502,
"author_profile": "https://Stackoverflow.com/users/274502",
"pm_score": 4,
"selected": false,
"text": "This repository currently has approximately 1500 loose objects.\n $ git count-objects\n .git/objects tcl"
},
{
"answer_id": 22358144,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "gc.autodetach gc --auto gc output gc.autodetach pclouds gitster gc gc --auto gc --auto gc --auto stderr cmd_gc() gc --auto gc --auto gc stderr $GIT_DIR/gc.log gc --auto gc.log gc.log"
},
{
"answer_id": 57290082,
"author": "Immi",
"author_id": 4239669,
"author_profile": "https://Stackoverflow.com/users/4239669",
"pm_score": 2,
"selected": false,
"text": "git gc git gc git pull\ngit merge\ngit rebase\ngit commit\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
55,735 |
<p>I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects.</p>
<p>Does anyone know if this is possible without polling the document?</p>
|
[
{
"answer_id": 1033966,
"author": "Sebastian Bender",
"author_id": 96671,
"author_profile": "https://Stackoverflow.com/users/96671",
"pm_score": 2,
"selected": false,
"text": "public class AutoBrandSmartTag : SmartTag\n{\n Microsoft.Office.Interop.Word.Document cDoc;\n\n Microsoft.Office.Tools.Word.Action act = new Microsoft.Office.Tools.Word.Action(\"Test Action\");\n\n public AutoBrandSmartTag(AutoBrandEngine.AutoBrandEngine _engine, Microsoft.Office.Interop.Word.Document _doc)\n : base(\"AutoBrandTool.com/SmartTag#AutoBrandSmartTag\", \"AutoBrand SmartTag\")\n {\n this.cDoc = _doc;\n\n this.Actions = new Microsoft.Office.Tools.Word.Action[] { act };\n }\n\n protected override void Recognize(string text, Microsoft.Office.Interop.SmartTag.ISmartTagRecognizerSite site, \n Microsoft.Office.Interop.SmartTag.ISmartTagTokenList tokenList)\n {\n if (tokenList.Count < 1)\n return;\n\n int start = 0;\n int length = 0;\n int index = tokenList.Count > 1 ? tokenList.Count - 1 : 1;\n\n ISmartTagToken token = tokenList.get_Item(index);\n\n start = token.Start;\n length = token.Length;\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925/"
] |
55,754 |
<p>What is the best way, using Bash, to rename files in the form:</p>
<pre><code>(foo1, foo2, ..., foo1300, ..., fooN)
</code></pre>
<p>With zero-padded file names:</p>
<pre><code>(foo00001, foo00002, ..., foo01300, ..., fooN)
</code></pre>
|
[
{
"answer_id": 55775,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "for ((i=1; i<=N; i++)) ; do mv foo$i `printf foo%05d $i` ; done\n"
},
{
"answer_id": 55778,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\n# some test data\nfiles=\"foo1\nfoo2\nfoo100\nfoo200\nfoo9999\"\n\nfor f in $files; do\n prefix=`echo \"$f\" | cut -c 1-3` # chars 1-3 = \"foo\"\n number=`echo \"$f\" | cut -c 4-` # chars 4-end = the number\n printf \"%s%04d\\n\" \"$prefix\" \"$number\"\ndone\n"
},
{
"answer_id": 55782,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "N for f in foo[0-9]*; do\n mv \"$f\" \"$(printf 'foo%05d' \"${f#foo}\")\"\ndone\n"
},
{
"answer_id": 506377,
"author": "Fritz G. Mehner",
"author_id": 57457,
"author_profile": "https://Stackoverflow.com/users/57457",
"pm_score": 3,
"selected": false,
"text": "for file in foo*; do\n newnumber='00000'${file#foo} # get number, pack with zeros\n newnumber=${newnumber:(-5)} # the last five characters\n mv $file foo$newnumber # rename\ndone\n"
},
{
"answer_id": 3700146,
"author": "Michael Baltaks",
"author_id": 23312,
"author_profile": "https://Stackoverflow.com/users/23312",
"pm_score": 4,
"selected": false,
"text": "foo56.png foo00000055.png #!/bin/bash\n\nprefix=\"foo\"\npostfix=\".png\"\ntargetDir=\"../newframes\"\npaddingLength=8\n\nfor file in ${prefix}[0-9]*${postfix}; do\n # strip the prefix off the file name\n postfile=${file#$prefix}\n # strip the postfix off the file name\n number=${postfile%$postfix}\n # subtract 1 from the resulting number\n i=$((number-1))\n # copy to a new name with padded zeros in a new folder\n cp ${file} \"$targetDir\"/$(printf $prefix%0${paddingLength}d$postfix $i)\ndone\n"
},
{
"answer_id": 4561801,
"author": "KARASZI István",
"author_id": 221213,
"author_profile": "https://Stackoverflow.com/users/221213",
"pm_score": 6,
"selected": false,
"text": "rename rename 's/\\d+/sprintf(\"%05d\",$&)/e' foo*\n 's/\\d+/sprintf(\"%05d\",$&)/e' \\d+ sprintf(\"%05d\",$&) sprintf %05d"
},
{
"answer_id": 45569550,
"author": "Pioz",
"author_id": 302005,
"author_profile": "https://Stackoverflow.com/users/302005",
"pm_score": 3,
"selected": false,
"text": "ls * | cat -n | while read i f; do mv \"$f\" `printf \"PATTERN\" \"$i\"`; done\n %04d.${f#*.} photo_%04d.${f#*.} %04d.jpg photo_$(basename $f .${f#*.})_%04d.${f#*.} ls *.jpg | ... f i ls * | cat -n | while read i f; do mv \"$f\" `printf \"foo%d05\" \"$i\"`; done\n"
},
{
"answer_id": 54888706,
"author": "AntonAL",
"author_id": 235158,
"author_profile": "https://Stackoverflow.com/users/235158",
"pm_score": 1,
"selected": false,
"text": "for f in * ; do\n number=`echo $f | sed 's/[^0-9]*//g'`\n padded=`printf \"%04d\" $number`\n echo $f | sed \"s/${number}/${padded}/\";\ndone\n for f in * ; do ;done $f echo $f | sed $f sed sed 's/[^0-9]*//g' [^0-9]* ^ // [a-z] number number = … printf \"%04d\" $number sed s/substring/replacement/ ${number} for f in *.js ; do\n number=`echo $f | sed 's/[^0-9]*//g'`\n padded=`printf \"%04d\" $number`\n new_name=`echo $f | sed \"s/${number}/${padded}/\"`\n mv $f $new_name;\ndone\n"
},
{
"answer_id": 55409116,
"author": "Victoria Stuart",
"author_id": 1904943,
"author_profile": "https://Stackoverflow.com/users/1904943",
"pm_score": 3,
"selected": false,
"text": "$ ls -l\ntotal 0\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 010\n-rw-r--r-- 1 victoria victoria 0 Mar 28 18:09 050\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 050.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 10\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 1.zzz\n\n$ for f in [0-9]*.[a-z]*; do tmp=`echo $f | awk -F. '{printf \"%04d.%s\\n\", $1, $2}'`; mv \"$f\" \"$tmp\"; done;\n\n$ ls -l\ntotal 0\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 0001.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 0050.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 010\n-rw-r--r-- 1 victoria victoria 0 Mar 28 18:09 050\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 10\n for f in [0-9]*.[a-z]*; do tmp=`echo $f | \\\nawk -F. '{printf \"%04d.%s\\n\", $1, $2}'`; mv \"$f\" \"$tmp\"; done;\n `echo ... $2}\\` [0-9]*.[a-z]* $f awk -F. awk . $1 $2 printf $1 %04d $2 %s $tmp $f $tmp"
},
{
"answer_id": 69038695,
"author": "danday74",
"author_id": 1205871,
"author_profile": "https://Stackoverflow.com/users/1205871",
"pm_score": 1,
"selected": false,
"text": "for f in foo[0-9]*; do mv \"$f\" \"$(printf 'foo%05d' \"${f#foo}\" 2> /dev/null)\"; done; for f in foo[0-9]*; do mv \"$f\" \"$f.ext\"; done;\n foo1.ext > foo00001.ext\nfoo2.ext > foo00002.ext\nfoo1300.ext > foo01300.ext\n rm * 2> /dev/null; touch foo1.ext foo2.ext foo1300.ext; for f in foo[0-9]*; do mv \"$f\" \"$(printf 'foo%05d' \"${f#foo}\" 2> /dev/null)\"; done; for f in foo[0-9]*; do mv \"$f\" \"$f.ext\"; done;\n for f in foo[0-9]*;\n do mv \"$f\" \"$(printf 'foo%05d' \"${f#foo}\" 2> /dev/null)\";\ndone;\n\nfor f in foo[0-9]*;\n do mv \"$f\" \"$f.ext\";\ndone;\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3020/"
] |
55,757 |
<p>I have <code>buy.php</code> with a <strong>form</strong> where you enter <em>items, quantity, shipping data, etc.</em> </p>
<p>When you click the <strong>Submit button</strong>, it posts back to <code>buy.php</code> <code>($_SERVER['PHP_SELF'])</code> and does some data validation. </p>
<p>If there are fields missing or errors, they are highlighted. If everything is correct, I save the <code>$_POST</code> data in <code>$_SESSION</code> variables, then do a <code>header('Location: check.php')</code>, where I display the data so the buyer can check the info one last time before actually buying.</p>
<p>Now, if I'm in <code>check.php</code> and hit the Back button to <code>buy.php</code> so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that. </p>
<p><strong>Anyone have any good advice or good practices for PHP Multiform validation?</strong></p>
<p><strong>Also, if I had n pages for the user to fill, <code>buy.php, buy2.php, ... buyn.php</code> before check.php would the same ideas still hold?</strong></p>
|
[
{
"answer_id": 11230741,
"author": "FstaRocka",
"author_id": 1486271,
"author_profile": "https://Stackoverflow.com/users/1486271",
"pm_score": 1,
"selected": false,
"text": "redir redir ?m &m page.php?m elseif if (isset($_GET['m'])) {\n echo 'order placed.';\n}\nelse {\n //...\n}\n submit1 submit2 $_POST['submit1_x'] if (isset($_POST[submit1]) {\n //validate + save session data from form1\n //display form 2\n} else if(isset($_POST[submit2])) {\n //validate + save session data from form2\n //display form 3\n} else {\n //display first form\n //<input type=\"submit\" name=\"submit1\" value=\"Continue\">\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2542/"
] |
55,797 |
<p>A Visual Studio 2008 project in one solution needs to reference a WCF service in another VS 2008 solution on the same development machine. Does anybody have any suggestions on how best to accomplish this?</p>
|
[
{
"answer_id": 11230741,
"author": "FstaRocka",
"author_id": 1486271,
"author_profile": "https://Stackoverflow.com/users/1486271",
"pm_score": 1,
"selected": false,
"text": "redir redir ?m &m page.php?m elseif if (isset($_GET['m'])) {\n echo 'order placed.';\n}\nelse {\n //...\n}\n submit1 submit2 $_POST['submit1_x'] if (isset($_POST[submit1]) {\n //validate + save session data from form1\n //display form 2\n} else if(isset($_POST[submit2])) {\n //validate + save session data from form2\n //display form 3\n} else {\n //display first form\n //<input type=\"submit\" name=\"submit1\" value=\"Continue\">\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
55,828 |
<p>Is there a simple method of parsing XML files in C#? If so, what?</p>
|
[
{
"answer_id": 55831,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "XmlReader XPathNavigator"
},
{
"answer_id": 55834,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "XmlTextReader XmlReader XmlNodeReader System.Xml.XPath XPathNavigator XPathDocument XPathExpression XPathnodeIterator XPath"
},
{
"answer_id": 55836,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 3,
"selected": false,
"text": "XmlReader XmlTextReader XmlValidatingReader XPath XPathNavigator XmlDocument"
},
{
"answer_id": 55840,
"author": "Lukas Šalkauskas",
"author_id": 5369,
"author_profile": "https://Stackoverflow.com/users/5369",
"pm_score": 8,
"selected": false,
"text": "XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object\nxmlDoc.Load(\"yourXMLFile.xml\"); // Load the XML document from the specified file\n\n// Get elements\nXmlNodeList girlAddress = xmlDoc.GetElementsByTagName(\"gAddress\");\nXmlNodeList girlAge = xmlDoc.GetElementsByTagName(\"gAge\"); \nXmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName(\"gPhone\");\n\n// Display the results\nConsole.WriteLine(\"Address: \" + girlAddress[0].InnerText);\nConsole.WriteLine(\"Age: \" + girlAge[0].InnerText);\nConsole.WriteLine(\"Phone Number: \" + girlCellPhoneNumber[0].InnerText);\n"
},
{
"answer_id": 55891,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 6,
"selected": false,
"text": "XmlSerializer XmlSerializer XmlSerializer"
},
{
"answer_id": 55965,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 5,
"selected": false,
"text": "XmlReader XPathNavigator XElement XmlDocument XmlSerializer"
},
{
"answer_id": 42276676,
"author": "Wojtpl2",
"author_id": 4809321,
"author_profile": "https://Stackoverflow.com/users/4809321",
"pm_score": 1,
"selected": false,
"text": "Install-Package ExtendedXmlSerializer\n ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();\nvar obj = new Message();\nvar xml = serializer.Serialize(obj);\n var obj2 = serializer.Deserialize<Message>(xml);\n"
},
{
"answer_id": 45176663,
"author": "Tapan kumar",
"author_id": 1784941,
"author_profile": "https://Stackoverflow.com/users/1784941",
"pm_score": 2,
"selected": false,
"text": "System.Xml.Linq public CatSubCatList GenerateCategoryListFromProductFeedXML()\n{\n string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);\n\n XDocument xDoc = XDocument.Load(path);\n\n XElement xElement = XElement.Parse(xDoc.ToString());\n\n\n List<Category> lstCategory = xElement.Elements(\"Product\").Select(d => new Category\n {\n Code = Convert.ToString(d.Element(\"CategoryCode\").Value),\n CategoryPath = d.Element(\"CategoryPath\").Value,\n Name = GetCateOrSubCategory(d.Element(\"CategoryPath\").Value, 0), // Category\n SubCategoryName = GetCateOrSubCategory(d.Element(\"CategoryPath\").Value, 1) // Sub Category\n }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();\n\n CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);\n\n return catSubCatList;\n}\n"
},
{
"answer_id": 46790003,
"author": "Joel Harkes",
"author_id": 1275832,
"author_profile": "https://Stackoverflow.com/users/1275832",
"pm_score": 3,
"selected": false,
"text": "XmlDocument doc = new XmlDocument();\ndoc.Load(\"test.xml\");\n\nvar found = doc.DocumentElement.SelectNodes(\"//book[@title='Barry Poter']\"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'\n\n// Retrieve your data here or change XML here:\nforeach (XmlNode book in nodeList)\n{\n book.InnerText=\"The story began as it was...\";\n}\n\nConsole.WriteLine(\"Display XML:\");\ndoc.Save(Console.Out);\n"
},
{
"answer_id": 48951398,
"author": "PJRobot",
"author_id": 2742811,
"author_profile": "https://Stackoverflow.com/users/2742811",
"pm_score": 4,
"selected": false,
"text": "public void ParseXML(string filePath) \n{ \n // create document instance using XML file path\n XDocument doc = XDocument.Load(filePath);\n\n // get the namespace to that within of the XML (xmlns=\"...\")\n XElement root = doc.Root;\n XNamespace ns = root.GetDefaultNamespace();\n\n // obtain a list of elements with specific tag\n IEnumerable<XElement> elements = from c in doc.Descendants(ns + \"exampleTagName\") select c;\n\n // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc\n XElement element = (from c in doc.Descendants(ns + \"exampleTagName\" select c).First();\n\n // obtain an element from within an element, same as from doc\n XElement embeddedElement = (from c in element.Descendants(ns + \"exampleEmbeddedTagName\" select c).First();\n\n // obtain an attribute from an element\n XAttribute attribute = element.Attribute(\"exampleAttributeName\");\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4361/"
] |
55,843 |
<p>I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current <code>IQueryable</code> result instance has been executed or not.</p>
<p>The debugger knows that my <code>IQueryable</code> has not been <em>'invoked'</em> because it tells me that expanding the Results property will <em>'enumerate'</em> it. Is there a way for me to programmatically identify that as well.</p>
<p>I hope that makes sense :)</p>
|
[
{
"answer_id": 81740,
"author": "Mark Pattison",
"author_id": 15519,
"author_profile": "https://Stackoverflow.com/users/15519",
"pm_score": 0,
"selected": false,
"text": "DataContext.Log = Console.Out .ToList"
},
{
"answer_id": 85732,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 3,
"selected": true,
"text": "class QueryableWrapper<T> : IQueryable<T>\n{\n private IQueryable<T> _InnerQueryable;\n private bool _HasExecuted;\n\n public QueryableWrapper(IQueryable<T> innerQueryable)\n {\n _InnerQueryable = innerQueryable;\n }\n\n public bool HasExecuted\n {\n get\n {\n return _HasExecuted;\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n _HasExecuted = true;\n\n return _InnerQueryable.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public Type ElementType\n {\n get { return _InnerQueryable.ElementType; }\n }\n\n public System.Linq.Expressions.Expression Expression\n {\n get { return _InnerQueryable.Expression; }\n }\n\n public IQueryProvider Provider\n {\n get { return _InnerQueryable.Provider; }\n }\n}\n var query = new QueryableWrapper<string>(\n from str in myDataSource\n select str);\n\nDebug.WriteLine(\"HasExecuted: \" + query.HasExecuted.ToString());\n\nforeach (string str in query)\n{\n Debug.WriteLine(str);\n}\n\nDebug.WriteLine(\"HasExecuted: \" + query.HasExecuted.ToString());\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
] |
55,855 |
<p>I am following the <a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx" rel="noreferrer">M-V-VM</a> pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.</p>
<p>Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?</p>
|
[
{
"answer_id": 56081,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "private void _textBox_TextChanged(object sender, EventArgs e)\n{\n MyCommand.Execute(null);\n}\n TextBox"
},
{
"answer_id": 56164,
"author": "Samuel Jack",
"author_id": 1727,
"author_profile": "https://Stackoverflow.com/users/1727",
"pm_score": 5,
"selected": true,
"text": "<TextBox\n x:Name=\"MyTextBox\"\n TextBoxBehaviours.TextChangedCommand=\"{Binding ViewModelTextChangedCommand}\" />\n"
},
{
"answer_id": 56191,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 3,
"selected": false,
"text": "<TextBox Text=\"{Binding WorldName}\"/>\n....\npublic string WorldName\n{\n get\n {\n return WorldData.Name;\n }\n set\n {\n WorldData.Name = value;\n OnPropertyChanged(\"WorldName\");\n // CallYourCustomFunctionHere();\n }\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
55,859 |
<p>In C++, I'm trying to catch all types of exceptions in one catch (like <code>catch(Exception)</code> in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?</p>
|
[
{
"answer_id": 55863,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": true,
"text": "catch (...)\n{\n // Handle exceptions not covered.\n}\n"
},
{
"answer_id": 55865,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "class WidgetError\n : public std::exception\n{\npublic:\n WidgetError()\n { }\n\n virtual ~WidgetError() throw()\n { }\n\n virtual const char *what() const throw()\n {\n return \"You got you a widget error!\";\n }\n};\n"
},
{
"answer_id": 55866,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": -1,
"selected": false,
"text": "try\n{\n // some code\n}\ncatch(...)\n{\n // catch anything\n}\n"
},
{
"answer_id": 56274,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "catch (...) { /* code here */ } void myfunc()\n{\n void* h = get_handle_that_must_be_released();\n try { random_func(h); }\n catch (...) { release_object(h); throw; }\n release_object(h);\n\n}\n #include<boost/shared_ptr.hpp>\n\nvoid my_func()\n{\n boost::shared_ptr<void> h(get_handle_that_must_be_released(), release_object);\n random_func(h.get());\n}\n"
},
{
"answer_id": 57088,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "void myTranslator(unsigned code, EXCEPTION_POINTERS*)\n{\n throw std::exception(<appropriate string here>);\n}\n\n_set_se_translator(myTranslator);\n"
},
{
"answer_id": 58223526,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 0,
"selected": false,
"text": "catch(...) catch(...) try\n{ \n try\n { \n // do something that can produce various exception types\n }\n catch( const CustomExceptionA &e ){ throw e; } \\\n catch( const CustomExceptionB &e ){ throw CustomExceptionA( e ); } \\\n catch( const std::exception &e ) { throw CustomExceptionA( e ); } \\\n catch( ... ) { throw CustomExceptionA(); } \\\n} \ncatch( const CustomExceptionA &e ) \n{\n // Handle any exception as CustomExceptionA\n}\n"
}
] |
2008/09/11
|
[
"https://Stackoverflow.com/questions/55859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.